You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "hughhhh (via GitHub)" <gi...@apache.org> on 2026/09/04 13:57:06 UTC
[PR] feat(explore): indicate when a filter is mirrored onto a partition column [superset]
hughhhh opened a new pull request, #43870:
URL: https://github.com/apache/superset/pull/43870
### SUMMARY
Sixth and last of the partition filter mapping stack, implementing **wireframe 1d** — the piece that tells a chart author *why* their query got faster.
Stacked on `hughhhh/pfm-5-editor-ui`. Review the [compare against pfm-5](https://github.com/apache/superset/compare/hughhhh/pfm-5-editor-ui...hughhhh/pfm-6-explore-indicator) rather than the diff against master.
A small glyph appears on any filter whose column the dataset mirrors onto its partition column, with the tooltip *"This filter is also applied to a partition column for faster queries. See 'View query' for the generated SQL."* Chart authors configure nothing and ideally never learn the word "partition"; per the PRD the indicator exists only to explain the speed-up and point at the SQL.
**Where it renders.** Explore models the time range as a `TEMPORAL_RANGE` adhoc filter, so the time range and ordinary filters are the same chip — one indicator covers both cases from 1d. The path that actually renders is `DndAdhocFilterOption` → `OptionWrapper` → `Option`; `OptionControlLabel` and the legacy `AdhocFilterOption` are wired too, so the glyph does not silently vanish on whichever surface uses them. The standalone `time_range` control gets the mapping through a new `mapStateToProps`, for viz types that still have one.
**Naming.** `partitionColumn` already exists on these components as the unrelated Presto `latest_partition` feature, so this is `partitionMapping` throughout to avoid two meanings of the same word one prop apart.
**Also fixes a bug this made visible.** `partition_filter_mapping_summary` was not gated on the feature flag, so with `PARTITION_FILTER_MAPPING` off the payload still reported `active: true`. Nothing is mirrored in that state — `resolve_partition_mapping` returns `None` — so the indicator was promising a predicate the query never carried. The summary now gates the same way the query path does. The bug has been in the stack since pfm-1; it was invisible until something rendered from it, which is exactly what this PR does.
### BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
_Attaching separately: `08-1d-explore-indicator.png` — the glyph on the `event_time` time-range chip with its tooltip open, and no glyph on the `country` dimension or `SUM(revenue)` metric._
### TESTING INSTRUCTIONS
Automated: 821 backend and 837 frontend tests pass; `tsc`, `ruff`, `ruff format` and `oxlint` clean.
Manually, on top of a dataset configured per pfm-5 (mapping `event_time → dt_epoch`, active):
1. Open a chart on that dataset with a time-range filter.
2. The **Filters** chip `2026-07-01 ≤ event_time < 2026-08-01` carries a small green filter glyph; the `country` dimension and `SUM(revenue)` metric do not.
3. Hover the glyph → *"This filter is also applied to a partition column for faster queries. See 'View query' for the generated SQL."*
4. Open **View query** and confirm the `dt_epoch` predicates the tooltip is referring to.
5. Set `PARTITION_FILTER_MAPPING: False` and reload: the Explore payload serializes `partition_filter_mapping` as `null` and no glyph renders.
Verified end-to-end against a real partitioned Postgres table in Docker, including the flag-off case.
### Deviation from the mockup
1d shows the tooltip ending in a clickable **View generated SQL →** link. This ships as static text pointing at *View query* instead: the tooltip hangs off a small hover glyph, so reaching a link inside it means traversing from the icon without dismissing the tooltip, and the View query action lives in the chart's `⋯` menu rather than anywhere the control panel can reach without new plumbing. Happy to add the link if the interaction is worth the wiring.
### ADDITIONAL INFORMATION
- [ ] Has associated issue:
- [x] Required feature flags: `PARTITION_FILTER_MAPPING`
- [x] Changes UI
- [ ] Includes DB Migration (follow approval process in [SIP-59](https://github.com/apache/superset/issues/13351))
- [ ] Migration is atomic, supports rollback & is backwards-compatible
- [ ] Confirm DB migration upgrade and downgrade tested
- [ ] Runtime estimates and downtime expectations provided
- [x] Introduces new feature or API
- [ ] Removes existing feature or API
🤖 Generated with [Claude Code](https://claude.com/claude-code)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4288257702
##########
superset/commands/dataset/importers/v0.py:
##########
@@ -291,7 +319,151 @@ def run(self) -> None:
.one()
)
dataset["database_id"] = database.id
- SqlaTable.import_from_dict(dataset, sync=self.sync)
+ self._prepare_partition_mapping(dataset, database)
+ table = SqlaTable.import_from_dict(dataset, sync=self.sync)
+ if table is not None:
+ imported.append(table)
+
+ self._repair_partition_mappings(imported)
+
+ @classmethod
+ def _default_omitted_monotonic_declarations(cls, config: Any) -> None:
+ """
+ Materialize `partition_transform_is_monotonic` wherever a transform is
+ set, anywhere in a v0 config.
+
+ The v1 importer does this on its own raw config, and for the same
+ reason: an overwrite keeps whatever the bundle omits, including a
+ ``True`` left behind by the transform this bundle is replacing. A
+ non-monotonic transform declared monotonic enables range mirrors that
+ exclude rows the filter keeps -- ``abs(:value)`` inheriting a stored
+ ``True`` turns ``n >= -1`` into ``p >= 1`` and misses ``n = 0``.
+
+ Walked rather than addressed directly because a v0 bundle comes in two
+ shapes: a CLI export nests datasets under ``databases[].tables[]``,
+ while a UI export is a bare list of datasets. Only columns that supply
+ a transform are touched, so a re-import that says nothing about a
+ column stays idempotent.
+ """
+ if isinstance(config, list):
+ for entry in config:
+ cls._default_omitted_monotonic_declarations(entry)
+ return
+ if not isinstance(config, dict):
+ return
+ _default_omitted_monotonic_declarations(config.get("columns") or [])
+ for key in (DATABASES_KEY, "tables"):
+ for child in config.get(key) or []:
+ cls._default_omitted_monotonic_declarations(child)
+
+ @staticmethod
+ def _prepare_partition_mapping(
+ dataset: dict[str, Any], database: Optional[Database]
+ ) -> None:
+ """
+ Run the two repairs that have to happen *before* the bundle is applied.
+
+ `_repair_partition_mappings` below runs after `import_from_dict`, which
+ is too late for either of these.
+
+ Sanitizing the bundle. The v1 importer drops a transform the save path
+ would refuse (`drop_unusable_partition_transforms`) on its way in, and
+ v0 did not -- so a legacy bundle naming ``partition_mapped_column: n``
+ and a transform of ``random() + :value`` on ``n`` imported happily and
+ then failed *every* later save: a description-only
+ ``PUT /api/v1/dataset/<id>`` returns 422 on the stored expression, and
+ the mapping never mirrors anything. Applied to the config rather than
+ the model because that is where the transform still is.
+
+ Disarming the old mapping. `DatasetDAO.clear_unmapped_partition_transforms`
+ reads the mapping as it stands, so the post-import call can only enforce
+ the one-transform invariant against the *new* references. An overwrite
+ that re-points the mapping makes a previously unmapped column the
+ effective one, and a transform parked there -- which nothing in the
+ bundle authored -- is found already mapped by the later call and kept.
+ A dataset mapping ``a -> p`` with a parked ``:value + 100`` on ``b``,
+ overwritten by a bundle setting ``partition_mapped_column: b`` and
+ omitting the columns, would mirror ``b = 5`` as ``p = 105`` and drop the
+ row ``(a=1, b=5, p=1)``. The same pre-change call `DatasetDAO.update`
+ and the v1 importer both make, and for the same reason.
+
+ ``database`` is ``None`` only for a CLI bundle importing a connection
+ that does not exist yet, which by definition has no stored dataset to
+ disarm and no dialect to validate a transform against -- the same case
+ `drop_unusable_partition_transforms` already declines to act on.
+ """
+ if database is None:
+ return
+
+ # Deferred import: `daos.dataset` pulls in `views.base`, which
+ # circularly imports back into the commands package at app init.
+ from superset.daos.dataset import DatasetDAO # noqa: PLC0415
+
+ drop_unusable_partition_transforms(dataset, database)
+
+ if not (table_name := dataset.get("table_name")):
+ return
+ existing = (
+ db.session.query(SqlaTable)
+ .filter(
+ SqlaTable.table_name == table_name,
+ SqlaTable.schema == dataset.get("schema"),
+ SqlaTable.database_id == database.id,
Review Comment:
When two catalogs contain the same schema/table, this lookup matches both and aborts v0 imports with `MultipleResultsFound`, even with the feature flag off. Include the supplied catalog in the lookup.
```suggestion
SqlaTable.schema == dataset.get("schema"),
SqlaTable.catalog == dataset["catalog"]
if dataset.get("catalog") is not None
else True,
SqlaTable.database_id == database.id,
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #43870:
URL: https://github.com/apache/superset/pull/43870#issuecomment-6008241803
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers an incremental AI Review.
- `/review full` - Manually triggers a full AI Review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4226585540
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2730 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+#: Returned by `ExploreMixin.mirror_probe_request` for a filter no mirror can
+#: stand in for: one the engine compares more coarsely than the value carries, a
+#: value it cannot render as a literal, or an ``IN`` list with a member of
+#: either kind. A sentinel rather than `None`, because `None` is a filter value
+#: in its own right.
+#:
+#: Lives here rather than beside that method so the preview can read it too:
+#: `superset.models.helpers` imports this module, so the sentinel can only cross
+#: the boundary in this direction. Both callers have to recognise the same
+#: object -- a preview that answered "valid" for a request the chart path
+#: declines is the drift this is here to prevent.
+UNMIRRORABLE = object()
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
Review Comment:
Returning `True` for every non-string column assumes a numeric `=` implies `T(col) = T(v)`, but the probe evaluates `T` at the comparator after the filter normalizes it, not at the stored type. On SQLite with integer `n`, text partition `p`, transform `CAST(:value AS TEXT)` and a row `(n=1, p='1')`, a filter `n = '1.0'` still matches (numeric comparison), yet the probe returns `'1.0'`, so the mirror `p = '1.0' OR p IS NULL` drops that row. Should numeric equality decline when the transform's output depends on the value's representation, or should the comparator be coerced to the column's type before probing?
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/utils.ts:
##########
@@ -0,0 +1,587 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { t } from '@apache-superset/core/translation';
+import type {
+ PartitionMappingColumn,
+ PartitionMappingDatasource,
+ PartitionMappingIssue,
+ PartitionRowState,
+} from './types';
+
+/**
+ * Jinja delimiters.
+ *
+ * A transform is evaluated in a different context and at a different time from
+ * the chart query, so a template would not render the same way -- the backend
+ * rejects one outright. Shared so the check that declines to preview a Jinja
+ * transform and the check that blocks saving it cannot drift apart.
+ */
+const JINJA_PATTERN = /\{\{|\{%|\{#/;
+
+/**
+ * The column whose filters are mirrored.
+ *
+ * `partition_mapped_column` is an explicit override; `null` means "follow the
+ * default datetime column", so re-pointing that column moves the mapping with
+ * it. Mirrors `SqlaTable.partition_filter_mapping_summary` on the backend.
+ */
+export function resolveMappedColumn(
+ datasource: PartitionMappingDatasource,
+): string | null {
+ if (!datasource.partition_column) {
+ return null;
+ }
+ return datasource.partition_mapped_column || datasource.main_dttm_col || null;
+}
+
+/** Whether the mapped column came from `main_dttm_col` rather than an override. */
+export function mappedColumnIsImplicit(
+ datasource: PartitionMappingDatasource,
+): boolean {
+ return Boolean(
+ datasource.partition_column &&
+ !datasource.partition_mapped_column &&
+ datasource.main_dttm_col,
+ );
+}
+
+/**
+ * Whether a transform is worth spending a preview request on.
+ *
+ * A necessary condition, never a sufficient one: the server stays the authority
+ * on whether a transform is usable, and anything this cannot see -- an
+ * unparseable expression, a non-deterministic function -- still comes back from
+ * it. What this catches is the cases that are knowably hopeless while the owner
+ * is still typing, which would otherwise spend the per-user preview budget and
+ * leave none for the transform they eventually finish writing.
+ */
+export function transformCanPreview(
+ transform: string | null | undefined,
+ mappedColumn?: string | null,
+ partitionColumn?: string | null,
+): boolean {
+ const trimmed = transform?.trim();
+ if (!trimmed) {
+ return false;
+ }
+ // Without the placeholder there is no value to substitute, so the transform
+ // is inert however well-formed it is.
+ if (!/:value\b/.test(trimmed)) {
+ return false;
+ }
+ // Jinja is rejected on save, so previewing it is pointless.
+ if (JINJA_PATTERN.test(trimmed)) {
+ return false;
+ }
+ // A column cannot stand in for itself; the backend rejects this outright.
+ if (mappedColumn && partitionColumn && mappedColumn === partitionColumn) {
+ return false;
+ }
+ return true;
+}
+
+/**
+ * Whether the mapping will actually mirror anything.
+ *
+ * Drives the choice between the green "filters will automatically apply"
+ * message and the warning that nothing is mirrored yet, so "non-blank text in
+ * the box" is not a good enough test: a transform with no `:value` to
+ * substitute, or one carrying Jinja, is as inert as an empty one and the
+ * backend's own summary reports it inactive. Claiming otherwise tells an owner
+ * their queries are pruning when they are not.
+ *
+ * Shares `transformCanPreview`'s conditions rather than restating them, and is
+ * necessary rather than sufficient for the same reason: an unparseable
+ * expression or a non-deterministic function needs a SQL parser to spot, so the
+ * server stays the authority -- `valueTransformIssues` surfaces what it says at
+ * the transform field itself.
+ */
+export function mappingIsActive(
+ datasource: PartitionMappingDatasource,
+ columns: PartitionMappingColumn[],
+): boolean {
+ const mappedColumnName = resolveMappedColumn(datasource);
+ if (!mappedColumnName || mappedColumnName === datasource.partition_column) {
+ return false;
+ }
+ const mappedColumn = columns.find(
+ column => column.column_name === mappedColumnName,
+ );
+ return transformCanPreview(
+ mappedColumn?.partition_value_transform,
+ mappedColumnName,
+ datasource.partition_column,
+ );
+}
+
+/**
+ * What is wrong with one column's value transform, if anything.
+ *
+ * Split out of `partitionMappingErrors` because the two callers disagree about
+ * which text to judge. The save gate reads the committed column record; the
+ * field's own message has to describe the text on screen, which lags the commit
+ * by a debounce. Passing the transform separately lets both ask the same
+ * question about different values instead of reimplementing the checks.
+ */
+export function valueTransformIssues(
+ column: PartitionMappingColumn | undefined,
+ transform: string | null | undefined,
+): PartitionMappingIssue[] {
+ if (!column) {
+ return [];
+ }
+
+ if (JINJA_PATTERN.test(transform ?? '')) {
+ return [
+ {
+ field: 'partition_value_transform',
+ message: t(
+ 'Jinja templating is not supported in a partition value transform. The transform is evaluated in a different context and at a different time from the chart query, so a template would not render the same way.',
+ ),
+ },
+ ];
+ }
+
+ // A temporal column falls back on the engine's own default, so leaving the box
+ // empty there only makes the mapping inactive -- which the dataset-level
+ // warning already says. A non-temporal column has nothing to fall back on.
+ if (!column.is_dttm && !transform?.trim()) {
+ return [
+ {
+ field: 'partition_value_transform',
+ message: t(
+ 'A value transform is required on %(name)s, which is not a temporal column. Use :value for each value.',
+ { name: column.column_name },
+ ),
+ },
+ ];
+ }
+
+ return [];
+}
+
+/**
+ * Everything wrong with the mapping that should stop the save.
+ *
+ * The client half of `validate_partition_mapping` in
+ * `superset/connectors/sqla/partition_mapping.py`, restricted to its blocking
+ * (Tier 1) issues. Those are the ones the PUT would reject anyway, so catching
+ * them here turns a 400 toast arriving after the modal closed into a disabled
+ * Save button that says why. Tier 2 is deliberately absent: an unparseable
+ * transform, or one missing `:value`, is "saved but stays inactive until it
+ * parses" per the PRD, and must not cost the owner the rest of their edits.
+ *
+ * One check is stricter than the backend's: an empty transform on a
+ * non-temporal mapped column blocks. The backend files that as Tier 2 for every
+ * column, but a non-temporal column has no default transform to fall back on --
+ * the field carries a required marker saying exactly this -- so the marker
+ * should mean something.
+ *
+ * Callers gate on the feature flag themselves, the way the two mount sites in
+ * `DatasourceEditor` already do; a dataset carrying a stale `partition_column`
+ * on an engine that cannot use one must not block a save the backend accepts.
+ */
+export function partitionMappingErrors(
+ datasource: PartitionMappingDatasource,
+ columns: PartitionMappingColumn[],
+): PartitionMappingIssue[] {
+ const partitionColumn = datasource.partition_column;
+ if (!partitionColumn) {
+ return [];
+ }
+
+ const issues: PartitionMappingIssue[] = [];
+ const columnNames = new Set(columns.map(column => column.column_name));
+
+ if (!columnNames.has(partitionColumn)) {
+ issues.push({
+ field: 'partition_column',
+ message: t('Partition column %(name)s is not a column on this dataset.', {
+ name: partitionColumn,
+ }),
+ });
+ }
+
+ const override = datasource.partition_mapped_column;
+ if (override && !columnNames.has(override)) {
+ issues.push({
+ field: 'partition_mapped_column',
+ message: t('Mapped column %(name)s is not a column on this dataset.', {
+ name: override,
+ }),
+ });
+ }
+
+ const mappedColumnName = resolveMappedColumn(datasource);
+ if (mappedColumnName === partitionColumn) {
+ // Only the *explicit* self-mapping blocks the save, matching
+ // `validate_partition_mapping`: an override naming the partition column is
+ // something the owner asked for and can take back, so it is Tier 1 there.
+ //
+ // The implicit one -- no override, and `main_dttm_col` happens to equal the
+ // partition column -- is Tier 2 on purpose. Blocking it here disabled Save
+ // on a dataset already in that state (metadata sync used to be able to
+ // produce one) even for a description-only edit, which is exactly the
+ // unsaveable dataset the backend comment says it avoids. The owner gets the
+ // same message, as a warning they can save through.
+ //
+ // No transform check can follow either way: the transform is a property of
+ // the mapped column, and there is no coherent mapped column to read it from.
+ issues.push({
+ field: 'partition_column',
+ blocking: Boolean(datasource.partition_mapped_column),
+ message: t(
+ 'The partition column cannot be mapped onto itself. %(name)s is both the partition column and the mapped column.',
+ { name: partitionColumn },
+ ),
+ });
+ return issues;
+ }
+
+ const mappedColumn = columns.find(
+ column => column.column_name === mappedColumnName,
+ );
+ issues.push(
+ ...valueTransformIssues(
+ mappedColumn,
+ mappedColumn?.partition_value_transform,
+ ),
+ );
+
+ return issues;
+}
+
+/** Which of the three row-expand treatments a column gets. */
+export function partitionRowState(
+ datasource: PartitionMappingDatasource,
+ columnName: string,
+): PartitionRowState {
+ if (!datasource.partition_column) {
+ return 'none';
+ }
+ if (columnName === datasource.partition_column) {
+ return 'partition';
+ }
+ return resolveMappedColumn(datasource) === columnName ? 'mapped' : 'unmapped';
+}
+
+/**
+ * The transform to pre-fill when a column becomes the mapped one.
+ *
+ * Only temporal columns get one, and only when the engine supplies it:
+ * `unix_timestamp(:value)` is Hive-family syntax and would not parse on
+ * Postgres or BigQuery, so a wrong default is worse than none.
+ */
+export function defaultTransformFor(
+ datasource: PartitionMappingDatasource,
+ column: PartitionMappingColumn | undefined,
+): string {
+ if (!column?.is_dttm) {
+ return '';
+ }
+ return datasource.partition_value_transform_default || '';
+}
+
+/** Declared types whose values are numbers rather than strings. */
+const NUMERIC_TYPE_RE =
+ /INT|NUMERIC|DECIMAL|DOUBLE|FLOAT|REAL|NUMBER|BIGNUMERIC/i;
+
+/**
+ * Samples the preview evaluates the transform at.
+ *
+ * Temporal columns get one timestamp, because a time-range bound is what they
+ * are mapped for. Everything else gets two values, so the preview demonstrates
+ * the element-wise `IN` an ordinary categorical filter actually produces.
+ *
+ * The samples follow the column's declared type, not just whether it is
+ * temporal. A mapped integer column with `CAST(:value AS INTEGER)` is a real
+ * configuration, and evaluating it at `'US'` makes the engine reject a transform
+ * that an actual `IN (2025, 2026)` filter would mirror perfectly well -- the
+ * preview was reporting a fault in its own sample data.
+ */
+export function sampleValuesFor(
+ column: PartitionMappingColumn | undefined,
+): string[] {
+ if (column?.is_dttm) {
+ return ['2026-01-15 00:00:00'];
Review Comment:
This picks a timestamp string for any `is_dttm` column before looking at the stored type. For a `BIGINT` column marked temporal with `python_date_format=epoch_s`, mapped with the identity transform `:value`, the preview sends `'2026-01-15 00:00:00'`; the backend's numeric coercion turns that into `NULL`, so the editor reports the mapping as broken even though chart time ranges mirror correctly through epoch bounds. Should the sample be generated in the column's stored representation when the column is numeric?
##########
superset/models/helpers.py:
##########
@@ -4292,36 +4389,661 @@ def dttm_sql_literal(self, dttm: datetime, col: "TableColumn") -> str:
return f"""'{dttm.strftime("%Y-%m-%d %H:%M:%S.%f")}'"""
- def get_time_filter( # pylint: disable=too-many-arguments # noqa: C901
+ def _mirror_probe_value(self, dttm: datetime, col: Optional["TableColumn"]) -> Any:
+ """
+ ``dttm`` in the mapped column's own stored representation.
+
+ The predicate this mirror stands in for compares the column against
+ `dttm_sql_literal(dttm, col)`, so the transform has to be probed with
+ the same value. On a column stored as an epoch integer, ``T`` is a
+ function of an integer: probing it with a `datetime` either returns
+ something unrelated to the partition keys or raises, and a raise costs
+ the dataset its pruning silently.
+
+ Only the ``python_date_format`` branches of `dttm_sql_literal` are
+ reproduced, because only those produce a *value*. `convert_dttm` yields
+ engine-specific SQL text, which cannot be bound as a parameter; its own
+ divergence from the probe is handled by widening the bounds instead
+ (`_engine_literal_resolution`).
+
+ In `dttm_sql_literal`'s own order, though: it asks ``convert_dttm``
+ first and reaches the format only when the engine answers nothing. A
+ column can carry both -- a TIMESTAMP with a ``%Y%m%d``
+ ``python_date_format``, or an entry in
+ ``python_date_format_by_column_name`` -- and applying the format
+ unconditionally probed a value the real predicate never compares.
+ ``event_time >= '2026-01-01 00:00:00'`` mirrored as
+ ``partition_col >= '20260101'``, and a January 15 row keyed
+ ``2026-01-15`` sorts below that string, so the chart lost a row the
+ filter keeps.
+
+ Where the engine does answer, the `datetime` is returned unchanged and
+ the widening path takes over -- which is exactly what already happens
+ for every temporal column that carries no format at all.
+ """
+ if col is None:
+ return dttm
+
+ if col.type and self.db_engine_spec.convert_dttm(
+ col.type, dttm, db_extra=self.db_extra
+ ):
+ # The format is unreachable in `dttm_sql_literal` for this column,
+ # so reproducing it here would describe a different bound.
+ return dttm
+
+ tf = col.python_date_format
+ if not tf and self.db_extra:
+ tf = self.db_extra.get("python_date_format_by_column_name", {}).get(
+ col.column_name
+ )
+ if not tf:
+ return dttm
+
+ if tf in EPOCH_FORMATS:
+ dttm_tz_aware = dttm
+ if dttm_tz_aware.tzinfo is None:
+ dttm_tz_aware = dttm_tz_aware.replace(tzinfo=timezone.utc)
+ return int(dttm_tz_aware.timestamp()) * EPOCH_FORMATS[tf]
+ return dttm.strftime(tf)
+
+ def _engine_literal_resolution(
+ self, dttm: datetime, col: Optional["TableColumn"]
+ ) -> LiteralResolution:
+ """
+ How much of ``dttm`` survives into this engine's literal for ``col``.
+
+ The real predicate compares `dttm_sql_literal(dttm, col)`, so whatever
+ that literal throws away is a bound the engine never sees. A mirror
+ derived from the full precision then describes a *narrower* range than
+ the predicate it stands in for -- and narrower means it drops rows the
+ filter keeps.
+
+ Two things get thrown away in practice:
+
+ - the sub-second part. SQLite renders a timestamp with
+ ``timespec="seconds"``.
+ - the time of day entirely. Every engine spec with a ``types.Date``
+ branch renders ``dttm.date().isoformat()``, so Presto, Trino,
+ BigQuery and some two dozen others answer `DATE '2026-01-01'` for a
+ bound of 10:00 -- and `T(DATE '2026-01-01')` is below the mirror's
+ own lower bound, so the whole first day is dropped.
+
+ Detected rather than enumerated per engine, because the branch depends
+ on the column's type as well as the spec: instants differing only in the
+ part under test render as the same text exactly when the engine has
+ thrown that part away.
+
+ The day test uses two fixed times of day rather than ``dttm`` and one
+ alternative, so a bound that happens to sit on the hour the alternative
+ uses cannot read as "no time at all". Neither probe sits at midnight on
+ purpose: SQLite renders a DATE column at exactly midnight as a bare
+ date, so a midnight probe would differ from its alternative for a
+ reason that has nothing to do with resolution.
+
+ Likewise both sub-second probes carry a non-zero remainder. Comparing
+ against ``dttm`` truncated to the second looks like the obvious test and
+ is wrong for the same formatting-boundary reason.
+
+ A non-temporal column has no answer here, and asking anyway gets a wrong
+ one. SQLite's ``convert_dttm`` renders for ``types.String`` as well as
+ for the date types, so a ``VARCHAR`` mapped column reads as
+ second-resolution -- and a filter value that happens to *look* like an
+ instant then has its bound rounded as though the engine had truncated
+ it. On a VARCHAR ``code`` mapped onto a VARCHAR ``p`` by ``:value``,
+ ``code < '2026-07-06T10:08:11.500000'`` was mirrored as
+ ``p <= '2026-07-06 10:08:12.000000'``; a space sorts before ``T``, so a
+ row holding ``2026-07-06T09:00:00`` fell outside the mirror while
+ matching the filter.
+
+ The guard lives here rather than in each caller so this and
+ `_column_literal_resolution` cannot disagree about which column is
+ coarse -- which is the same reason that helper delegates to this one.
+ """
+ if col is None or not col.type or not col.is_dttm:
+ return LiteralResolution.FULL
+
+ def render(moment: datetime) -> Optional[str]:
+ return self.db_engine_spec.convert_dttm(
+ col.type, moment, db_extra=self.db_extra
+ )
+
+ try:
+ early = render(dttm.replace(hour=1, minute=2, second=3, microsecond=444444))
+ late = render(
+ dttm.replace(hour=22, minute=33, second=44, microsecond=555555)
+ )
+ if early is not None and early == late:
+ return LiteralResolution.DAY
+
+ # Flooring to the second is a no-op on a bound that has no
+ # sub-second part, so there is nothing to detect.
+ if not dttm.microsecond:
+ return LiteralResolution.FULL
+
+ first = render(dttm.replace(microsecond=111111))
+ second = render(dttm.replace(microsecond=222222))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return LiteralResolution.FULL
+
+ if first is not None and first == second:
+ return LiteralResolution.SECOND
+ return LiteralResolution.FULL
+
+ def _round_bounds_outward(
self,
- time_col: "TableColumn",
+ start_dttm: Optional[datetime],
+ end_dttm: Optional[datetime],
+ col: Optional["TableColumn"],
+ ) -> tuple[Optional[datetime], Optional[datetime]]:
+ """
+ The bounds widened to whatever the engine's literal actually resolves to.
+
+ Rounding outward is never narrower than the predicate being mirrored,
+ which is the only property the mirror has to hold.
+ """
+ resolutions = {
+ self._engine_literal_resolution(bound, col)
+ for bound in (start_dttm, end_dttm)
+ if bound is not None
+ }
+
+ if LiteralResolution.DAY in resolutions:
+ # The engine compares a bare date, so the real predicate's lower
+ # bound is the start of that day and its upper bound admits the
+ # whole of the day before. Anything finer excludes rows it keeps.
+ if start_dttm is not None:
+ start_dttm = start_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ )
+ if end_dttm is not None and end_dttm != end_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ ):
+ end_dttm = end_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ ) + timedelta(days=1)
+ elif LiteralResolution.SECOND in resolutions:
+ if start_dttm is not None:
+ start_dttm = start_dttm.replace(microsecond=0)
+ if end_dttm is not None and end_dttm.microsecond:
+ end_dttm = end_dttm.replace(microsecond=0) + timedelta(seconds=1)
+
+ return start_dttm, end_dttm
+
+ def _literal_is_coarser_than(
+ self, dttm: datetime, col: Optional["TableColumn"]
+ ) -> bool:
+ """
+ Whether the engine's literal for ``dttm`` throws away part of it.
+
+ Unlike a range, an equality cannot be widened outward, so the only safe
+ answer when the engine compares less than the full value is to decline
+ the mirror.
+ """
+ resolution = self._engine_literal_resolution(dttm, col)
+ if resolution is LiteralResolution.DAY:
+ return dttm != dttm.replace(hour=0, minute=0, second=0, microsecond=0)
+ if resolution is LiteralResolution.SECOND:
+ return bool(dttm.microsecond)
+ return False
+
+ def _column_literal_resolution(
+ self, col: Optional["TableColumn"]
+ ) -> LiteralResolution:
+ """
+ How much of *any* value this engine compares on ``col``.
+
+ `_engine_literal_resolution` answers about a particular instant, which
+ is what a mirror derived from one needs. Two callers have no instant to
+ ask about -- the summary the Explore glyph reads, and a filter value
+ `_instant_from_filter_value` cannot read as an instant at all -- and
+ both need the column's own answer. Through one helper so that the glyph
+ and the query path cannot disagree about which column is coarse, which
+ is the same reason `mirrorable_operators` is computed once.
+
+ A non-temporal column has no answer, and asking anyway gets a wrong one:
+ SQLite's ``convert_dttm`` renders for ``types.String`` as well as for the
+ date types, so a reference instant makes a ``VARCHAR`` mapped column look
+ second-resolution -- and ``country = 'US'``, the text half of this
+ feature, reads as a value the engine compares coarsely.
+
+ That guard is `_engine_literal_resolution`'s, not this function's. It
+ used to be here, on the belief that the per-instant callers never met
+ the case because they arrive only with a value that parsed as an
+ instant -- which is untrue of a text column holding ISO-shaped text,
+ where the value parses and the column is still not temporal.
+ """
+ return self._engine_literal_resolution(_RESOLUTION_REFERENCE_INSTANT, col)
+
+ def _round_bound_outward(
+ self,
+ instant: datetime,
+ col: Optional["TableColumn"],
+ *,
+ is_upper: bool,
+ ) -> datetime:
+ """
+ One bound widened to whatever the engine resolves ``col`` to.
+
+ `_round_bounds_outward` answers for a since/until pair, because a time
+ range is the shape it was written for. A single comparison is one end of
+ such a pair with the other end absent, and the widening is per-end
+ already -- a lower bound moves back, an upper bound forward.
+
+ Narrowing the return type is the other half of the point: a bound handed
+ in non-`None` comes back non-`None`, and saying so here saves every
+ caller from re-establishing it.
+ """
+ start_dttm, end_dttm = self._round_bounds_outward(
+ None if is_upper else instant,
+ instant if is_upper else None,
+ col,
+ )
+ rounded = end_dttm if is_upper else start_dttm
+ return rounded if rounded is not None else instant
+
+ def _mirror_probe_input(
+ self,
+ operator: utils.FilterOperator,
+ value: Any,
+ col: Optional["TableColumn"],
+ ) -> Any:
+ """
+ ``value`` in the representation the mirror may probe the transform at.
+
+ A simple filter on a temporal column carries a *string*.
+ `filter_values_handler` rewrites only an all-digit value, which it reads
+ as epoch milliseconds, so ``'2026-07-06 10:08:11'`` reaches here exactly
+ as the chart author typed it and is bound as text. The engine compares
+ that text against the column under its own cast, and on a ``DATE``
+ column the cast drops the time of day: the filter keeps the whole of
+ 2026-07-06 while a mirror probed at 10:08:11 keeps one instant of it,
+ which is narrower than the predicate it stands in for.
+
+ So the text is read back into the instant it denotes -- the only way
+ `_engine_literal_resolution`, which answers about a `datetime`, reaches
+ a filter value at all -- and where the engine compares less of that
+ instant than the filter carries, what to do about it is a property of
+ the *operator*:
+
+ * a bound rounds outward, through the helper the range collector uses.
+ Reading one extra bucket at the edge is the trade this feature makes
+ everywhere else too -- see `mirror_operator` -- and the original
+ predicate is still in the query to exclude the rows that bucket adds.
+ * an equality, or one member of an ``IN`` list, has nowhere to widen to.
+ These entries are ``AND``-ed onto the query, so "or the day either
+ side" is not something this sink can express, and the request is
+ declined with `_UNMIRRORABLE`. The query is then correct and unpruned,
+ which is the one failure mode this feature is allowed.
+
+ An instant carrying a UTC offset is declined for every operator, a
+ bound included. Rounding one outward would first have to place it in the
+ frame the partition column was written in, and guessing that frame is
+ how a mirror ends up a whole offset narrower than the filter -- see the
+ load-bearing assumption in
+ `superset.connectors.sqla.partition_mapping`.
+
+ A *string* `_instant_from_filter_value` cannot read at all is declined on
+ the same terms, and for the same reason one more step back: there is no
+ instant to round. ``'07/06/2026 10:08:11'`` is not ISO 8601, so the
+ parser leaves it alone -- and Postgres casts that same text to a DATE and
+ keeps the whole of July 6 while the probe, handed the string verbatim,
+ evaluates the transform at 10:08:11 and asks for a partition key no row
+ holds. That is exactly the narrowing the ISO-only parser was written to
+ prevent, reached through a value it declines to read, so the decline has
+ to travel with it. Which costs a non-ISO *date* its pruning too, because
+ telling July 6 from June 7 is the guess that started this.
+
+ Only a string. `_as_probe_input` has already run, so the engine SQL
+ `filter_values_handler` returns for an epoch-millisecond bound arrives
+ here as a `RawProbeValue` rather than text -- and that literal was
+ rendered by the engine at the engine's own resolution, so it is the one
+ thing on this path with nothing left to resolve.
+
+ Where the engine compares the whole instant, a string is returned
+ exactly as it arrived -- down to the type the probe binds and the cache
+ key it lands on, because every query that was already correct has to
+ stay byte-for-byte correct. A `datetime` is still converted, which it
+ has always needed: on a column stored as an epoch integer the transform
+ is a function of an integer, and a `datetime` is not the value the real
+ predicate compares.
+ """
+ parsed = _instant_from_filter_value(value)
+ if parsed is None:
+ if (
+ isinstance(value, str)
+ and self._column_literal_resolution(col) is not LiteralResolution.FULL
+ ):
+ return _UNMIRRORABLE
+ return value
+
+ if (
+ self._engine_literal_resolution(parsed.replace(tzinfo=None), col)
Review Comment:
When the engine compares the whole instant, a string bound with an explicit UTC offset is passed to the probe as-is, while the coarse-resolution path below declines it. If the mapped column is a `TIMESTAMPTZ` and the transform is `extract(epoch from CAST(:value AS TIMESTAMP))`, a row at `2026-01-01 00:00:00Z` (key `1767225600`) matches `event_time = '2026-01-01T01:00:00+01:00'`, but the cast drops the offset, the probe yields `1767229200`, and the added `p = 1767229200` excludes the row. Should an offset-bearing string decline here too, or be normalized to the column's representation first?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2730 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+#: Returned by `ExploreMixin.mirror_probe_request` for a filter no mirror can
+#: stand in for: one the engine compares more coarsely than the value carries, a
+#: value it cannot render as a literal, or an ``IN`` list with a member of
+#: either kind. A sentinel rather than `None`, because `None` is a filter value
+#: in its own right.
+#:
+#: Lives here rather than beside that method so the preview can read it too:
+#: `superset.models.helpers` imports this module, so the sentinel can only cross
+#: the boundary in this direction. Both callers have to recognise the same
+#: object -- a preview that answered "valid" for a request the chart path
+#: declines is the drift this is here to prevent.
+UNMIRRORABLE = object()
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error( # noqa: C901
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ And it must be a *read*. Shape is a separate question from effect: a bare
+ scalar expression can still write, so `SQLStatement.is_mutating` is asked
+ too -- the same question SQL Lab and the chart executor ask before letting
+ SQL run. See the gate itself for what that reaches and what it does not.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ # Also ahead of the parse, and for a stronger reason than cost: every gate
+ # below reasons about the parse tree, and this is the one construct that
+ # makes the parse tree describe a different statement from the one the
+ # engine runs. Checked here as well as in `validate_transform` because this
+ # is the door a row written by an earlier release still comes through.
+ if contains_executable_comment(transform):
+ return str(
+ _(
+ "A partition value transform cannot contain a MySQL "
+ "executable comment, which the database executes and every "
+ "validator reads as a comment."
+ )
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The read-only gate, which nothing above implies. The shape gates ask what
+ # the transform *selects*; this asks what evaluating it *does*, and a bare
+ # scalar expression can still write. `nextval(:value)` on PostgreSQL
+ # advances a sequence: one function call, no clause, no sub-query, and not
+ # in the default `DISALLOWED_SQL_FUNCTIONS` either -- so every gate above
+ # passes it and the probe then runs it. `setval` is the same shape, and
+ # `exp.Execute` and the opaque-`exp.Command` forms arrive the same way.
+ #
+ # The large-object writers (`lo_export`, `lowrite`, `lo_from_bytea`, ...)
+ # are caught here too, and the shipped denylist happens to name them as
+ # well -- but that is config an operator can replace, while this is not.
+ #
+ # `is_mutating` is the same question SQL Lab, `get_virtual_table_metadata`
+ # and the chart executor ask before letting SQL run, so a transform is held
+ # to the bar the rest of Superset already sets rather than to one invented
+ # here. Unconditional rather than gated on `Database.allow_dml`: a transform
+ # is a scalar function of `:value` by definition, so there is no legitimate
+ # mutating one, and the probe runs on a cache schedule nobody chose -- a
+ # write would repeat every time the entry expired.
+ #
+ # It bears saying what this does not reach. A user-defined function whose
+ # body writes is a plain call no parser can tell from `lower(:value)`, and
+ # `is_mutating`'s function-name walk is PostgreSQL-only by design, since the
+ # same names are read-only elsewhere. Neither residual is specific to this
+ # feature -- a dataset editor can already have the engine evaluate an
+ # arbitrary expression through a calculated column or a virtual dataset's
+ # SQL -- and closing them means authorizing the preview against the
+ # database, not parsing harder.
+ if statement.is_mutating():
+ return str(
+ _(
+ "A partition value transform cannot change data. It is "
+ "evaluated against the database to check that it mirrors, so "
+ "it has to be a read."
+ )
+ )
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the probe
+ uninspected -- string elements are escaped by the dialect's own literal
+ processor. `probe_sql_is_evaluable` then re-reads the finished query, which
+ is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def _placeholder_is_bindable(transform: str) -> bool:
+ """
+ Whether SQLAlchemy's ``text()`` can see ``:value`` as a bound parameter.
+
+ `VALUE_PLACEHOLDER_RE` is ``:value\b``, which matches the placeholder in a
+ Postgres cast such as ``:value::bigint``. SQLAlchemy's own bind scan is
+ ``(?<![:\\w$]):([\\w$]+)(?![:\\w$])`` -- note the trailing exclusion -- so a
+ following colon stops it: ``text(":value::bigint")`` reports a parameter
+ named ``valu``, and ``.bindparams(bindparam("value"))`` then raises
+ ``ArgumentError``.
+
+ `_probe` swallows that, so the only symptom was a perfectly valid transform
+ whose mapping silently never pruned, and a preview reporting an engine
+ failure for SQL that was never sent. Every write-side gate passes the
+ transform: it parses, it is a bare expression, and the placeholder *is* in
+ an executable position.
+
+ Answered by attempting the bind itself rather than by pattern-matching
+ ``::`` or reading ``text()``'s private parameter map, so this cannot
+ disagree with what `build_probe_sql` is about to do -- on any dialect, or on
+ a SQLAlchemy whose scan changes.
+ """
+ try:
+ sa.text(transform).bindparams(sa.bindparam("value", value=None))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return False
+ return True
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ bindable = _placeholder_is_bindable(transform)
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ elif bindable:
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ rendered = _compile_literal(clause, dialect)
+ else:
+ # `text()` cannot see the placeholder (see
+ # `_placeholder_is_bindable`), so the value is rendered by the
+ # dialect's own literal processor first and substituted as SQL
+ # text. The same two steps in the other order: binding exists to
+ # get the value through that processor, and `_compile_literal`
+ # inlines the result either way, so this is the same string by a
+ # different route -- not a loosening of the "never interpolate a
+ # raw value" rule. `parse_skeleton` substitutes literally, so a
+ # rendered literal containing a backslash is safe here.
+ rendered = parse_skeleton(
+ transform, _compile_literal(sa.literal(value), dialect)
+ )
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Four things have to hold, and all four are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ # Before the parse, because this gate's whole contract is that what the
+ # parse describes is what the engine will run, and an executable comment is
+ # precisely the text where that stops being true. The transform is already
+ # refused for carrying one; this covers the compiled statement, so no later
+ # change to how values are rendered can reintroduce it behind the gates
+ # below.
+ if contains_executable_comment(sql):
+ return False
+
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if not isinstance(statement, SQLStatement):
+ # A dialect whose statements this gate cannot take apart -- KQL -- gets
+ # no probe rather than an unchecked one. It never had one: the clause
+ # inspection below is implemented for SQL statements only, and the
+ # alternative to declining here is an `AttributeError` that `_probe`
+ # swallows into the same outcome, less legibly.
+ return False
+ if statement.has_subquery():
+ return False
+ if statement.get_clause_names() - {"from"}:
+ return False
+ if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+ """
+ The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+ Parsed rather than string-compared so that the comparison in
+ `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+ not parse answers ``None``, which no statement carrying a FROM can match --
+ the probe then declines, which is the right way for an unreadable engine
+ constant to fail.
+ """
+ if not from_suffix.strip():
+ return None
+ try:
+ return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+ except SupersetParseError:
+ return None
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=values is not None and not any(value is None for value in values),
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ from_suffix = database.db_engine_spec.select_without_from_suffix
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ from_suffix,
+ )
+ if not probe_sql_is_evaluable(
+ sql, database.backend, len(distinct), from_suffix
+ ):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _execution_identity(database: Database) -> str | None:
+ """
+ Who the warehouse will run the probe as, when that can vary by caller.
+
+ `_probe_cache_key` keys on the `Database` record, which is the *connection*
+ -- not the identity it is opened under. Two hooks make that identity a
+ function of the Superset user instead:
+
+ * ``impersonate_user`` on the database, which hands the effective username
+ to `db_engine_spec.impersonate_user`;
+ * ``DB_CONNECTION_MUTATOR``, which receives the effective username and may
+ return an entirely different account's URL.
+
+ Under either one, a cached probe result computed under user A's grants was
+ served to user B, and the preview echoed it back in ``emitted_predicate``.
+ A transform wrapping a read-capable function the denylist does not name --
+ Oracle's ``DBMS_XMLGEN.GETXML`` is the worked example -- then leaks across
+ users who were never allowed the same rows.
+
+ Returns ``None`` when neither hook is configured, which is the common case
+ and deliberately leaves the key as it was: the cache exists to keep a
+ synchronous warehouse round trip off the chart-query path, and keying every
+ deployment on the username would cost every deployment the hit rate to fix
+ the two that need it.
+
+ The *Superset* username rather than the resolved warehouse account, because
+ it is the input both hooks branch on, and reading it needs no URL parse and
+ puts no credential in the key.
+ """
+ if not (database.impersonate_user or app.config["DB_CONNECTION_MUTATOR"]):
+ return None
+ return get_username()
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _mirror_verdict_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str:
+ """
+ `_probe_cache_key` without the values.
+
+ Whether a transform can be evaluated at all is a property of the transform
+ and the connection, not of the filter that happened to be probing it, so
+ one chart's answer settles the question for the next one.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ # Whether a transform *can* be evaluated is a property of the
+ # transform and the connection -- but under impersonation the
+ # connection is per-user, and a function one account may call can
+ # be refused to another. See `_execution_identity`.
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_verdict:{digest}"
+
+
+def record_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ *,
+ mirrors: bool,
+) -> None:
+ """
+ Remember whether this transform produced a mirror, for the UI to read.
+
+ Advisory only. Nothing in the query path consults it: a probe that failed
+ once is retried on the next chart exactly as it is today, because declining
+ to prune for a whole cache timeout over one transient engine blip is the
+ trade `evaluate_transform` deliberately refuses -- see the comment where it
+ declines to cache a failure.
+
+ What this is for is the *claim*. `is_transform_active` parses the transform
+ and no more, so a transform the database rejects -- a misspelled function
+ is the common case -- is "active", and the editor's banner and Explore's
+ pruning glyph promise a speed-up that never happens. A promise is exactly
+ the thing that may be withheld on one bad answer and restored on a good
+ one, which is why this is a separate entry from the probe's own results
+ rather than a relaxation of that rule.
+
+ Written by `_run_probe`, so the preview endpoint -- which shares the
+ evaluator -- settles the question before the owner has even saved.
+ """
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(
+ _mirror_verdict_cache_key(database, catalog, schema, transform),
+ mirrors,
+ timeout=timeout,
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform verdict", exc_info=True)
+
+
+def known_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> bool | None:
+ """
+ The last verdict `record_mirror_verdict` stored, or `None` if there is none.
+
+ `None` is the honest answer on a cold cache and is deliberately not `False`:
+ reporting a working mapping as broken until something probes it would
+ trade one wrong claim for another. The alternative -- probing from the
+ read side -- would put a warehouse round trip on every Explore and
+ dashboard load, and a failing transform is not cached at all, so it would
+ be a round trip every single time.
+ """
+ try:
+ verdict = cache_manager.cache.get(
+ _mirror_verdict_cache_key(database, catalog, schema, transform)
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return verdict if isinstance(verdict, bool) else None
+
+
+def _compile_literal(element: Any, dialect: Dialect | None) -> str:
+ """
+ Compile with inline literals, undoing the paramstyle's percent doubling.
+
+ Both ``TextClause`` and literal compilation run the dialect's
+ ``post_process_text``, which doubles every ``%`` whenever the identifier
+ preparer asks it to -- true for MySQL and Postgres and for every spec
+ inheriting their paramstyle. That doubling exists so a later DBAPI
+ parameter-interpolation pass can undo it, and the probe has no such pass:
+ it executes with no bound parameters at all. So a transform of
+ ``date_format(:value, '%Y%m%d')`` reaches the warehouse asking for the
+ literal string ``%%Y%%m%%d``, the probe returns that instead of a date, and
+ the mirrored predicate drops every row the filter keeps.
+
+ The same normalization ``Database.compile_sqla_query`` applies for the same
+ reason. ``_double_percents`` is private and not guaranteed on a third-party
+ dialect, hence the ``getattr`` default.
+ """
+ compiled = str(
+ element.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
+ )
+ if dialect is not None and getattr(
+ dialect.identifier_preparer, "_double_percents", False
+ ):
+ compiled = compiled.replace("%%", "%")
+ return compiled
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be *asked* to stand in for itself, and the transform
+ cannot carry Jinja or call a non-deterministic function. Tier 2
+ (``blocking=False``) is everything that merely leaves the mapping inactive
+ -- including a self-mapping nobody asked for, where the partition column
+ merely happens to be the default datetime column.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column == partition_column:
+ # Asked for explicitly, so report it as the mistake it is.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+ elif not partition_mapped_column and main_dttm_col == partition_column:
+ # Resolved onto itself only because the default datetime column happens
+ # to be the partition column -- a state metadata sync could produce
+ # without anyone asking for it. The mapping is inert either way, since
+ # `resolve_partition_mapping` bails out on it, so this reports and lets
+ # the write through: blocking here means a dataset already in the state
+ # can never be saved again, not even to change its description, and
+ # there is no field whose edit would clear the error first.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "%(name)s is both the partition column and the default "
+ "datetime column, so the mapping points at itself and "
+ "stays inactive. Set a mapped column override, or change "
+ "the default datetime column.",
+ name=partition_column,
+ ),
+ blocking=False,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def drop_unmapped_value_transforms(
+ columns: list[dict[str, Any]] | None,
+ *,
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ names_by_id: dict[int, str] | None = None,
+) -> list[str]:
+ """
+ Null the value transform on every *incoming* column the mapping cannot mirror.
+
+ The write-side twin of `DatasetDAO.clear_unmapped_partition_transforms`,
+ which answers for the model. A mapping has exactly one mirrored column, so
+ at most one column may carry a transform. One parked on any other column is
+ invisible -- no row but the mapped one renders a transform -- and yet it is
+ stored, and it goes live the moment the mapped column resolves back to it.
+ Clearing an override is enough to do that: a null
+ ``partition_mapped_column`` means "follow ``main_dttm_col``".
+
+ Ungated on the feature flag, unlike its model-level twin, and the difference
+ is what each one discards. That one drops stored configuration, so with the
+ flag off it would be pure loss. This one drops only a value the request in
+ hand is asking to write where the invariant says none may live -- and the
+ flag-off window is precisely when such a value gets parked for later, since
+ the editor hides these fields and the model-level pass declines to run.
+
+ Three writers reach the columns with no effective model-level pass between
+ them, which is why this exists at all: the deprecated
+ ``POST /datasource/save/``, which writes straight through
+ `update_from_object` and so never had one; and a
+ ``PUT /api/v1/dataset/<pk>`` or a dataset import made while the flag is
+ off, where the pass runs on both sides of the write and declines on both.
+
+ Mutates the payload in place, because every caller hands its own request
+ dict straight on to the code that writes it. Returns the names it cleared,
+ so the caller can say so in a log: this is a silent correction to a payload
+ whose author may have meant it.
+
+ A column whose payload mentions neither field is left alone. "Incoming" is
+ the whole scope -- a transform already in storage on a column this request
+ says nothing about is the model-level pass's business, under its own flag.
+
+ The mapped column resolves the way every other reader resolves it,
+ ``partition_mapped_column or main_dttm_col``, and resolves to nothing
+ without a partition column -- in which case no column may hold a transform
+ either.
+
+ :param names_by_id: how to read the name off a payload entry that gives
+ only an ``id``. `DatasetDAO._upsert_columns` identifies an existing
+ column by its primary key and lets ``column_name`` be omitted -- the
+ column keeps the name it has -- so without this an ordinary PUT looked
+ like a payload of nameless columns, none of which matched the mapped
+ one, and every transform in it was dropped. Callers whose writer keys
+ on the name instead (`update_from_object`, the importer) pass nothing.
+ An entry this cannot name is left alone rather than guessed at.
+ """
+ mapped_column = (
+ (partition_mapped_column or main_dttm_col) if partition_column else None
+ )
+ cleared: list[str] = []
+ for column in columns or []:
+ name = column.get("column_name")
+ if name is None and names_by_id is not None:
+ column_id = column.get("id")
+ if column_id is not None:
+ name = names_by_id.get(column_id)
+ if name is None or name == mapped_column:
+ continue
+ if column.get("partition_value_transform") or column.get(
+ "partition_transform_is_monotonic"
+ ):
+ column["partition_value_transform"] = None
+ column["partition_transform_is_monotonic"] = False
+ cleared.append(name)
+ return cleared
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if contains_executable_comment(transform):
+ # Blocking, and checked on raw text next to the Jinja gate because no
+ # parse reports it: sqlglot reads `/*!50000 ... */` as comment data
+ # while MySQL and MariaDB execute it, so every shape gate downstream
+ # inspects a statement the engine will not run. See
+ # `EXECUTABLE_COMMENT_RE`.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform cannot contain a MySQL executable "
+ "comment (/*! ... */ or /*M! ... */). Those are comments "
+ "to every validator and statement text to the database, "
+ "so what would run is not what was checked."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_bare_expression(transform, engine):
+ # Blocking, and deliberately placed in `validate_transform` rather than
+ # only at the probe: one issue here closes the PUT, the importer, the
+ # query-time gate through `is_transform_active`, the Explore indicator's
+ # active verdict and the preview endpoint, all of which already consult
+ # this function.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform must be a single SQL expression. It "
+ "cannot carry a FROM, WHERE, GROUP BY or any other clause, "
+ "and it cannot contain a sub-query."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not contains_value_placeholder(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform must contain the :value placeholder, "
+ "which stands for the filter value being mirrored."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not placeholder_is_executable(transform, engine):
+ # Blocking, and for the same reason the shape gate above is: this is
+ # the function the PUT, the importer, `is_transform_active`, the
+ # Explore indicator and the preview all consult, so one issue here
+ # closes every door at once. A placeholder inside a string literal is
+ # a sub-query the engine will run once a filter value closes the quote;
+ # one inside a comment silently eats the probe's own alias.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The :value placeholder must appear where the engine will "
+ "evaluate it. It cannot sit inside a string literal or a "
+ "comment."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if functions := find_non_deterministic_functions(transform, engine):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform calls %(functions)s, whose result "
+ "depends on when and where it runs. The transform is "
+ "evaluated in a separate session and the result is cached, "
+ "so the emitted predicate would freeze a snapshot of that "
+ "moment.",
+ functions=", ".join(sorted(functions)),
+ ),
+ blocking=True,
+ )
+ ]
+
+ return []
+
+
+@lru_cache(maxsize=LRU_CACHE_MAX_SIZE)
+def is_transform_active(transform: str | None, engine: str) -> bool:
+ """
+ Whether Superset will mirror filters through this transform.
+
+ `validate_transform` with the messages discarded, so the Explore indicator
+ cannot advertise a mapping the save path recorded as inactive. Anything
+ cheaper here would be a second, weaker statement of the same rule, free to
+ drift from the one the save path applies.
+
+ Blocking issues count too. Jinja and non-deterministic transforms are
+ rejected on PUT, but `CreateDatasetCommand` and import do not validate the
+ mapping, so one can still reach the database -- and it would never mirror a
+ filter either.
+
+ Memoized because `partition_filter_mapping_summary` is serialized on every
+ Explore and dashboard load and this parses the transform. The key is
+ everything the answer depends on: `validate_transform` reads no session, no
+ locale and no config beyond `SQL_MAX_PARSE_LENGTH`, which bounds the parser
+ rather than changing a verdict within that bound.
+ """
+ return not validate_transform(transform, engine)
+
+
+def preview_partition_mapping( # pylint: disable=too-many-return-statements
+ datasource: SqlaTable,
+ *,
+ mapped_column: str,
+ value_transform: str | None,
+ sample_values: list[str],
+ operator: FilterOperator = FilterOperator.EQUALS,
+ is_monotonic: bool = False,
+ partition_column: str | None = None,
+) -> dict[str, Any]:
+ """
+ Evaluate a candidate mapping and describe the predicate it would emit.
+
+ Shares the evaluator -- and therefore the probe cache -- with the query
+ path, so preview and runtime cannot drift and a previewed transform warms
+ the chart path for free. The predicate itself comes from
+ `build_mirrored_predicates`, the same builder the query path uses, so
+ operator shapes cannot drift either: what the panel shows is what a chart
+ would emit.
+
+ Validation runs first and the engine second: a half-typed transform is by
+ definition unparseable, so most of what a text input produces costs zero
+ queries.
+
+ Every part of the mapping is taken from the request rather than the stored
+ dataset. The editor previews while the owner is still editing -- a mapping
+ that has to be saved before it can be checked is not a preview.
+ """
+ partition_column = partition_column or datasource.partition_column
+ if not partition_column:
+ return {
+ "valid": False,
+ "reason": "unconfigured",
+ "error": _("No partition column is set."),
+ }
+
+ columns_by_name = {str(column.column_name): column for column in datasource.columns}
+ if mapped_column not in columns_by_name:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _("%(name)s is not a column on this dataset.", name=mapped_column),
+ }
+
+ # The bail-out `resolve_partition_mapping` makes at query time, and that
+ # `partition_filter_mapping_summary` repeats for the Explore indicator.
+ # Without it here, preview reports a valid emitted predicate for a mapping
+ # no chart will ever mirror -- the one answer a preview panel must not give.
+ if has_active_advanced_data_type(columns_by_name[mapped_column]):
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _(
+ "%(name)s has an advanced data type, so its filters are "
+ "translated into their own predicate shape and cannot be "
+ "mirrored onto the partition column.",
+ name=mapped_column,
+ ),
+ }
+
+ engine = datasource.database.backend
+ for issue in validate_partition_mapping(
+ column_names=set(columns_by_name),
+ partition_column=str(partition_column),
+ partition_mapped_column=mapped_column,
+ main_dttm_col=datasource.main_dttm_col,
+ transform=value_transform,
+ engine=engine,
+ ):
+ return {
+ "valid": False,
+ # The parse failure is the one an owner sees constantly, and it is
+ # the only one the mockup gives its own headline to.
+ "reason": (
+ "parse"
+ if issue.field == "partition_value_transform"
+ and not is_parseable(value_transform, engine)
+ else "validation"
+ ),
+ "error": str(issue.message),
+ }
+
+ # The policy every other stored expression goes through. The save path
+ # applies it in `UpdateDatasetCommand._validate_partition_mapping`, but
+ # preview evaluates a candidate transform that has not been saved, so
+ # without this the gate had a door around it. See
+ # `stored_expression_error` for what is being kept out and why.
+ if reason := stored_expression_error(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ cast(str, value_transform),
+ ):
+ return {"valid": False, "reason": "validation", "error": reason}
+
+ mapping = PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=mapped_column,
+ value_transform=cast(str, value_transform),
+ is_monotonic=is_monotonic,
+ equality_is_safe=equality_mirrors_safely(
+ columns_by_name[mapped_column], datasource.database.db_engine_spec
+ ),
+ )
+ sample_input = _render_sample_input(
+ datasource, mapped_column, operator, sample_values
+ )
+
+ if operator not in PREVIEWABLE_OPERATORS:
+ # Checked before `mirrors`, which lets `TEMPORAL_RANGE` through when the
+ # transform is declared monotonic -- and the single sample value would
+ # then reach `handle_comparison_filter`, which has no case for a range
+ # and raises. The request schema rejects it too; this keeps the function
+ # honest for any other caller.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is mirrored as a pair of bounds, which "
+ "a preview of a single value cannot describe.",
+ operator=operator.value,
+ ),
+ }
+
+ if not mapping.mirrors(operator):
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is only mirrored when the transform "
+ "preserves ordering, which this one is not declared to do.",
+ operator=operator.value,
+ ),
+ }
+
+ return _preview_probe(
+ datasource,
+ mapping,
+ columns_by_name[mapped_column],
+ operator,
+ sample_values,
+ sample_input,
+ )
+
+
+def _preview_probe(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ mapped_col: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+ sample_input: str,
+) -> dict[str, Any]:
+ """
+ The half of a preview that needs the warehouse.
+
+ Split out from `preview_partition_mapping` so that the gates which answer
+ from the stored mapping alone stay readable as the single run of guard
+ clauses they are. Everything here has either run a query or decided not to.
+ """
+ value = datasource.mirror_probe_request(
+ operator,
+ _probe_input(datasource, mapped_col, operator, sample_values),
+ mapped_col,
+ )
+ if value is UNMIRRORABLE:
+ # The same step the chart path applies, so the preview cannot promise a
+ # mirror the query declines. Its own reason: the transform is fine and
+ # the engine evaluates it, the filter just carries more of the value
+ # than the engine compares on this column -- which is the column's type
+ # talking, not a broken expression.
+ return {
+ "valid": False,
+ "reason": "resolution",
+ "sample_input": sample_input,
+ "error": _(
+ "This engine compares less of a %(operator)s value on "
+ "%(column)s than the filter carries, so there is no mirror a "
+ "predicate on the partition column could stand in for. Map a "
+ "column the engine compares in full to mirror this operator.",
+ operator=operator.value,
+ column=mapped_col.column_name,
+ ),
+ }
+ errors: list[str] = []
+ type_errors: list[str] = []
+ predicates = build_mirrored_predicates(
+ datasource,
+ mapping,
+ [(operator, value)],
+ errors=errors,
+ type_errors=type_errors,
+ )
+ if type_errors:
+ # Its own reason, because "the database would not evaluate this" and
+ # "it evaluated and answered with the wrong kind of thing" are
+ # different problems with different fixes, and the owner is the only
+ # one who can tell which transform they meant to write.
+ return {
+ "valid": False,
+ "reason": "type",
+ "sample_input": sample_input,
+ "error": type_errors[0],
+ }
+ if not predicates:
+ return {
+ "valid": False,
+ "reason": "engine",
+ "sample_input": sample_input,
+ "error": (
+ _(
+ "The transform could not be evaluated against the "
+ "database: %(reason)s",
+ reason=errors[0],
+ )
+ if errors
+ else _("The transform could not be evaluated against the database.")
+ ),
+ }
+
+ return {
+ "valid": True,
+ "sample_input": sample_input,
+ "emitted_predicate": _render_predicate(datasource, predicates[0]),
+ }
+
+
+def _probe_input(
+ datasource: SqlaTable,
+ column: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+) -> Any:
+ """
+ The sample values as the query path would bind them.
+
+ The request carries samples as strings, and the probe is keyed on exactly
+ what it is handed, so passing them through raw asks the engine a different
+ question from the one a chart asks. A sample of ``2025`` on a numeric
+ column has to arrive as the integer the chart compares: under a transform
+ of ``typeof(:value)`` the raw string previewed ``'text'`` where the chart
+ emitted ``'integer'``. And because `_probe_cache_key` keys on each value's
+ ``repr``, the two also missed each other's cache entirely -- so the "a
+ previewed transform warms the chart path for free" claim in
+ `preview_partition_mapping`'s docstring did not actually hold.
+
+ Coerced by `filter_values_handler`, the same function the query path uses,
+ rather than by a second implementation of the same rules. Everything the
+ query path then does to the coerced value -- rendering an expression as a
+ literal, widening a bound, declining a comparison the engine resolves too
+ coarsely -- is `ExploreMixin.mirror_probe_request`'s, and the caller hands
+ this result straight to it.
+
+ Ranges are not previewable (see `PREVIEWABLE_OPERATORS`), so the bound
+ conversion `_collect_partition_mirror_range` applies -- a ``datetime`` into
+ the column's stored representation -- has no counterpart here.
+
+ Always answers with a value: nothing here declines. `UNMIRRORABLE` is
+ `mirror_probe_request`'s to return, and the caller hands this straight to it.
+ """
+ is_list = operator == FilterOperator.IN
+ column_spec = datasource.db_engine_spec.get_column_spec(native_type=column.type)
+ handled = datasource.filter_values_handler(
+ # `list[str]` is not a `list[FilterValue]` to mypy, invariantly, even
+ # though every `str` is a `FilterValue`.
+ values=cast(FilterValues, sample_values if is_list else sample_values[0]),
+ operator=operator,
+ target_generic_type=(
+ column_spec.generic_type if column_spec else utils.GenericDataType.STRING
+ ),
+ target_native_type=column.type,
+ is_list_target=is_list,
+ db_engine_spec=datasource.db_engine_spec,
+ db_extra=datasource.db_extra,
+ )
+ # No `ColumnElement` conversion here: an epoch-milliseconds sample comes back
+ # as engine SQL rather than a value, and `mirror_probe_request` renders it --
+ # the same step, on the same values, as for a chart filter.
+ return handled
Review Comment:
Preview returns `filter_values_handler`'s result directly, but the chart path additionally runs `_array_mirror_probe_value` for array columns before probing, so the two evaluate different inputs. On ClickHouse with `tags Array(Int32)` and `length(:value)`, previewing `==` with `[1, 2]` binds the text and shows `p = 6 OR p IS NULL`, whereas a chart filter probes `array(1, 2)` and emits `p = 2 OR p IS NULL`. Should the preview apply the same array conversion (or refuse array columns) so it shows what the query will emit?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2730 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+#: Returned by `ExploreMixin.mirror_probe_request` for a filter no mirror can
+#: stand in for: one the engine compares more coarsely than the value carries, a
+#: value it cannot render as a literal, or an ``IN`` list with a member of
+#: either kind. A sentinel rather than `None`, because `None` is a filter value
+#: in its own right.
+#:
+#: Lives here rather than beside that method so the preview can read it too:
+#: `superset.models.helpers` imports this module, so the sentinel can only cross
+#: the boundary in this direction. Both callers have to recognise the same
+#: object -- a preview that answered "valid" for a request the chart path
+#: declines is the drift this is here to prevent.
+UNMIRRORABLE = object()
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error( # noqa: C901
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ And it must be a *read*. Shape is a separate question from effect: a bare
+ scalar expression can still write, so `SQLStatement.is_mutating` is asked
+ too -- the same question SQL Lab and the chart executor ask before letting
+ SQL run. See the gate itself for what that reaches and what it does not.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ # Also ahead of the parse, and for a stronger reason than cost: every gate
+ # below reasons about the parse tree, and this is the one construct that
+ # makes the parse tree describe a different statement from the one the
+ # engine runs. Checked here as well as in `validate_transform` because this
+ # is the door a row written by an earlier release still comes through.
+ if contains_executable_comment(transform):
+ return str(
+ _(
+ "A partition value transform cannot contain a MySQL "
+ "executable comment, which the database executes and every "
+ "validator reads as a comment."
+ )
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The read-only gate, which nothing above implies. The shape gates ask what
+ # the transform *selects*; this asks what evaluating it *does*, and a bare
+ # scalar expression can still write. `nextval(:value)` on PostgreSQL
+ # advances a sequence: one function call, no clause, no sub-query, and not
+ # in the default `DISALLOWED_SQL_FUNCTIONS` either -- so every gate above
+ # passes it and the probe then runs it. `setval` is the same shape, and
+ # `exp.Execute` and the opaque-`exp.Command` forms arrive the same way.
+ #
+ # The large-object writers (`lo_export`, `lowrite`, `lo_from_bytea`, ...)
+ # are caught here too, and the shipped denylist happens to name them as
+ # well -- but that is config an operator can replace, while this is not.
+ #
+ # `is_mutating` is the same question SQL Lab, `get_virtual_table_metadata`
+ # and the chart executor ask before letting SQL run, so a transform is held
+ # to the bar the rest of Superset already sets rather than to one invented
+ # here. Unconditional rather than gated on `Database.allow_dml`: a transform
+ # is a scalar function of `:value` by definition, so there is no legitimate
+ # mutating one, and the probe runs on a cache schedule nobody chose -- a
+ # write would repeat every time the entry expired.
+ #
+ # It bears saying what this does not reach. A user-defined function whose
+ # body writes is a plain call no parser can tell from `lower(:value)`, and
+ # `is_mutating`'s function-name walk is PostgreSQL-only by design, since the
+ # same names are read-only elsewhere. Neither residual is specific to this
+ # feature -- a dataset editor can already have the engine evaluate an
+ # arbitrary expression through a calculated column or a virtual dataset's
+ # SQL -- and closing them means authorizing the preview against the
+ # database, not parsing harder.
+ if statement.is_mutating():
+ return str(
+ _(
+ "A partition value transform cannot change data. It is "
+ "evaluated against the database to check that it mirrors, so "
+ "it has to be a read."
+ )
+ )
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the probe
+ uninspected -- string elements are escaped by the dialect's own literal
+ processor. `probe_sql_is_evaluable` then re-reads the finished query, which
+ is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def _placeholder_is_bindable(transform: str) -> bool:
+ """
+ Whether SQLAlchemy's ``text()`` can see ``:value`` as a bound parameter.
+
+ `VALUE_PLACEHOLDER_RE` is ``:value\b``, which matches the placeholder in a
+ Postgres cast such as ``:value::bigint``. SQLAlchemy's own bind scan is
+ ``(?<![:\\w$]):([\\w$]+)(?![:\\w$])`` -- note the trailing exclusion -- so a
+ following colon stops it: ``text(":value::bigint")`` reports a parameter
+ named ``valu``, and ``.bindparams(bindparam("value"))`` then raises
+ ``ArgumentError``.
+
+ `_probe` swallows that, so the only symptom was a perfectly valid transform
+ whose mapping silently never pruned, and a preview reporting an engine
+ failure for SQL that was never sent. Every write-side gate passes the
+ transform: it parses, it is a bare expression, and the placeholder *is* in
+ an executable position.
+
+ Answered by attempting the bind itself rather than by pattern-matching
+ ``::`` or reading ``text()``'s private parameter map, so this cannot
+ disagree with what `build_probe_sql` is about to do -- on any dialect, or on
+ a SQLAlchemy whose scan changes.
+ """
+ try:
+ sa.text(transform).bindparams(sa.bindparam("value", value=None))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return False
+ return True
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ bindable = _placeholder_is_bindable(transform)
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ elif bindable:
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ rendered = _compile_literal(clause, dialect)
+ else:
+ # `text()` cannot see the placeholder (see
+ # `_placeholder_is_bindable`), so the value is rendered by the
+ # dialect's own literal processor first and substituted as SQL
+ # text. The same two steps in the other order: binding exists to
+ # get the value through that processor, and `_compile_literal`
+ # inlines the result either way, so this is the same string by a
+ # different route -- not a loosening of the "never interpolate a
+ # raw value" rule. `parse_skeleton` substitutes literally, so a
+ # rendered literal containing a backslash is safe here.
+ rendered = parse_skeleton(
+ transform, _compile_literal(sa.literal(value), dialect)
+ )
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Four things have to hold, and all four are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ # Before the parse, because this gate's whole contract is that what the
+ # parse describes is what the engine will run, and an executable comment is
+ # precisely the text where that stops being true. The transform is already
+ # refused for carrying one; this covers the compiled statement, so no later
+ # change to how values are rendered can reintroduce it behind the gates
+ # below.
+ if contains_executable_comment(sql):
+ return False
+
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if not isinstance(statement, SQLStatement):
+ # A dialect whose statements this gate cannot take apart -- KQL -- gets
+ # no probe rather than an unchecked one. It never had one: the clause
+ # inspection below is implemented for SQL statements only, and the
+ # alternative to declining here is an `AttributeError` that `_probe`
+ # swallows into the same outcome, less legibly.
+ return False
+ if statement.has_subquery():
+ return False
+ if statement.get_clause_names() - {"from"}:
+ return False
+ if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+ """
+ The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+ Parsed rather than string-compared so that the comparison in
+ `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+ not parse answers ``None``, which no statement carrying a FROM can match --
+ the probe then declines, which is the right way for an unreadable engine
+ constant to fail.
+ """
+ if not from_suffix.strip():
+ return None
+ try:
+ return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+ except SupersetParseError:
+ return None
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=values is not None and not any(value is None for value in values),
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ from_suffix = database.db_engine_spec.select_without_from_suffix
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ from_suffix,
+ )
+ if not probe_sql_is_evaluable(
+ sql, database.backend, len(distinct), from_suffix
+ ):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _execution_identity(database: Database) -> str | None:
+ """
+ Who the warehouse will run the probe as, when that can vary by caller.
+
+ `_probe_cache_key` keys on the `Database` record, which is the *connection*
+ -- not the identity it is opened under. Two hooks make that identity a
+ function of the Superset user instead:
+
+ * ``impersonate_user`` on the database, which hands the effective username
+ to `db_engine_spec.impersonate_user`;
+ * ``DB_CONNECTION_MUTATOR``, which receives the effective username and may
+ return an entirely different account's URL.
+
+ Under either one, a cached probe result computed under user A's grants was
+ served to user B, and the preview echoed it back in ``emitted_predicate``.
+ A transform wrapping a read-capable function the denylist does not name --
+ Oracle's ``DBMS_XMLGEN.GETXML`` is the worked example -- then leaks across
+ users who were never allowed the same rows.
+
+ Returns ``None`` when neither hook is configured, which is the common case
+ and deliberately leaves the key as it was: the cache exists to keep a
+ synchronous warehouse round trip off the chart-query path, and keying every
+ deployment on the username would cost every deployment the hit rate to fix
+ the two that need it.
+
+ The *Superset* username rather than the resolved warehouse account, because
+ it is the input both hooks branch on, and reading it needs no URL parse and
+ puts no credential in the key.
+ """
+ if not (database.impersonate_user or app.config["DB_CONNECTION_MUTATOR"]):
+ return None
+ return get_username()
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _mirror_verdict_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str:
+ """
+ `_probe_cache_key` without the values.
+
+ Whether a transform can be evaluated at all is a property of the transform
+ and the connection, not of the filter that happened to be probing it, so
+ one chart's answer settles the question for the next one.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ # Whether a transform *can* be evaluated is a property of the
+ # transform and the connection -- but under impersonation the
+ # connection is per-user, and a function one account may call can
+ # be refused to another. See `_execution_identity`.
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_verdict:{digest}"
+
+
+def record_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ *,
+ mirrors: bool,
+) -> None:
+ """
+ Remember whether this transform produced a mirror, for the UI to read.
+
+ Advisory only. Nothing in the query path consults it: a probe that failed
+ once is retried on the next chart exactly as it is today, because declining
+ to prune for a whole cache timeout over one transient engine blip is the
+ trade `evaluate_transform` deliberately refuses -- see the comment where it
+ declines to cache a failure.
+
+ What this is for is the *claim*. `is_transform_active` parses the transform
+ and no more, so a transform the database rejects -- a misspelled function
+ is the common case -- is "active", and the editor's banner and Explore's
+ pruning glyph promise a speed-up that never happens. A promise is exactly
+ the thing that may be withheld on one bad answer and restored on a good
+ one, which is why this is a separate entry from the probe's own results
+ rather than a relaxation of that rule.
+
+ Written by `_run_probe`, so the preview endpoint -- which shares the
+ evaluator -- settles the question before the owner has even saved.
+ """
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(
+ _mirror_verdict_cache_key(database, catalog, schema, transform),
+ mirrors,
+ timeout=timeout,
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform verdict", exc_info=True)
+
+
+def known_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> bool | None:
+ """
+ The last verdict `record_mirror_verdict` stored, or `None` if there is none.
+
+ `None` is the honest answer on a cold cache and is deliberately not `False`:
+ reporting a working mapping as broken until something probes it would
+ trade one wrong claim for another. The alternative -- probing from the
+ read side -- would put a warehouse round trip on every Explore and
+ dashboard load, and a failing transform is not cached at all, so it would
+ be a round trip every single time.
+ """
+ try:
+ verdict = cache_manager.cache.get(
+ _mirror_verdict_cache_key(database, catalog, schema, transform)
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return verdict if isinstance(verdict, bool) else None
+
+
+def _compile_literal(element: Any, dialect: Dialect | None) -> str:
+ """
+ Compile with inline literals, undoing the paramstyle's percent doubling.
+
+ Both ``TextClause`` and literal compilation run the dialect's
+ ``post_process_text``, which doubles every ``%`` whenever the identifier
+ preparer asks it to -- true for MySQL and Postgres and for every spec
+ inheriting their paramstyle. That doubling exists so a later DBAPI
+ parameter-interpolation pass can undo it, and the probe has no such pass:
+ it executes with no bound parameters at all. So a transform of
+ ``date_format(:value, '%Y%m%d')`` reaches the warehouse asking for the
+ literal string ``%%Y%%m%%d``, the probe returns that instead of a date, and
+ the mirrored predicate drops every row the filter keeps.
+
+ The same normalization ``Database.compile_sqla_query`` applies for the same
+ reason. ``_double_percents`` is private and not guaranteed on a third-party
+ dialect, hence the ``getattr`` default.
+ """
+ compiled = str(
+ element.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
+ )
+ if dialect is not None and getattr(
+ dialect.identifier_preparer, "_double_percents", False
+ ):
+ compiled = compiled.replace("%%", "%")
+ return compiled
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be *asked* to stand in for itself, and the transform
+ cannot carry Jinja or call a non-deterministic function. Tier 2
+ (``blocking=False``) is everything that merely leaves the mapping inactive
+ -- including a self-mapping nobody asked for, where the partition column
+ merely happens to be the default datetime column.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column == partition_column:
+ # Asked for explicitly, so report it as the mistake it is.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+ elif not partition_mapped_column and main_dttm_col == partition_column:
+ # Resolved onto itself only because the default datetime column happens
+ # to be the partition column -- a state metadata sync could produce
+ # without anyone asking for it. The mapping is inert either way, since
+ # `resolve_partition_mapping` bails out on it, so this reports and lets
+ # the write through: blocking here means a dataset already in the state
+ # can never be saved again, not even to change its description, and
+ # there is no field whose edit would clear the error first.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "%(name)s is both the partition column and the default "
+ "datetime column, so the mapping points at itself and "
+ "stays inactive. Set a mapped column override, or change "
+ "the default datetime column.",
+ name=partition_column,
+ ),
+ blocking=False,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def drop_unmapped_value_transforms(
+ columns: list[dict[str, Any]] | None,
+ *,
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ names_by_id: dict[int, str] | None = None,
+) -> list[str]:
+ """
+ Null the value transform on every *incoming* column the mapping cannot mirror.
+
+ The write-side twin of `DatasetDAO.clear_unmapped_partition_transforms`,
+ which answers for the model. A mapping has exactly one mirrored column, so
+ at most one column may carry a transform. One parked on any other column is
+ invisible -- no row but the mapped one renders a transform -- and yet it is
+ stored, and it goes live the moment the mapped column resolves back to it.
+ Clearing an override is enough to do that: a null
+ ``partition_mapped_column`` means "follow ``main_dttm_col``".
+
+ Ungated on the feature flag, unlike its model-level twin, and the difference
+ is what each one discards. That one drops stored configuration, so with the
+ flag off it would be pure loss. This one drops only a value the request in
+ hand is asking to write where the invariant says none may live -- and the
+ flag-off window is precisely when such a value gets parked for later, since
+ the editor hides these fields and the model-level pass declines to run.
+
+ Three writers reach the columns with no effective model-level pass between
+ them, which is why this exists at all: the deprecated
+ ``POST /datasource/save/``, which writes straight through
+ `update_from_object` and so never had one; and a
+ ``PUT /api/v1/dataset/<pk>`` or a dataset import made while the flag is
+ off, where the pass runs on both sides of the write and declines on both.
+
+ Mutates the payload in place, because every caller hands its own request
+ dict straight on to the code that writes it. Returns the names it cleared,
+ so the caller can say so in a log: this is a silent correction to a payload
+ whose author may have meant it.
+
+ A column whose payload mentions neither field is left alone. "Incoming" is
+ the whole scope -- a transform already in storage on a column this request
+ says nothing about is the model-level pass's business, under its own flag.
+
+ The mapped column resolves the way every other reader resolves it,
+ ``partition_mapped_column or main_dttm_col``, and resolves to nothing
+ without a partition column -- in which case no column may hold a transform
+ either.
+
+ :param names_by_id: how to read the name off a payload entry that gives
+ only an ``id``. `DatasetDAO._upsert_columns` identifies an existing
+ column by its primary key and lets ``column_name`` be omitted -- the
+ column keeps the name it has -- so without this an ordinary PUT looked
+ like a payload of nameless columns, none of which matched the mapped
+ one, and every transform in it was dropped. Callers whose writer keys
+ on the name instead (`update_from_object`, the importer) pass nothing.
+ An entry this cannot name is left alone rather than guessed at.
+ """
+ mapped_column = (
+ (partition_mapped_column or main_dttm_col) if partition_column else None
+ )
+ cleared: list[str] = []
+ for column in columns or []:
+ name = column.get("column_name")
+ if name is None and names_by_id is not None:
+ column_id = column.get("id")
+ if column_id is not None:
+ name = names_by_id.get(column_id)
+ if name is None or name == mapped_column:
+ continue
+ if column.get("partition_value_transform") or column.get(
+ "partition_transform_is_monotonic"
+ ):
+ column["partition_value_transform"] = None
+ column["partition_transform_is_monotonic"] = False
+ cleared.append(name)
+ return cleared
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if contains_executable_comment(transform):
+ # Blocking, and checked on raw text next to the Jinja gate because no
+ # parse reports it: sqlglot reads `/*!50000 ... */` as comment data
+ # while MySQL and MariaDB execute it, so every shape gate downstream
+ # inspects a statement the engine will not run. See
+ # `EXECUTABLE_COMMENT_RE`.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform cannot contain a MySQL executable "
+ "comment (/*! ... */ or /*M! ... */). Those are comments "
+ "to every validator and statement text to the database, "
+ "so what would run is not what was checked."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_bare_expression(transform, engine):
+ # Blocking, and deliberately placed in `validate_transform` rather than
+ # only at the probe: one issue here closes the PUT, the importer, the
+ # query-time gate through `is_transform_active`, the Explore indicator's
+ # active verdict and the preview endpoint, all of which already consult
+ # this function.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform must be a single SQL expression. It "
+ "cannot carry a FROM, WHERE, GROUP BY or any other clause, "
+ "and it cannot contain a sub-query."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not contains_value_placeholder(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform must contain the :value placeholder, "
+ "which stands for the filter value being mirrored."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not placeholder_is_executable(transform, engine):
+ # Blocking, and for the same reason the shape gate above is: this is
+ # the function the PUT, the importer, `is_transform_active`, the
+ # Explore indicator and the preview all consult, so one issue here
+ # closes every door at once. A placeholder inside a string literal is
+ # a sub-query the engine will run once a filter value closes the quote;
+ # one inside a comment silently eats the probe's own alias.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The :value placeholder must appear where the engine will "
+ "evaluate it. It cannot sit inside a string literal or a "
+ "comment."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if functions := find_non_deterministic_functions(transform, engine):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform calls %(functions)s, whose result "
+ "depends on when and where it runs. The transform is "
+ "evaluated in a separate session and the result is cached, "
+ "so the emitted predicate would freeze a snapshot of that "
+ "moment.",
+ functions=", ".join(sorted(functions)),
+ ),
+ blocking=True,
+ )
+ ]
+
+ return []
+
+
+@lru_cache(maxsize=LRU_CACHE_MAX_SIZE)
+def is_transform_active(transform: str | None, engine: str) -> bool:
+ """
+ Whether Superset will mirror filters through this transform.
+
+ `validate_transform` with the messages discarded, so the Explore indicator
+ cannot advertise a mapping the save path recorded as inactive. Anything
+ cheaper here would be a second, weaker statement of the same rule, free to
+ drift from the one the save path applies.
+
+ Blocking issues count too. Jinja and non-deterministic transforms are
+ rejected on PUT, but `CreateDatasetCommand` and import do not validate the
+ mapping, so one can still reach the database -- and it would never mirror a
+ filter either.
+
+ Memoized because `partition_filter_mapping_summary` is serialized on every
+ Explore and dashboard load and this parses the transform. The key is
+ everything the answer depends on: `validate_transform` reads no session, no
+ locale and no config beyond `SQL_MAX_PARSE_LENGTH`, which bounds the parser
+ rather than changing a verdict within that bound.
+ """
+ return not validate_transform(transform, engine)
+
+
+def preview_partition_mapping( # pylint: disable=too-many-return-statements
+ datasource: SqlaTable,
+ *,
+ mapped_column: str,
+ value_transform: str | None,
+ sample_values: list[str],
+ operator: FilterOperator = FilterOperator.EQUALS,
+ is_monotonic: bool = False,
+ partition_column: str | None = None,
+) -> dict[str, Any]:
+ """
+ Evaluate a candidate mapping and describe the predicate it would emit.
+
+ Shares the evaluator -- and therefore the probe cache -- with the query
+ path, so preview and runtime cannot drift and a previewed transform warms
+ the chart path for free. The predicate itself comes from
+ `build_mirrored_predicates`, the same builder the query path uses, so
+ operator shapes cannot drift either: what the panel shows is what a chart
+ would emit.
+
+ Validation runs first and the engine second: a half-typed transform is by
+ definition unparseable, so most of what a text input produces costs zero
+ queries.
+
+ Every part of the mapping is taken from the request rather than the stored
+ dataset. The editor previews while the owner is still editing -- a mapping
+ that has to be saved before it can be checked is not a preview.
+ """
+ partition_column = partition_column or datasource.partition_column
+ if not partition_column:
+ return {
+ "valid": False,
+ "reason": "unconfigured",
+ "error": _("No partition column is set."),
+ }
+
+ columns_by_name = {str(column.column_name): column for column in datasource.columns}
+ if mapped_column not in columns_by_name:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _("%(name)s is not a column on this dataset.", name=mapped_column),
+ }
+
+ # The bail-out `resolve_partition_mapping` makes at query time, and that
+ # `partition_filter_mapping_summary` repeats for the Explore indicator.
+ # Without it here, preview reports a valid emitted predicate for a mapping
+ # no chart will ever mirror -- the one answer a preview panel must not give.
+ if has_active_advanced_data_type(columns_by_name[mapped_column]):
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _(
+ "%(name)s has an advanced data type, so its filters are "
+ "translated into their own predicate shape and cannot be "
+ "mirrored onto the partition column.",
+ name=mapped_column,
+ ),
+ }
+
+ engine = datasource.database.backend
+ for issue in validate_partition_mapping(
+ column_names=set(columns_by_name),
+ partition_column=str(partition_column),
+ partition_mapped_column=mapped_column,
+ main_dttm_col=datasource.main_dttm_col,
+ transform=value_transform,
+ engine=engine,
+ ):
+ return {
+ "valid": False,
+ # The parse failure is the one an owner sees constantly, and it is
+ # the only one the mockup gives its own headline to.
+ "reason": (
+ "parse"
+ if issue.field == "partition_value_transform"
+ and not is_parseable(value_transform, engine)
+ else "validation"
+ ),
+ "error": str(issue.message),
+ }
+
+ # The policy every other stored expression goes through. The save path
+ # applies it in `UpdateDatasetCommand._validate_partition_mapping`, but
+ # preview evaluates a candidate transform that has not been saved, so
+ # without this the gate had a door around it. See
+ # `stored_expression_error` for what is being kept out and why.
+ if reason := stored_expression_error(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ cast(str, value_transform),
+ ):
+ return {"valid": False, "reason": "validation", "error": reason}
+
+ mapping = PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=mapped_column,
+ value_transform=cast(str, value_transform),
+ is_monotonic=is_monotonic,
+ equality_is_safe=equality_mirrors_safely(
+ columns_by_name[mapped_column], datasource.database.db_engine_spec
+ ),
+ )
+ sample_input = _render_sample_input(
+ datasource, mapped_column, operator, sample_values
+ )
+
+ if operator not in PREVIEWABLE_OPERATORS:
+ # Checked before `mirrors`, which lets `TEMPORAL_RANGE` through when the
+ # transform is declared monotonic -- and the single sample value would
+ # then reach `handle_comparison_filter`, which has no case for a range
+ # and raises. The request schema rejects it too; this keeps the function
+ # honest for any other caller.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is mirrored as a pair of bounds, which "
+ "a preview of a single value cannot describe.",
+ operator=operator.value,
+ ),
+ }
+
+ if not mapping.mirrors(operator):
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is only mirrored when the transform "
Review Comment:
This message says the filter is only mirrored when the transform preserves ordering for every operator that fails `mirrors()`, but `=`/`IN` on a string column are also rejected by `equality_mirrors_safely`, independent of monotonicity. On MySQL, `country` mapped through `lower(:value)` previews `IN` with this text; the owner ticks the ordering box and the same error comes back. Could the reason distinguish a comparison-semantics rejection from missing monotonicity?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4225234813
##########
superset/migrations/versions/2026-09-23_00-01_a7f3c2e91d84_add_partition_filter_mapping.py:
##########
@@ -0,0 +1,101 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""add partition filter mapping
+
+Adds the four columns behind the ``PARTITION_FILTER_MAPPING`` feature:
+
+- ``tables.partition_column`` -- the physical column the engine partitions on
+- ``tables.partition_mapped_column`` -- explicit override for the column whose
+ filters are mirrored; NULL means "follow ``main_dttm_col``"
+- ``table_columns.partition_value_transform`` -- the ``:value`` expression
+- ``table_columns.partition_transform_is_monotonic`` -- gates range operators
+
+The Continuum shadow tables get the same columns so dataset version history and
+restore keep working.
+
+Revision ID: a7f3c2e91d84
+Revises: 00fab727cd0a
+Create Date: 2026-08-31 22:30:00.000000
+
+"""
+
+import sqlalchemy as sa
+
+from superset.migrations.shared.utils import add_columns, drop_columns
+
+# revision identifiers, used by Alembic.
+revision = "a7f3c2e91d84"
+down_revision = "00fab727cd0a"
Review Comment:
Master's #44992 added `e4a7c2b9d1f3` on `00fab727cd0a` too, so merging master leaves two Alembic heads and `test_migrations_have_one_head` fails. Re-parent onto it (and update `Revises:` on line 31).
```suggestion
down_revision = "e4a7c2b9d1f3"
```
##########
superset/migrations/versions/2026-09-23_00-01_a7f3c2e91d84_add_partition_filter_mapping.py:
##########
@@ -0,0 +1,101 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""add partition filter mapping
+
+Adds the four columns behind the ``PARTITION_FILTER_MAPPING`` feature:
+
+- ``tables.partition_column`` -- the physical column the engine partitions on
+- ``tables.partition_mapped_column`` -- explicit override for the column whose
+ filters are mirrored; NULL means "follow ``main_dttm_col``"
+- ``table_columns.partition_value_transform`` -- the ``:value`` expression
+- ``table_columns.partition_transform_is_monotonic`` -- gates range operators
+
+The Continuum shadow tables get the same columns so dataset version history and
+restore keep working.
+
+Revision ID: a7f3c2e91d84
+Revises: 00fab727cd0a
+Create Date: 2026-08-31 22:30:00.000000
+
+"""
+
+import sqlalchemy as sa
+
+from superset.migrations.shared.utils import add_columns, drop_columns
+
+# revision identifiers, used by Alembic.
+revision = "a7f3c2e91d84"
+down_revision = "00fab727cd0a"
Review Comment:
Master's https://github.com/apache/superset/pull/44992 added `e4a7c2b9d1f3` on `00fab727cd0a` too, so merging master leaves two Alembic heads and `test_migrations_have_one_head` fails. Re-parent onto it (and update `Revises:` on line 31).
```suggestion
down_revision = "e4a7c2b9d1f3"
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4334098368
##########
superset/views/datasource/views.py:
##########
@@ -95,6 +104,129 @@ def _load_dataset_for_samples(
return dataset, None
+def _partition_transform_error(
+ orm_datasource: Any,
+ datasource_dict: dict[str, Any],
+) -> str | None:
+ """
+ The first column whose incoming value transform may not be stored, if any.
+
+ Only datasets carry a partition mapping, and only a transform the request
+ actually changes is worth refusing over -- re-sending a value already in
+ storage is what a GET-then-PUT client does, and a transform stored before
+ this check existed is disarmed at probe time instead.
+
+ Both gates the other writers apply, not just the storability one.
+ `stored_expression_error` asks whether the expression may be *run*;
+ `validate_transform`'s blocking tier asks whether it may be *stored* --
+ Jinja, an executable comment, a non-deterministic function, a placeholder
+ the engine will not read. The REST PUT and the importer reach both, and this
+ endpoint reached only the first, so `random() + :value` saved here with a
+ 200 and then failed `UpdateDatasetCommand`'s validation on every later edit,
+ including a description-only PUT. The dataset could not be saved again until
+ someone edited the transform.
+ """
+ incoming = [
+ column
+ for column in datasource_dict.get("columns") or []
+ if column.get("partition_value_transform")
+ ]
+ database = getattr(orm_datasource, "database", None)
+ if not incoming or database is None:
+ return None
+
+ stored = {
+ column.column_name: column.partition_value_transform
+ for column in orm_datasource.columns
+ }
+ for column in incoming:
+ transform = column["partition_value_transform"]
+ if transform == stored.get(column.get("column_name")):
+ continue
+ reason = stored_expression_error(
Review Comment:
This calls `stored_expression_error` for every changed transform, but that gate fails closed on anything that does not parse, and the REST PUT (`update.py`, guarded by `is_unfinished`) and the importer deliberately let a half-typed transform through and store the mapping as inactive. With a valid `event_time -> dt_epoch` mapping, posting the existing datasource payload to `/datasource/save/` with the transform changed to `unix_timestamp(:value` returns 422 and rejects the whole save, including any unrelated edits in the same payload, while the same payload via PUT succeeds. Should this apply the same `not is_unfinished(transform, database.backend)` exemption before calling the gate?
##########
tests/unit_tests/connectors/sqla/partition_mapping_test.py:
##########
@@ -0,0 +1,3643 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Unit tests for ``superset.connectors.sqla.partition_mapping``."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from decimal import Decimal
+from importlib import import_module
+from typing import Any, cast
+from unittest.mock import MagicMock, patch, PropertyMock
+
+import pandas as pd
+import pytest
+from dateutil.relativedelta import relativedelta
+from flask import Flask
+from pytest_mock import MockerFixture
+from sqlalchemy.dialects import mysql, postgresql
+
+from superset.config import DISALLOWED_SQL_FUNCTIONS
+from superset.connectors.sqla.models import SqlaTable, TableColumn
+from superset.connectors.sqla.partition_mapping import (
+ _mirror_verdict_cache_key,
+ _placeholder_is_bindable,
+ _probe_cache_key,
+ _reads_as_temporal,
+ _render_literal,
+ _render_predicate,
+ BARE_WALL_CLOCK_KEYWORDS,
+ build_mirrored_predicates,
+ build_probe_sql,
+ contains_executable_comment,
+ contains_jinja,
+ contains_value_placeholder,
+ drop_unmapped_value_transforms,
+ equality_mirrors_safely,
+ evaluate_transform,
+ find_non_deterministic_functions,
+ grain_bucket_width,
+ GRAIN_BUCKET_WIDTHS,
+ is_bare_expression,
+ is_parseable,
+ is_transform_active,
+ is_unfinished,
+ known_mirror_verdict,
+ literal_round_trips,
+ MappingValidationIssue,
+ mirror_operator,
+ MIRRORABLE_ALWAYS,
+ MIRRORABLE_IF_MONOTONIC,
+ mirrorable_operators,
+ NON_DETERMINISTIC_FUNCTIONS,
+ parse_error_detail,
+ placeholder_is_executable,
+ probe_sql_is_evaluable,
+ probed_value_type_error,
+ RawProbeValue,
+ resolve_partition_mapping,
+ stored_expression_error,
+ validate_partition_mapping,
+ validate_transform,
+)
+from superset.constants import TimeGrain
+from superset.db_engine_specs.base import BaseEngineSpec
+from superset.db_engine_specs.mysql import MySQLEngineSpec
+from superset.db_engine_specs.oracle import OracleEngineSpec
+from superset.db_engine_specs.postgres import PostgresEngineSpec
+from superset.models.core import Database
+from superset.sql.parse import SQLStatement
+from superset.utils.core import FilterOperator, GenericDataType, override_user
+
+
+@pytest.fixture(autouse=True)
+def real_probe_cache(app: Flask) -> Any:
+ """
+ The test app runs a null cache, which would make every cache assertion here
+ vacuously pass. Swap in a real in-memory one for the duration.
+ """
+ from flask_caching import Cache
+
+ from superset.extensions import cache_manager
+
+ cache = Cache(config={"CACHE_TYPE": "SimpleCache", "CACHE_DEFAULT_TIMEOUT": 300})
+ cache.init_app(app)
+ original = cache_manager._cache # noqa: SLF001
+ cache_manager._cache = cache # noqa: SLF001
+ yield
+ cache_manager._cache = original # noqa: SLF001
+
+
+@pytest.fixture(autouse=True)
+def enable_partition_filter_mapping(app: Flask) -> Any:
+ """The feature ships off; every test here exercises it on."""
+ original = app.config["DEFAULT_FEATURE_FLAGS"].get("PARTITION_FILTER_MAPPING")
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = True
+ yield
+ if original is None:
+ del app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"]
+ else:
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = original
+
+
+def _table(**kwargs: Any) -> SqlaTable:
+ database = Database(database_name="test_db", sqlalchemy_uri="sqlite://")
+ defaults: dict[str, Any] = {
+ "table_name": "web_events",
+ "database": database,
+ "main_dttm_col": "event_time",
+ "columns": [
+ TableColumn(column_name="event_time", is_dttm=True, type="TIMESTAMP"),
+ TableColumn(
+ column_name="dt_epoch",
+ type="BIGINT",
+ partition_value_transform=None,
+ ),
+ TableColumn(column_name="country", type="VARCHAR"),
+ TableColumn(column_name="region_key", type="VARCHAR"),
+ ],
+ }
+ defaults.update(kwargs)
+ return SqlaTable(**defaults)
+
+
+def _mapped_table(
+ *,
+ partition_column: str = "dt_epoch",
+ mapped_column: str = "event_time",
+ transform: str | None = "unix_timestamp(:value)",
+ monotonic: bool = True,
+ partition_mapped_column: str | None = None,
+ main_dttm_col: str | None = "event_time",
+) -> SqlaTable:
+ table = _table(main_dttm_col=main_dttm_col)
+ table.partition_column = partition_column
+ table.partition_mapped_column = partition_mapped_column
+ for column in table.columns:
+ if column.column_name == mapped_column:
+ column.partition_value_transform = transform
+ column.partition_transform_is_monotonic = monotonic
+ return table
+
+
+# ---------------------------------------------------------------------------
+# §2 — operator safety matrix
+# ---------------------------------------------------------------------------
+
+
+def test_equality_and_in_are_always_mirrorable() -> None:
+ """``=`` and ``IN`` are safe for any function ``T``."""
+ assert MIRRORABLE_ALWAYS == {FilterOperator.EQUALS, FilterOperator.IN}
+
+
+def test_range_operators_require_a_monotonic_transform() -> None:
+ assert MIRRORABLE_IF_MONOTONIC == {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+ }
+
+
+def test_mirrorable_operators_excludes_ranges_when_not_monotonic() -> None:
+ assert mirrorable_operators(is_monotonic=False) == MIRRORABLE_ALWAYS
+
+
+def test_mirrorable_operators_includes_ranges_when_monotonic() -> None:
+ assert mirrorable_operators(is_monotonic=True) == (
+ MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+ )
+
+
+@pytest.mark.parametrize(
+ "operator",
+ [
+ FilterOperator.NOT_EQUALS,
+ FilterOperator.NOT_IN,
+ FilterOperator.LIKE,
+ FilterOperator.ILIKE,
+ FilterOperator.NOT_LIKE,
+ FilterOperator.NOT_ILIKE,
+ FilterOperator.IS_NULL,
+ FilterOperator.IS_NOT_NULL,
+ FilterOperator.IS_TRUE,
+ FilterOperator.IS_FALSE,
+ ],
+)
+def test_negations_and_pattern_matches_are_never_mirrorable(
+ operator: FilterOperator,
+) -> None:
+ """
+ ``T`` is not injective, so ``col != v`` does **not** imply ``T(col) != T(v)``:
+ mirroring it would drop rows the original filter keeps.
+ """
+ assert operator not in mirrorable_operators(is_monotonic=True)
+
+
+def test_equality_is_dropped_when_the_engine_does_not_compare_byte_exactly() -> None:
+ """
+ "Safe for any function ``T``" reasons about value equality: ``T`` is a
+ function, so ``col = v`` gives ``T(col) = T(v)``. The engine reasons about
+ *SQL* equality, and the two part company under a case-insensitive
+ collation -- a stored ``'us'`` satisfies a filter for ``'US'`` while the
+ mirror ``hex('US')`` excludes the row, and the chart loses it silently.
+ """
+ assert mirrorable_operators(is_monotonic=False, equality_is_safe=False) == set()
+
+
+def test_ranges_survive_an_unsafe_equality() -> None:
+ """
+ Range mirroring already rests on the owner declaring ``T``
+ order-preserving with respect to the column's own order -- an assertion
+ about the very comparison semantics this gate checks for. Equality has no
+ such declaration behind it, which is why only equality is withdrawn.
+ """
+ assert (
+ mirrorable_operators(is_monotonic=True, equality_is_safe=False)
+ == MIRRORABLE_IF_MONOTONIC
+ )
+
+
+@pytest.mark.parametrize(
+ "operator,expected",
+ [
+ (FilterOperator.GREATER_THAN, FilterOperator.GREATER_THAN_OR_EQUALS),
+ (FilterOperator.LESS_THAN, FilterOperator.LESS_THAN_OR_EQUALS),
+ (
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ ),
+ (FilterOperator.LESS_THAN_OR_EQUALS, FilterOperator.LESS_THAN_OR_EQUALS),
+ (FilterOperator.EQUALS, FilterOperator.EQUALS),
+ (FilterOperator.IN, FilterOperator.IN),
+ ],
+)
+def test_a_strict_bound_mirrors_non_strictly(
+ operator: FilterOperator, expected: FilterOperator
+) -> None:
+ """
+ Order-preserving means non-decreasing, not injective, so ``col < v``
+ implies only ``T(col) <= T(v)``. A day-key transform maps a whole day onto
+ one value and a strict mirror drops the boundary bucket. The non-strict
+ cases are already safe and pass through, which is what makes applying this
+ twice harmless.
+ """
+ assert mirror_operator(operator) == expected
+
+
+def test_relaxing_a_bound_stays_inside_the_mirrorable_set() -> None:
+ """
+ The substitution is about strictness, not about which filters mirror. The
+ Explore indicator reads `mirrorable_operators`, so leaving that set alone is
+ what keeps the glyph from promising pruning the SQL does not do -- and it is
+ also what guarantees `handle_comparison_filter` is never handed an operator
+ it has no case for.
+ """
+ assert {
+ mirror_operator(operator) for operator in MIRRORABLE_IF_MONOTONIC
+ } <= MIRRORABLE_IF_MONOTONIC
+
+
+def _column(type_: str) -> TableColumn:
+ database = Database(database_name="t", sqlalchemy_uri="sqlite://")
+ table = SqlaTable(table_name="t", database=database)
+ return TableColumn(column_name="c", type=type_, table=table)
+
+
+@pytest.mark.parametrize(
+ "type_, binary, expected",
+ [
+ ("VARCHAR", True, True),
+ ("VARCHAR", False, False),
+ # Numeric and temporal comparison is exact everywhere.
+ ("BIGINT", False, True),
+ ("TIMESTAMP", False, True),
+ ("DOUBLE", False, True),
+ ],
+)
+def test_equality_mirrors_safely_only_guards_string_columns(
+ app: Flask, type_: str, binary: bool, expected: bool
+) -> None:
+ class _Spec(BaseEngineSpec):
+ binary_string_comparison = binary
+
+ with app.app_context():
+ assert equality_mirrors_safely(_column(type_), _Spec) is expected
+
+
+@pytest.mark.parametrize(
+ "type_, expected",
+ [
+ # The padded types: `'US'` and `'US '` are equal in the column, and
+ # `lower()` of the two is not.
+ ("CHAR(2)", False),
+ ("CHAR", False),
+ ("CHARACTER(2)", False),
+ ("NCHAR(2)", False),
+ # What PostgreSQL reflection reports for a `CHAR(n)` column.
+ ("BPCHAR", False),
+ ("bpchar(2)", False),
+ ("NATIONAL CHARACTER(2)", False),
+ # The variable-width types start with the same letters and must not be
+ # caught by it.
+ ("VARCHAR(2)", True),
+ ("NVARCHAR(2)", True),
+ ("CHARACTER VARYING(2)", True),
+ ("TEXT", True),
+ ],
+)
+def test_a_padded_character_column_declines_equality_on_a_byte_exact_engine(
+ app: Flask, type_: str, expected: bool
+) -> None:
+ """
+ `binary_string_comparison` speaks for the engine's default comparison,
+ which PostgreSQL declares -- and a `CHAR(2)` there still matches a filter
+ for `'US '` against a stored `'US'`, so the mirror `lower('US ')` excludes
+ the row. Padding is a property of the type, so it is asked per column.
+ """
+
+ class _Spec(BaseEngineSpec):
+ binary_string_comparison = True
+
+ with app.app_context():
+ assert equality_mirrors_safely(_column(type_), _Spec) is expected
+
+
+def test_redshift_does_not_opt_in_to_byte_exact_comparison() -> None:
+ """
+ Redshift ignores trailing blanks for `VARCHAR` as well as `CHAR`, so the
+ `True` it inherits from `PostgresBaseEngineSpec` would be wrong.
+ """
+ from superset.db_engine_specs.redshift import RedshiftEngineSpec
+
+ assert RedshiftEngineSpec.binary_string_comparison is False
+
+
+@pytest.mark.parametrize(
+ "type_",
+ [
+ # PostgreSQL's case-insensitive text type matches no type pattern, so
+ # the spec cannot classify it -- and its whole purpose is the
+ # comparison this gate is about.
+ "citext",
+ # A column with no declared type at all.
+ "",
+ "SOME_EXTENSION_TYPE",
+ ],
+)
+def test_equality_mirrors_safely_fails_closed_on_an_unresolvable_type(
+ app: Flask, type_: str
+) -> None:
+ """
+ The gate exists to stop a silent wrong answer, so a column whose type it
+ cannot read is treated as the risky case rather than waved through.
+
+ `type_generic` answers `None` for these -- neither string nor not-string --
+ and the old reading waved them through, which for `citext` admitted exactly
+ the case-insensitive equality the gate is for. Only the exception branch
+ failed closed, though the docstring claimed otherwise.
+ """
+ with app.app_context():
+ assert equality_mirrors_safely(_column(type_), PostgresEngineSpec) is False
+
+
+def test_equality_mirrors_safely_reads_past_the_temporal_flag(app: Flask) -> None:
+ """
+ `TableColumn.type_generic` answers `TEMPORAL` for anything carrying
+ `is_dttm`, so a `VARCHAR` flagged temporal skipped the string check
+ entirely: on MySQL a filter for `'2026-01-01T00:00:00'` matches a stored
+ `'...t00:00:00'` while the mirror `hex('...T...')` excludes it.
+ """
+ with app.app_context():
+ flagged = _column("VARCHAR")
+ flagged.is_dttm = True
+ assert flagged.type_generic == GenericDataType.TEMPORAL
+ # Declines where plain text declines...
+ assert equality_mirrors_safely(flagged, MySQLEngineSpec) is False
+ # ...and is admitted where plain text is admitted.
+ assert equality_mirrors_safely(flagged, PostgresEngineSpec) is True
+
+ # A column that really is temporal is unaffected.
+ real = _column("TIMESTAMP")
+ real.is_dttm = True
+ assert equality_mirrors_safely(real, MySQLEngineSpec) is True
+
+
+def test_no_mapped_column_leaves_the_matrix_alone(app: Flask) -> None:
+ """Nothing to reason about, and the resolver bails out on it anyway."""
+ with app.app_context():
+ assert equality_mirrors_safely(None, BaseEngineSpec) is True
+
+
+@pytest.mark.parametrize(
+ "module, spec_name",
+ [
+ ("presto", "PrestoEngineSpec"),
+ ("hive", "HiveEngineSpec"),
+ ("trino", "TrinoEngineSpec"),
+ ("impala", "ImpalaEngineSpec"),
+ ("postgres", "PostgresEngineSpec"),
+ ("bigquery", "BigQueryEngineSpec"),
+ ("sqlite", "SqliteEngineSpec"),
+ ],
+)
+def test_the_byte_exact_engines_opt_in(module: str, spec_name: str) -> None:
+ """
+ The engines this feature targets compare text byte-exactly, so the gate
+ must not cost them the second canonical mapping (`lower(:value)` onto a
+ lowercased key).
+ """
+ spec = getattr(import_module(f"superset.db_engine_specs.{module}"), spec_name)
+ assert spec.binary_string_comparison is True
+
+
+@pytest.mark.parametrize("module, spec_name", [("mysql", "MySQLEngineSpec")])
+def test_a_case_insensitive_engine_does_not_opt_in(module: str, spec_name: str) -> None:
+ """
+ MySQL's default collation is `utf8mb4_0900_ai_ci`, which is exactly the
+ case the reviewer raised.
+ """
+ spec = getattr(import_module(f"superset.db_engine_specs.{module}"), spec_name)
+ assert spec.binary_string_comparison is False
+
+
+def test_the_base_spec_does_not_opt_in() -> None:
+ """A spec that has not said so does not mirror string equality."""
+ assert BaseEngineSpec.binary_string_comparison is False
+
+
+# ---------------------------------------------------------------------------
+# Time grain bucket widths
+# ---------------------------------------------------------------------------
+
+
+@pytest.mark.parametrize("grain", list(TimeGrain))
+def test_every_builtin_grain_has_a_known_bucket_width(
+ app: Flask, grain: TimeGrain
+) -> None:
+ """
+ The widening is only sound for a grain whose bucket width we know, so a
+ grain added upstream without a width here would silently stop mirroring.
+ This is the test that notices.
+ """
+ with app.app_context():
+ assert grain_bucket_width(grain.value, "sqlite") is not None
+
+
+def test_a_calendar_grain_widens_by_a_calendar_month(app: Flask) -> None:
+ """A month is not thirty days, and the month it lands in decides its width."""
+ with app.app_context():
+ width = grain_bucket_width(TimeGrain.MONTH.value, "sqlite")
+
+ assert width is not None
+ assert datetime(2026, 1, 31) + width == datetime(2026, 2, 28)
+ assert datetime(2026, 2, 1) + width == datetime(2026, 3, 1)
+
+
+def test_a_fractional_grain_has_a_width(app: Flask) -> None:
+ """
+ ``PT0.5H`` and ``P0.25Y`` are why the widths are written out rather than
+ parsed -- and the anchored week grains are intervals ``parse_duration``
+ rejects outright.
+ """
+ with app.app_context():
+ assert grain_bucket_width(TimeGrain.HALF_HOUR.value, "sqlite") == relativedelta(
+ minutes=30
+ )
+ assert grain_bucket_width(
+ TimeGrain.WEEK_ENDING_SATURDAY.value, "sqlite"
+ ) == relativedelta(days=7)
+
+
+def test_an_unknown_grain_has_no_known_width(app: Flask) -> None:
+ with app.app_context():
+ assert grain_bucket_width("P13X", "sqlite") is None
+ assert grain_bucket_width(None, "sqlite") is None
+
+
+def test_an_addon_grain_has_no_known_width(app: Flask) -> None:
+ """An operator-declared grain carries whatever duration string they typed."""
+ with app.app_context():
+ app.config["TIME_GRAIN_ADDONS"] = {"PT2S": "2 second"}
+ try:
+ assert grain_bucket_width("PT2S", "sqlite") is None
+ finally:
+ app.config["TIME_GRAIN_ADDONS"] = {}
+
+
+def test_a_builtin_grain_an_operator_redefined_has_no_known_width(
+ app: Flask,
+) -> None:
+ """
+ ``TIME_GRAIN_ADDON_EXPRESSIONS`` replaces a built-in grain's SQL for one
+ engine, so its duration no longer bounds the displacement *there* -- but it
+ still does on every other engine.
+ """
+ with app.app_context():
+ app.config["TIME_GRAIN_ADDON_EXPRESSIONS"] = {
+ "sqlite": {"P1D": "DATETIME({col}, 'start of year')"}
+ }
+ try:
+ assert grain_bucket_width(TimeGrain.DAY.value, "sqlite") is None
+ assert grain_bucket_width(TimeGrain.DAY.value, "hive") is not None
+ finally:
+ app.config["TIME_GRAIN_ADDON_EXPRESSIONS"] = {}
+
+
+def test_the_width_table_is_keyed_on_grain_durations(app: Flask) -> None:
+ """Keys are the ISO duration a filter carries, not the enum member name."""
+ assert GRAIN_BUCKET_WIDTHS[TimeGrain.DAY] == relativedelta(days=1)
+ assert set(GRAIN_BUCKET_WIDTHS) == {grain.value for grain in TimeGrain}
+
+
+# ---------------------------------------------------------------------------
+# §4.1 — resolving the effective mapping, and the defensive bail-outs
+# ---------------------------------------------------------------------------
+
+
+def test_resolve_returns_the_mapping_when_everything_lines_up(app: Flask) -> None:
+ with app.app_context():
+ mapping = resolve_partition_mapping(_mapped_table())
+
+ assert mapping is not None
+ assert mapping.partition_column == "dt_epoch"
+ assert mapping.mapped_column == "event_time"
+ assert mapping.value_transform == "unix_timestamp(:value)"
+ assert mapping.is_monotonic is True
+
+
+def test_effective_mapped_column_follows_main_dttm_col(app: Flask) -> None:
+ """No explicit override: the mapping follows the default datetime column."""
+ with app.app_context():
+ mapping = resolve_partition_mapping(_mapped_table())
+
+ assert mapping is not None
+ assert mapping.mapped_column == "event_time"
+
+
+def test_explicit_override_wins_over_main_dttm_col(app: Flask) -> None:
+ table = _mapped_table(
+ mapped_column="country",
+ transform="lower(:value)",
+ monotonic=False,
+ partition_mapped_column="country",
+ )
+ table.partition_column = "region_key"
+
+ with app.app_context():
+ mapping = resolve_partition_mapping(table)
+
+ assert mapping is not None
+ assert mapping.mapped_column == "country"
+ assert mapping.partition_column == "region_key"
+ assert mapping.is_monotonic is False
+
+
+def test_resolve_returns_none_when_the_feature_flag_is_off(app: Flask) -> None:
+ table = _mapped_table()
+ with app.app_context():
+ with patch(
+ "superset.connectors.sqla.partition_mapping.feature_flag_manager."
+ "is_feature_enabled",
+ return_value=False,
+ ):
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_without_a_partition_column(app: Flask) -> None:
+ table = _mapped_table()
+ table.partition_column = None
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_partition_column_no_longer_exists(
+ app: Flask,
+) -> None:
+ """A column sync can drop the physical partition column out from under us."""
+ table = _mapped_table()
+ table.partition_column = "dt_epoch_gone"
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_the_mapped_column_no_longer_exists(
+ app: Flask,
+) -> None:
+ table = _mapped_table(main_dttm_col="vanished")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_on_self_mapping(app: Flask) -> None:
+ """
+ ``partition_column == effective mapped column`` mirrors a column onto itself.
+ Save-time validation rejects it, but rows predating that validation exist.
+ """
+ table = _mapped_table(
+ partition_column="event_time",
+ mapped_column="event_time",
+ )
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+@pytest.mark.parametrize("transform", [None, "", " "])
+def test_resolve_returns_none_without_a_transform(
+ app: Flask, transform: str | None
+) -> None:
+ table = _mapped_table(transform=transform)
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_the_transform_lacks_the_placeholder(
+ app: Flask,
+) -> None:
+ table = _mapped_table(transform="unix_timestamp(event_time)")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_for_a_non_deterministic_transform(app: Flask) -> None:
+ """
+ The query-time gate is `is_transform_active`, the same one the Explore
+ indicator reads. Anything narrower would let a transform that reached
+ storage without passing `UpdateDatasetCommand` -- through import, or a
+ hand-written bundle -- mirror a filter with a value frozen at probe time,
+ while the editor reported the mapping as inactive and nothing on screen
+ said otherwise.
+ """
+ table = _mapped_table(transform="unix_timestamp(:value) + rand()")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_for_a_multi_expression_transform(app: Flask) -> None:
+ """A select list is not an expression; the probe cannot align its columns."""
+ table = _mapped_table(transform="lower(:value), 'x'")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_for_an_unparseable_transform(app: Flask) -> None:
+ table = _mapped_table(transform="unix_timestamp(:value")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_the_mapped_column_has_an_advanced_data_type(
+ app: Flask,
+) -> None:
+ """
+ ``translate_filter`` builds its own predicate shape from *translated* values,
+ so the ``(operator, value)`` pair the operator matrix reasons about does not
+ exist. Mirroring anyway would silently apply the wrong values (§4.1).
+ """
+ table = _mapped_table()
+ for column in table.columns:
+ if column.column_name == "event_time":
+ column.advanced_data_type = "port"
+
+ with app.app_context():
+ with patch.dict(app.config["ADVANCED_DATA_TYPES"], {"port": MagicMock()}):
+ with patch(
+ "superset.connectors.sqla.partition_mapping.feature_flag_manager."
+ "is_feature_enabled",
+ side_effect=lambda flag: (
+ flag in {"PARTITION_FILTER_MAPPING", "ENABLE_ADVANCED_DATA_TYPES"}
+ ),
+ ):
+ assert resolve_partition_mapping(table) is None
+
+
+def test_advanced_data_type_does_not_block_when_the_flag_is_off(app: Flask) -> None:
+ """An inert ``advanced_data_type`` is not a reason to skip mirroring."""
+ table = _mapped_table()
+ for column in table.columns:
+ if column.column_name == "event_time":
+ column.advanced_data_type = "port"
+
+ with app.app_context():
+ with patch(
+ "superset.connectors.sqla.partition_mapping.feature_flag_manager."
+ "is_feature_enabled",
+ side_effect=lambda flag: flag == "PARTITION_FILTER_MAPPING",
+ ):
+ assert resolve_partition_mapping(table) is not None
+
+
+# ---------------------------------------------------------------------------
+# §5 — transform inspection helpers
+# ---------------------------------------------------------------------------
+
+
+@pytest.mark.parametrize(
+ "transform,expected",
+ [
+ ("unix_timestamp(:value)", True),
+ ("lower(:value)", True),
+ ("CAST(:value AS BIGINT)", True),
+ ("unix_timestamp(event_time)", False),
+ (":values", False),
+ ("", False),
+ (None, False),
+ ],
+)
+def test_contains_value_placeholder(transform: str | None, expected: bool) -> None:
+ assert contains_value_placeholder(transform) is expected
+
+
+@pytest.mark.parametrize(
+ "transform,expected",
+ [
+ ("unix_timestamp(:value)", False),
+ ("{{ current_username() }}", True),
+ ("lower({% if x %}:value{% endif %})", True),
+ ("lower(:value) -- {# comment #}", True),
+ ],
+)
+def test_contains_jinja(transform: str, expected: bool) -> None:
+ assert contains_jinja(transform) is expected
+
+
+def test_contains_jinja_answers_as_the_block_pattern_does() -> None:
+ """
+ The scan has to agree with the lazy, ``DOTALL`` pattern it stands in for
+ on every input, including overlapping and unclosed delimiters, so that no
+ stored transform changes verdict. Every string of up to seven characters
+ over the delimiter characters, a newline and a filler is checked.
+ """
+ import itertools
+ import re
+
+ pattern = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+ for length in range(8):
+ for chars in itertools.product("{}%#\na", repeat=length):
+ text = "".join(chars)
+ assert contains_jinja(text) is (pattern.search(text) is not None), text
+
+
+@pytest.mark.parametrize("opening", ["{{", "{%", "{#"])
+def test_contains_jinja_is_linear_in_a_run_of_opening_delimiters(
+ opening: str,
+) -> None:
+ """
+ A run of opening delimiters with no closing one made the lazy pattern retry
+ from every position, which is quadratic. Stored transforms are not
+ length-bounded here, so a long run has to stay cheap.
+ """
+ import time
+
+ started = time.monotonic()
+ assert contains_jinja(opening * 200_000) is False
+ assert time.monotonic() - started < 1
+
+
+@pytest.mark.parametrize(
+ ("transform", "expected"),
+ [
+ ("lower(:value)", False),
+ ("lower(:value) /* an ordinary comment */", False),
+ ("lower(:value) -- a line comment", False),
+ (":value /*!50000 + 1 */", True),
+ (":value /*M!50000 + 1 */", True),
+ (":value /*! + 1 */", True),
+ ("", False),
+ (None, False),
+ ],
+)
+def test_contains_executable_comment(transform: str | None, expected: bool) -> None:
+ assert contains_executable_comment(transform) is expected
+
+
+@pytest.mark.parametrize(
+ "transform",
+ [
+ "unix_timestamp(:value)",
+ "lower(:value)",
+ "CAST(:value AS BIGINT)",
+ "date_format(:value, 'yyyyMMdd')",
+ ],
+)
+def test_pure_transforms_report_no_non_deterministic_functions(
+ transform: str,
+) -> None:
+ assert find_non_deterministic_functions(transform, "hive") == set()
+
+
+@pytest.mark.parametrize(
+ "transform,expected_name",
+ [
+ ("date_diff(:value, now())", "NOW"),
+ ("CAST(:value AS BIGINT) + rand()", "RAND"),
+ ("CAST(:value AS DATE) - current_date", "CURRENT_DATE"),
+ ],
+)
+def test_non_deterministic_functions_are_reported(
+ transform: str, expected_name: str
+) -> None:
+ """
+ The probe runs at a different moment and in a different session from the
+ chart query, and its result is cached, so anything time- or
+ randomness-dependent freezes a snapshot of probe time into the predicate.
+ """
+ assert expected_name in find_non_deterministic_functions(transform, "hive")
+
+
+@pytest.mark.parametrize(
+ ("engine", "transform", "expected_name"),
+ [
+ # `now()` is statement-stable on PostgreSQL; these two are not even
+ # that, and the ANSI four did not name them.
+ ("postgresql", "age(clock_timestamp(), :value)", "CLOCK_TIMESTAMP"),
+ ("postgresql", "age(statement_timestamp(), :value)", "STATEMENT_TIMESTAMP"),
+ # Every engine spells "now" its own way, and the gate matches by name.
+ ("mysql", "datediff(sysdate(), :value)", "SYSDATE"),
+ ("mysql", "datediff(curdate(), :value)", "CURDATE"),
+ ("oracle", "datediff(day, :value, LOCALTIMESTAMP)", "LOCALTIMESTAMP"),
+ ("oracle", "SYSTIMESTAMP - :value", "SYSTIMESTAMP"),
+ ("mssql", "DATEDIFF(day, :value, GETDATE())", "GETDATE"),
+ ("mssql", "DATEDIFF(day, :value, SYSUTCDATETIME())", "SYSUTCDATETIME"),
+ ("clickhouse", "now64() - :value", "NOW64"),
+ ("bigquery", "DATE_DIFF(CURRENT_DATETIME(), :value, DAY)", "CURRENT_DATETIME"),
+ ],
+)
+def test_every_engine_s_spelling_of_now_is_reported(
+ engine: str, transform: str, expected_name: str
+) -> None:
+ """
+ The list is matched by SQL function name, so a spelling it does not carry
+ passes the gate. A relative partition key such as
+ `datediff(day, :value, LOCALTIMESTAMP)` is then probed once, cached, and
+ keeps emitting yesterday's partition value after midnight -- so the chart
+ silently drops rows.
+ """
+ assert expected_name in find_non_deterministic_functions(transform, engine)
+
+
+@pytest.mark.parametrize(
+ ("engine", "transform", "expected_name"),
+ [
+ # MySQL takes these with no parentheses at all...
+ ("mysql", "datediff(UTC_DATE, :value)", "UTC_DATE"),
+ ("mysql", "datediff(utc_timestamp, :value)", "UTC_TIMESTAMP"),
+ ("mysql", "datediff(CURRENT_DATE, :value)", "CURRENT_DATE"),
+ # ...as do Oracle and PostgreSQL for their own spellings.
+ # sqlglot normalizes Oracle's bare `SYSDATE` to `CURRENT_TIMESTAMP`,
+ # so it is caught as a function under that name -- which is a pass:
+ # what matters is that the gate reports it, not what it is called.
+ ("oracle", ":value - SYSDATE", "CURRENT_TIMESTAMP"),
+ ("oracle", ":value - SYSTIMESTAMP", "SYSTIMESTAMP"),
+ ("postgresql", "age(LOCALTIMESTAMP, :value)", "LOCALTIMESTAMP"),
+ ],
+)
+def test_a_bare_wall_clock_keyword_is_reported(
+ engine: str, transform: str, expected_name: str
+) -> None:
+ """
+ Written without parentheses these parse as *column references*, so the
+ function-name walk could not see them and probe time was frozen into a
+ cached mirror.
+ """
+ assert expected_name in find_non_deterministic_functions(transform, engine)
+
+
+def test_the_bare_list_stays_to_names_that_need_no_parentheses() -> None:
+ """
+ Refusing a bare name costs an owner a column genuinely called that, so the
+ list is only the datetime keywords SQL lets you write without `()`.
+ `rand`, `uuid` and `newid` always need them, and are plausible column
+ names.
+ """
+ assert BARE_WALL_CLOCK_KEYWORDS <= {
+ name.lower() for name in NON_DETERMINISTIC_FUNCTIONS
+ }
+ assert not BARE_WALL_CLOCK_KEYWORDS & {"rand", "random", "uuid", "newid"}
+ # A column by one of those names is still an ordinary column.
+ assert find_non_deterministic_functions("lower(:value) || uuid", "postgresql") == (
+ set()
+ )
+
+
+@pytest.mark.parametrize(
+ ("engine", "transform"),
+ [
+ # The canonical transforms, which must not be swept up by the names
+ # added above.
+ ("hive", "unix_timestamp(:value)"),
+ ("postgresql", "to_char(:value, 'YYYYMMDD')"),
+ ("postgresql", "extract(epoch from :value)"),
+ ("mysql", "date_format(:value, '%Y%m%d')"),
+ ("oracle", "trunc(:value)"),
+ ("mssql", "CONVERT(date, :value)"),
+ ],
+)
+def test_the_canonical_transforms_are_still_pure(engine: str, transform: str) -> None:
+ """The list grew; this is the half that says it did not grow into the
+ transforms this feature exists for."""
+ assert find_non_deterministic_functions(transform, engine) == set()
+
+
+def test_niladic_unix_timestamp_is_rejected_but_the_unary_form_is_not() -> None:
+ """
+ On Hive/Impala ``unix_timestamp()`` means "now" while ``unix_timestamp(x)``
+ -- the canonical temporal transform -- is pure. The distinction is the whole
+ reason this check inspects arity rather than just the name.
+ """
+ assert find_non_deterministic_functions("unix_timestamp(:value)", "hive") == set()
+ assert find_non_deterministic_functions(
+ "unix_timestamp(:value) - unix_timestamp()", "hive"
+ )
+
+
+# ---------------------------------------------------------------------------
+# §4.2 — probe evaluation
+# ---------------------------------------------------------------------------
+
+
+def _user(username: str) -> Any:
+ """A stand-in for `override_user`, which only needs `.username` here."""
+ user = MagicMock()
+ user.username = username
+ user.is_anonymous = False
+ return user
+
+
+def _database_returning(values: list[Any]) -> Database:
+ """A real ``Database`` (so the dialect is real) with only ``get_df`` stubbed."""
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ return_value=pd.DataFrame(
+ [values], columns=[f"v{i}" for i in range(len(values))]
+ )
+ )
+ return database
+
+
+def _database_returning_frame(frame: pd.DataFrame) -> Database:
+ """
+ ``_database_returning`` for a probe result whose column dtypes matter.
+
+ The flat-list sibling builds its frame from one Python list, so pandas
+ infers a single dtype and the row-versus-cell distinction cannot be seen.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ return_value=frame
+ )
+ return database
+
+
+def _probe(database: Database) -> MagicMock:
+ """
+ The stubbed ``get_df``, typed for call assertions.
+
+ ``Database.get_df`` is a real method, so mypy reads its declared signature
+ rather than the mock that replaced it and rejects ``.call_args`` and
+ friends.
+ """
+ return cast(MagicMock, database.get_df)
+
+
+def test_evaluate_transform_returns_one_value_per_input(app: Flask) -> None:
+ database = _database_returning([1767225600, 1769904000])
+
+ with app.app_context():
+ result = evaluate_transform(
+ database,
+ None,
+ "default",
+ "unix_timestamp(:value)",
+ ["2026-01-01 00:00:00", "2026-02-01 00:00:00"],
+ )
+
+ assert result == [1767225600, 1769904000]
+ _probe(database).assert_called_once()
+
+
+def test_evaluate_transform_binds_values_rather_than_interpolating(
+ app: Flask,
+) -> None:
+ """
+ Filter values are attacker-controlled (a Gamma user picks them), so they must
+ be bound and escaped, never pasted into the probe SQL.
+ """
+ database = _database_returning(["o''brien"])
+
+ with app.app_context():
+ evaluate_transform(database, None, None, "lower(:value)", ["O'Brien"])
+
+ sql = _probe(database).call_args.kwargs["sql"]
+ assert "O'Brien" not in sql
+ assert "O''Brien" in sql
+
+
+@pytest.mark.parametrize(
+ ("transform", "expected"),
+ [
+ ("lower(:value)", True),
+ ("CAST(:value AS BIGINT)", True),
+ ("date_format(:value, '%Y%m%d')", True),
+ # The cast shorthand: a trailing colon stops SQLAlchemy's bind scan.
+ (":value::bigint", False),
+ ("(:value::date)::text", False),
+ ],
+)
+def test_a_postgres_cast_shorthand_is_not_bindable(
+ transform: str, expected: bool
+) -> None:
+ """
+ `VALUE_PLACEHOLDER_RE` is `:value\b`, which matches inside `:value::bigint`.
+ SQLAlchemy's own scan ends with `(?![:\\w$])`, so the following colon stops
+ it: `text(":value::bigint")` reports a parameter named `valu`, and asking it
+ to bind `value` raises.
+
+ Pinned because the two regexes disagreeing is the whole bug: every
+ write-side gate accepted the transform and the probe then died on an
+ `ArgumentError` that `_probe` swallows.
+ """
+ assert _placeholder_is_bindable(transform) is expected
+
+
+def test_a_cast_shorthand_transform_still_probes(app: Flask) -> None:
+ """
+ The transform is valid SQL, passes every gate, and used to prune nothing:
+ `build_probe_sql` raised, `_probe` swallowed it, and the only symptom was a
+ mapping that silently never mirrored -- with the preview reporting an engine
+ failure for SQL that was never sent.
+ """
+ database = _database_returning([20260115])
+
+ with app.app_context():
+ result = evaluate_transform(
+ database, None, None, ":value::bigint", ["20260115"]
+ )
+
+ assert result == [20260115]
+ assert _probe(database).call_count == 1
+ assert "::bigint" in _probe(database).call_args.kwargs["sql"]
+
+
+def test_a_cast_shorthand_value_is_still_escaped_by_the_dialect(
+ app: Flask,
+) -> None:
+ """
+ The fallback substitutes where the bind path binds, so it has to earn the
+ same guarantee its sibling above pins: the value is rendered by the
+ dialect's literal processor, not pasted in.
+
+ Binding was only ever the vehicle for reaching that processor --
+ `_compile_literal` inlines the result either way -- so this renders first
+ and substitutes second. Same string, different order.
+
+ Rendering is necessary and not sufficient: whether the engine reads the
+ rendered text back as this value is a separate question, and the one
+ `literal_round_trips` answers. SQLite's engine honours the doubling its
+ driver emits, which is why this value is probed here at all.
+ """
+ database = _database_returning(["x"])
+
+ with app.app_context():
+ evaluate_transform(database, None, None, ":value::text", ["O'Brien"])
+
+ sql = _probe(database).call_args.kwargs["sql"]
+ assert "O'Brien" not in sql
+ assert "O''Brien" in sql
+
+
+def test_evaluate_transform_dedupes_repeated_values(app: Flask) -> None:
+ """Three inputs, two distinct: the probe evaluates the transform twice."""
+ database = _database_returning(["us", "us"])
Review Comment:
Every mocked probe result here is `"us"`, so the assertion can't tell whether results are mapped back to the right inputs: a regression that fans the two distinct results back out in the wrong order would still return `["us", "us", "us"]` and pass. Could the mock return two different values for the two distinct inputs, with inputs such as `[1, 1, 2]` and results `[1, 2]`, and assert the full positional result `[1, 1, 2]` on both the cache miss and the cache hit?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,3524 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Writing the value into the probe
+--------------------------------
+The probe evaluates the transform at a *literal*, because it runs with no bound
+parameters at all -- so every value is written into SQL text by the driver's
+literal renderer and read back by the engine's lexer, and the two do not always
+agree. SQLAlchemy's default renderer doubles apostrophes and leaves backslashes
+alone; Hive honours backslash escapes and not doubling, so ``'O''Brien'`` is
+read there as two adjacent literals and ``'x\\''`` ends four characters into a
+value the filter carries whole. A disagreement is either a mirror built from a
+value nobody filtered on -- dropping rows the filter keeps -- or, where the
+value closes its own quote, an expression of the filterer's choosing running in
+the probe.
+
+Which side is right is not knowable from the driver: it is a per-session server
+setting (``standard_conforming_strings``, ``NO_BACKSLASH_ESCAPES``,
+``spark.sql.parser.escapedStringLiterals``), and SQLAlchemy's own view of it is
+only correct on a dialect that has connected. So escaping is not what makes
+this safe. `literal_round_trips` renders the literal and reads it back in the
+engine's own dialect instead, and a value that does not survive the trip is not
+mirrored -- the usual trade, pruning for correctness. `probe_sql_is_evaluable`
+re-reads the finished statement behind it.
+
+The probe's *answers* make the same trip, in the other direction. The chart
+query is compiled with ``literal_binds``, so a probed partition key is rendered
+into its SQL by the same renderer and read by the same lexer -- and
+``concat(:value, chr(92), 'b')`` turns the unremarkable input ``a`` into the key
+``a\\b``, which Hive reads back as ``a`` followed by a backspace. So
+`_predicates_from_probe` asks `literal_round_trips` about each result too, and
+declines the request rather than emitting a predicate no row can satisfy: the
+mirror is ``AND``-ed onto the query, so a mirror that matches nothing costs the
+chart its rows rather than its pruning.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: The opening and closing delimiters of each kind of Jinja block. The probe
+#: would render these in a different context at a different time from the chart
+#: query, so a transform holding one is rejected at save time.
+JINJA_BLOCK_DELIMITERS = (("{{", "}}"), ("{%", "%}"), ("{#", "#}"))
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: A PostgreSQL Unicode-escaped identifier, ``U&"..."``.
+#:
+#: The second construct that breaks the premise above, and in the same way:
+#: ``U&"\\0071uery_to_xml"(...)`` parses as an anonymous function whose name is
+#: the *literal* ``\\0071uery_to_xml``, so the function denylist is matching a
+#: name the engine never sees -- PostgreSQL decodes the escape and runs
+#: ``query_to_xml``, handing a dataset owner rows from outside their RLS scope
+#: through the preview's ``emitted_predicate``.
+#:
+#: Normalizing the escapes and re-checking would be the other repair, and is
+#: worse: it means reimplementing one engine's identifier decoding well enough
+#: to be a security boundary. Refusing the construct is exact, and costs
+#: nothing real -- a transform is a scalar function of ``:value``, and there is
+#: no reason to name a function or column through an escape sequence.
+#:
+#: Refused on every engine, like the executable comment, so a transform stored
+#: on SQLite cannot detonate when the dataset is re-pointed at PostgreSQL. The
+#: ``&`` may be separated from the ``U`` by nothing at all, but whitespace or a
+#: comment between the prefix and the string is not accepted by PostgreSQL
+#: either, so the strict form is the whole surface.
+#:
+#: Matched in raw text, so the prefix is refused inside a string literal too.
+#: That is the same trade the executable comment makes and has the same
+#: justification: a gate whose contract is to fire *before* the parse cannot
+#: ask the parse whether the text was quoted. ``concat(:value, 'u&"x"')`` is
+#: refused, which costs an owner nothing anyone writes.
+UNICODE_ESCAPED_IDENTIFIER_RE = re.compile(r'\bU&"', re.IGNORECASE)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate: a transform such as
+#: ``datediff(day, :value, LOCALTIMESTAMP)`` for a relative partition key is
+#: evaluated once and then keeps emitting yesterday's answer, so the chart
+#: silently drops rows after midnight.
+#:
+#: Matched by SQL function name, so every engine's spelling of "now" has to be
+#: named -- the ANSI four were not enough. Listed rather than delegated to the
+#: engine specs because the risk is the same everywhere and a spec that had not
+#: got round to declaring its own would fail open; a name no engine has is
+#: inert, so over-listing costs nothing.
+NON_DETERMINISTIC_FUNCTIONS = {
+ # ANSI, and the engines that spell it this way.
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "LOCALTIME",
+ "LOCALTIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+ # PostgreSQL. `now()` is statement-stable; these two are not even that.
+ "CLOCK_TIMESTAMP",
+ "STATEMENT_TIMESTAMP",
+ "TIMEOFDAY",
+ # MySQL and MariaDB.
+ "CURDATE",
+ "CURTIME",
+ "SYSDATE",
+ "UTC_DATE",
+ "UTC_TIME",
+ "UTC_TIMESTAMP",
+ "UUID_SHORT",
+ # Oracle.
+ "SYSTIMESTAMP",
+ "SYS_GUID",
+ # SQL Server.
+ "GETDATE",
+ "GETUTCDATE",
+ "SYSDATETIME",
+ "SYSUTCDATETIME",
+ "SYSDATETIMEOFFSET",
+ "NEWID",
+ # BigQuery.
+ "CURRENT_DATETIME",
+ "GENERATE_UUID",
+ # Snowflake.
+ "RANDSTR",
+ "UUID_STRING",
+ # ClickHouse.
+ "NOW64",
+ "RANDCANONICAL",
+ "GENERATEUUIDV4",
+ # H2 and Derby, which the test fixtures use.
+ "RANDOM_UUID",
+}
+
+#: The wall-clock names an engine evaluates with no parentheses at all.
+#:
+#: These parse as *column references*, not functions, so the name-based walk
+#: below cannot see them: `datediff(UTC_DATE, :value)` on MySQL and
+#: `:value - SYSDATE` on Oracle both cleared the gate and froze probe time into
+#: a cached mirror.
+#:
+#: A subset of `NON_DETERMINISTIC_FUNCTIONS` rather than the whole of it,
+#: because refusing a bare name costs an owner a column genuinely called that.
+#: Only the names SQL lets you write without ``()`` are listed -- the datetime
+#: keywords -- so `rand`, `uuid` and `newid`, which always need parentheses and
+#: are plausible column names, stay out.
+BARE_WALL_CLOCK_KEYWORDS = frozenset(
+ {
+ "current_date",
+ "current_time",
+ "current_timestamp",
+ "localtime",
+ "localtimestamp",
+ "utc_date",
+ "utc_time",
+ "utc_timestamp",
+ "sysdate",
+ "systimestamp",
+ }
+)
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+class Unmirrorable:
+ """
+ A filter no mirror can stand in for, and why.
+
+ Returned by `ExploreMixin.mirror_probe_request` for a value the engine
+ compares more coarsely than the filter carries, one it cannot render as a
+ literal, one whose rendered literal the engine would not read back as the
+ same value, one in a time frame the transform would discard, or an ``IN``
+ list with a member of any of those kinds. An object rather than `None`,
+ because `None` is a filter value in its own right.
+
+ The reason rides along because the preview has to explain the decline to
+ the owner, and the two declines want different advice: "the engine compares
+ less of this value than you typed, so map a column it compares in full" is
+ sound guidance for a `DATE` column and actively misleading for an
+ offset-bearing bound on a `TIMESTAMP` one, which already is such a column.
+ Carried rather than re-derived so the preview's explanation cannot come
+ apart from the chart path's decision.
+
+ Lives here rather than beside that method so the preview can read it too:
+ `superset.models.helpers` imports this module, so these can only cross the
+ boundary in this direction. Both callers recognise the same instances -- a
+ preview that answered "valid" for a request the chart path declines is the
+ drift this is here to prevent.
+ """
+
+ __slots__ = ("reason",)
+
+ def __init__(self, reason: str) -> None:
+ self.reason = reason
+
+ def __repr__(self) -> str:
+ return f"<Unmirrorable {self.reason}>"
+
+
+#: The ordinary decline: whatever the mirror cannot be built from, with the
+#: engine's own comparison resolution as the reason an owner can act on.
+UNMIRRORABLE = Unmirrorable("resolution")
+
+#: A value carrying a UTC offset, declined whatever the column's resolution.
+#: A transform such as ``CAST(:value AS TIMESTAMP)`` drops the offset, so even
+#: an engine that compares the whole instant would be probed in the wrong
+#: frame -- which is not something mapping a different column fixes.
+UNMIRRORABLE_OFFSET = Unmirrorable("offset")
+
+#: A value the driver and the engine would not spell the same way, declined
+#: whatever the column's resolution and whatever the operator. Nothing about
+#: the column or the transform fixes it -- see `literal_round_trips` -- so the
+#: advice the resolution reason carries would send an owner after the wrong
+#: thing entirely.
+UNMIRRORABLE_ESCAPING = Unmirrorable("escaping")
+
+
+def is_unmirrorable(value: Any) -> bool:
+ """Whether `mirror_probe_request` declined this request."""
+ return isinstance(value, Unmirrorable)
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def _native_generic_type(
+ column: "TableColumn",
+) -> utils.GenericDataType | None:
+ """
+ What the engine spec makes of ``column``'s declared type.
+
+ `TableColumn.type_generic` answers ``TEMPORAL`` for every column carrying
+ ``is_dttm``, which is the right answer for a chart's time axis and the
+ wrong one for a comparison: an epoch ``BIGINT`` is a number to the engine
+ however it is labelled here. Falls back to the flag where the spec has no
+ answer, so a type Superset cannot resolve is no worse off than before.
+ """
+ try:
+ column_spec = column.db_engine_spec.get_column_spec(
+ column.type, db_extra=column.db_extra
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ column_spec = None
+ if column_spec is not None and column_spec.generic_type is not None:
+ return column_spec.generic_type
+ try:
+ return column.type_generic
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+#: Declared types whose comparison ignores trailing blanks.
+#:
+#: The fixed-width character types, which the SQL standard has compare as
+#: though both sides were padded to the same length -- so ``'US'`` and
+#: ``'US '`` are equal in a ``CHARACTER(3)``, while ``lower()`` of the two is
+#: not. Spelled out rather than matched by prefix because the variable-width
+#: names start with the same letters: ``VARCHAR`` and ``CHARACTER VARYING``
+#: compare the blanks and must not land here.
+PADDED_CHARACTER_TYPES = frozenset(
+ {
+ "CHAR",
+ "NCHAR",
+ # PostgreSQL's own name for ``CHARACTER``, which is what reflection
+ # reports for a ``CHAR(n)`` column there.
+ "BPCHAR",
+ "CHARACTER",
+ "NATIONAL CHAR",
+ "NATIONAL CHARACTER",
+ }
+)
+
+
+def _is_padded_character_type(column: TableColumn) -> bool:
+ """
+ Whether ``column``'s declared type compares without its trailing blanks.
+
+ Read off the declared type rather than the engine spec's resolved one: the
+ specs map ``CHAR`` and ``VARCHAR`` onto the same `sqlalchemy.String`, so
+ the distinction this needs is gone by then. The length suffix is dropped
+ and the name matched against `PADDED_CHARACTER_TYPES`, so an unfamiliar
+ spelling answers ``False`` and the engine-level flag decides as before --
+ this gate adds a decline rather than lifting one. A column with no
+ declared type has nothing to read, and answers the same way.
+ """
+ if not isinstance(column.type, str):
+ return False
+ native = re.sub(r"\s+", " ", column.type.strip().upper())
+ return native.split("(")[0].strip() in PADDED_CHARACTER_TYPES
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ Padding is asked about per column, because it is a property of the *type*
+ rather than of the engine. ``binary_string_comparison`` speaks for an
+ engine's default text comparison, and on PostgreSQL -- which declares it
+ -- a ``CHAR(2)`` still matches a filter for ``'US '`` against a stored
+ ``'US'``, because the standard says a padded character type compares
+ without its trailing blanks. The mirror ``region_key = lower('US ')`` then
+ excludes the row. So a fixed-width character type declines whatever the
+ engine says, and an engine that ignores trailing blanks on its *variable*
+ types says so by not declaring the flag at all (see `RedshiftEngineSpec`).
+
+ The type asked for is the engine spec's reading of the column's declared
+ type, not `TableColumn.type_generic`, which answers ``TEMPORAL`` for
+ anything carrying ``is_dttm``. A ``VARCHAR`` flagged temporal is still text
+ to the engine: on MySQL a filter for ``'2026-01-01T00:00:00'`` matches a
+ stored ``'...t00:00:00'``, while the mirror ``p = hex('...T...')`` excludes
+ it -- and asking the semantic flag skipped the check entirely.
+
+ A type the spec cannot classify declines, which is what the paragraph above
+ promises and what only the exception branch used to do. PostgreSQL's
+ ``citext`` matches no type pattern, so it answered ``None`` -- neither
+ string nor not-string -- and was waved through, which is precisely wrong
+ for a type whose whole purpose is case-insensitive comparison. Declining
+ costs the pruning; admitting it costs rows.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ # Ahead of the generic-type question, which a padded type can lose: the
+ # specs map ``CHARACTER`` onto no generic type at all on some engines, and
+ # a fixed-width character type is a string whether or not Superset can say
+ # so from the name.
+ if _is_padded_character_type(column):
+ return False
+ generic_type = _native_generic_type(column)
+ if generic_type is None:
+ return False
+ if generic_type != utils.GenericDataType.STRING:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_unicode_escaped_identifier(transform: str | None) -> bool:
+ """Whether the transform names something through a ``U&"..."`` escape.
+
+ See `UNICODE_ESCAPED_IDENTIFIER_RE`. Answered on raw text for the same
+ reason as the comment above: the parse reports a name the engine does not
+ use, which is exactly what makes the denylist blind to it.
+ """
+ return (
+ bool(transform)
+ and UNICODE_ESCAPED_IDENTIFIER_RE.search(transform or "") is not None
+ )
+
+
+#: Sequence pseudo-columns, which advance a sequence when they are *read*.
+#:
+#: ``orders_seq.NEXTVAL`` parses as a qualified column reference, not a
+#: function call, so neither `SQLStatement.is_mutating` -- which walks function
+#: names -- nor the function denylist can see it. The probe would then run
+#: ``SELECT orders_seq.NEXTVAL + 1 FROM DUAL`` and advance the sequence, again
+#: on every cache expiry, for a dataset editor holding neither SQL Lab nor a
+#: DML grant. Reading one is a write however the parser classifies it.
+#:
+#: The function spelling (``nextval('s')`` on PostgreSQL) is a different shape
+#: and is caught as a function; this is only about the suffix form.
+SEQUENCE_PSEUDO_COLUMNS = frozenset({"nextval", "currval"})
+
+#: The same thing written as a call.
+#:
+#: Only the suffix form parses as a column; `nextval('s')` on PostgreSQL and
+#: DuckDB, `NEXTVAL(s)`/`SETVAL(s, 1)` on MySQL and MariaDB, and SQL Server's
+#: `NEXT VALUE FOR s` all parse as functions. `SQLStatement.is_mutating` walks
+#: function names on PostgreSQL alone -- deliberately, since the same names are
+#: read-only elsewhere -- so every other engine let these through.
+#:
+#: Matched on the name whatever the engine, because advancing a sequence is a
+#: write wherever it happens and a transform has no reason to call one.
+SEQUENCE_FUNCTIONS = frozenset(
+ {"nextval", "setval", "next_value_for", "nextvalfor", "prevval", "lastval"}
+)
+
+
+def references_sequence(statement: SQLStatement) -> bool:
+ """Whether the statement reads or advances a sequence.
+
+ Both spellings: the pseudo-column suffix, which parses as a column (see
+ `SEQUENCE_PSEUDO_COLUMNS`), and the call, which parses as a function (see
+ `SEQUENCE_FUNCTIONS`).
+
+ Answered on the parse rather than on raw text, because position is what
+ makes it the construct: a column or alias merely *called* ``nextval`` is
+ an ordinary column, and a string literal holding the word is text.
+ """
+ return bool(
+ statement.get_column_names() & SEQUENCE_PSEUDO_COLUMNS
+ or statement.get_disallowed_functions(set(SEQUENCE_FUNCTIONS))
+ )
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """
+ Whether the transform contains a balanced Jinja block.
+
+ A block is an opening delimiter followed, anywhere later, by its closing
+ one -- the same thing ``{{.*?}}`` and its two siblings match under
+ ``re.DOTALL``. Scanned with `str.find` rather than that pattern, because a
+ lazy match retried from every opening delimiter is quadratic in a run of
+ them, and this runs on stored transforms with no length bound of its own:
+ `is_transform_active` reads whatever the column holds. The earliest opening
+ delimiter is the only one worth trying, since any closing delimiter after a
+ later one is also after it.
+ """
+ if not transform:
+ return False
+ for opening, closing in JINJA_BLOCK_DELIMITERS:
+ start = transform.find(opening)
+ if start != -1 and transform.find(closing, start + len(opening)) != -1:
+ return True
+ return False
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+
+ Three spellings have to be looked for, because one name reaches the parse
+ three ways: as a function call, as a zero-argument call a dialect resolves
+ itself, and -- for the datetime keywords -- as a bare word that parses as a
+ column reference.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ # The parenthesis-free spellings, which parse as columns rather than
+ # functions and so are invisible to the walk above. See
+ # `BARE_WALL_CLOCK_KEYWORDS`.
+ found |= {
+ name.upper() for name in BARE_WALL_CLOCK_KEYWORDS & statement.get_column_names()
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error( # noqa: C901
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ And it must be a *read*. Shape is a separate question from effect: a bare
+ scalar expression can still write, so `SQLStatement.is_mutating` is asked
+ too -- the same question SQL Lab and the chart executor ask before letting
+ SQL run. See the gate itself for what that reaches and what it does not.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ # Also ahead of the parse, and for a stronger reason than cost: every gate
+ # below reasons about the parse tree, and this is the one construct that
+ # makes the parse tree describe a different statement from the one the
+ # engine runs. Checked here as well as in `validate_transform` because this
+ # is the door a row written by an earlier release still comes through.
+ if contains_executable_comment(transform):
+ return str(
+ _(
+ "A partition value transform cannot contain a MySQL "
+ "executable comment, which the database executes and every "
+ "validator reads as a comment."
+ )
+ )
+
+ if contains_unicode_escaped_identifier(transform):
+ return str(
+ _(
+ "A partition value transform cannot name anything through a "
+ 'U&"..." escape sequence, which the database decodes and '
+ "every validator reads literally."
+ )
+ )
+
+ # Same door, same reason: the name the denylist below would match is not
+ # the name the engine resolves. See `UNICODE_ESCAPED_IDENTIFIER_RE`.
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The read-only gate, which nothing above implies. The shape gates ask what
+ # the transform *selects*; this asks what evaluating it *does*, and a bare
+ # scalar expression can still write. `nextval(:value)` on PostgreSQL
+ # advances a sequence: one function call, no clause, no sub-query, and not
+ # in the default `DISALLOWED_SQL_FUNCTIONS` either -- so every gate above
+ # passes it and the probe then runs it. `setval` is the same shape, and
+ # `exp.Execute` and the opaque-`exp.Command` forms arrive the same way.
+ #
+ # The large-object writers (`lo_export`, `lowrite`, `lo_from_bytea`, ...)
+ # are caught here too, and the shipped denylist happens to name them as
+ # well -- but that is config an operator can replace, while this is not.
+ #
+ # `is_mutating` is the same question SQL Lab, `get_virtual_table_metadata`
+ # and the chart executor ask before letting SQL run, so a transform is held
+ # to the bar the rest of Superset already sets rather than to one invented
+ # here. Unconditional rather than gated on `Database.allow_dml`: a transform
+ # is a scalar function of `:value` by definition, so there is no legitimate
+ # mutating one, and the probe runs on a cache schedule nobody chose -- a
+ # write would repeat every time the entry expired.
+ #
+ # It bears saying what this does not reach. A user-defined function whose
+ # body writes is a plain call no parser can tell from `lower(:value)`, and
+ # `is_mutating`'s function-name walk is PostgreSQL-only by design, since the
+ # same names are read-only elsewhere. Neither residual is specific to this
+ # feature -- a dataset editor can already have the engine evaluate an
+ # arbitrary expression through a calculated column or a virtual dataset's
+ # SQL -- and closing them means authorizing the preview against the
+ # database, not parsing harder.
+ if statement.is_mutating():
+ return str(
+ _(
+ "A partition value transform cannot change data. It is "
+ "evaluated against the database to check that it mirrors, so "
+ "it has to be a read."
+ )
+ )
+
+ # Not reached by the walk above, which is why it is its own gate: a
+ # sequence pseudo-column is a *column* to the parser and a write to the
+ # engine. See `SEQUENCE_PSEUDO_COLUMNS`.
+ if references_sequence(statement):
+ return str(
+ _(
+ "A partition value transform cannot read a sequence. "
+ "NEXTVAL advances the sequence every time it is evaluated, "
+ "and the transform is evaluated on a cache schedule."
+ )
+ )
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
Review Comment:
The function denylist is looked up by the engine spec's own `engine` name, and `DISALLOWED_SQL_FUNCTIONS` only has keys for `postgresql`, `mysql`, `mssql`, `oracle`, `clickhouse` and `sqlite`, so a database whose spec has another name gets an empty set here. `MariaDBEngineSpec` subclasses the MySQL spec but has `engine = "mariadb"`, so for a `mariadb://` database a dataset editor without SQL Lab access can store `LOAD_FILE(:value)` (or `SLEEP(:value)`): it parses as a bare scalar, clears every other gate, runs on the warehouse connection, and the result comes back in the preview's emitted predicate. Should the denylist resolve to the parent spec's family (or merge it) so MySQL/PostgreSQL forks inherit the same entries?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,3524 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Writing the value into the probe
+--------------------------------
+The probe evaluates the transform at a *literal*, because it runs with no bound
+parameters at all -- so every value is written into SQL text by the driver's
+literal renderer and read back by the engine's lexer, and the two do not always
+agree. SQLAlchemy's default renderer doubles apostrophes and leaves backslashes
+alone; Hive honours backslash escapes and not doubling, so ``'O''Brien'`` is
+read there as two adjacent literals and ``'x\\''`` ends four characters into a
+value the filter carries whole. A disagreement is either a mirror built from a
+value nobody filtered on -- dropping rows the filter keeps -- or, where the
+value closes its own quote, an expression of the filterer's choosing running in
+the probe.
+
+Which side is right is not knowable from the driver: it is a per-session server
+setting (``standard_conforming_strings``, ``NO_BACKSLASH_ESCAPES``,
+``spark.sql.parser.escapedStringLiterals``), and SQLAlchemy's own view of it is
+only correct on a dialect that has connected. So escaping is not what makes
+this safe. `literal_round_trips` renders the literal and reads it back in the
+engine's own dialect instead, and a value that does not survive the trip is not
+mirrored -- the usual trade, pruning for correctness. `probe_sql_is_evaluable`
+re-reads the finished statement behind it.
+
+The probe's *answers* make the same trip, in the other direction. The chart
+query is compiled with ``literal_binds``, so a probed partition key is rendered
+into its SQL by the same renderer and read by the same lexer -- and
+``concat(:value, chr(92), 'b')`` turns the unremarkable input ``a`` into the key
+``a\\b``, which Hive reads back as ``a`` followed by a backspace. So
+`_predicates_from_probe` asks `literal_round_trips` about each result too, and
+declines the request rather than emitting a predicate no row can satisfy: the
+mirror is ``AND``-ed onto the query, so a mirror that matches nothing costs the
+chart its rows rather than its pruning.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: The opening and closing delimiters of each kind of Jinja block. The probe
+#: would render these in a different context at a different time from the chart
+#: query, so a transform holding one is rejected at save time.
+JINJA_BLOCK_DELIMITERS = (("{{", "}}"), ("{%", "%}"), ("{#", "#}"))
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: A PostgreSQL Unicode-escaped identifier, ``U&"..."``.
+#:
+#: The second construct that breaks the premise above, and in the same way:
+#: ``U&"\\0071uery_to_xml"(...)`` parses as an anonymous function whose name is
+#: the *literal* ``\\0071uery_to_xml``, so the function denylist is matching a
+#: name the engine never sees -- PostgreSQL decodes the escape and runs
+#: ``query_to_xml``, handing a dataset owner rows from outside their RLS scope
+#: through the preview's ``emitted_predicate``.
+#:
+#: Normalizing the escapes and re-checking would be the other repair, and is
+#: worse: it means reimplementing one engine's identifier decoding well enough
+#: to be a security boundary. Refusing the construct is exact, and costs
+#: nothing real -- a transform is a scalar function of ``:value``, and there is
+#: no reason to name a function or column through an escape sequence.
+#:
+#: Refused on every engine, like the executable comment, so a transform stored
+#: on SQLite cannot detonate when the dataset is re-pointed at PostgreSQL. The
+#: ``&`` may be separated from the ``U`` by nothing at all, but whitespace or a
+#: comment between the prefix and the string is not accepted by PostgreSQL
+#: either, so the strict form is the whole surface.
+#:
+#: Matched in raw text, so the prefix is refused inside a string literal too.
+#: That is the same trade the executable comment makes and has the same
+#: justification: a gate whose contract is to fire *before* the parse cannot
+#: ask the parse whether the text was quoted. ``concat(:value, 'u&"x"')`` is
+#: refused, which costs an owner nothing anyone writes.
+UNICODE_ESCAPED_IDENTIFIER_RE = re.compile(r'\bU&"', re.IGNORECASE)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate: a transform such as
+#: ``datediff(day, :value, LOCALTIMESTAMP)`` for a relative partition key is
+#: evaluated once and then keeps emitting yesterday's answer, so the chart
+#: silently drops rows after midnight.
+#:
+#: Matched by SQL function name, so every engine's spelling of "now" has to be
+#: named -- the ANSI four were not enough. Listed rather than delegated to the
+#: engine specs because the risk is the same everywhere and a spec that had not
+#: got round to declaring its own would fail open; a name no engine has is
+#: inert, so over-listing costs nothing.
+NON_DETERMINISTIC_FUNCTIONS = {
+ # ANSI, and the engines that spell it this way.
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "LOCALTIME",
+ "LOCALTIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+ # PostgreSQL. `now()` is statement-stable; these two are not even that.
+ "CLOCK_TIMESTAMP",
+ "STATEMENT_TIMESTAMP",
+ "TIMEOFDAY",
+ # MySQL and MariaDB.
+ "CURDATE",
+ "CURTIME",
+ "SYSDATE",
+ "UTC_DATE",
+ "UTC_TIME",
+ "UTC_TIMESTAMP",
+ "UUID_SHORT",
+ # Oracle.
+ "SYSTIMESTAMP",
+ "SYS_GUID",
+ # SQL Server.
+ "GETDATE",
+ "GETUTCDATE",
+ "SYSDATETIME",
+ "SYSUTCDATETIME",
+ "SYSDATETIMEOFFSET",
+ "NEWID",
+ # BigQuery.
+ "CURRENT_DATETIME",
+ "GENERATE_UUID",
+ # Snowflake.
+ "RANDSTR",
+ "UUID_STRING",
+ # ClickHouse.
+ "NOW64",
+ "RANDCANONICAL",
+ "GENERATEUUIDV4",
+ # H2 and Derby, which the test fixtures use.
+ "RANDOM_UUID",
+}
+
+#: The wall-clock names an engine evaluates with no parentheses at all.
+#:
+#: These parse as *column references*, not functions, so the name-based walk
+#: below cannot see them: `datediff(UTC_DATE, :value)` on MySQL and
+#: `:value - SYSDATE` on Oracle both cleared the gate and froze probe time into
+#: a cached mirror.
+#:
+#: A subset of `NON_DETERMINISTIC_FUNCTIONS` rather than the whole of it,
+#: because refusing a bare name costs an owner a column genuinely called that.
+#: Only the names SQL lets you write without ``()`` are listed -- the datetime
+#: keywords -- so `rand`, `uuid` and `newid`, which always need parentheses and
+#: are plausible column names, stay out.
+BARE_WALL_CLOCK_KEYWORDS = frozenset(
+ {
+ "current_date",
+ "current_time",
+ "current_timestamp",
+ "localtime",
+ "localtimestamp",
+ "utc_date",
+ "utc_time",
+ "utc_timestamp",
+ "sysdate",
+ "systimestamp",
+ }
+)
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+class Unmirrorable:
+ """
+ A filter no mirror can stand in for, and why.
+
+ Returned by `ExploreMixin.mirror_probe_request` for a value the engine
+ compares more coarsely than the filter carries, one it cannot render as a
+ literal, one whose rendered literal the engine would not read back as the
+ same value, one in a time frame the transform would discard, or an ``IN``
+ list with a member of any of those kinds. An object rather than `None`,
+ because `None` is a filter value in its own right.
+
+ The reason rides along because the preview has to explain the decline to
+ the owner, and the two declines want different advice: "the engine compares
+ less of this value than you typed, so map a column it compares in full" is
+ sound guidance for a `DATE` column and actively misleading for an
+ offset-bearing bound on a `TIMESTAMP` one, which already is such a column.
+ Carried rather than re-derived so the preview's explanation cannot come
+ apart from the chart path's decision.
+
+ Lives here rather than beside that method so the preview can read it too:
+ `superset.models.helpers` imports this module, so these can only cross the
+ boundary in this direction. Both callers recognise the same instances -- a
+ preview that answered "valid" for a request the chart path declines is the
+ drift this is here to prevent.
+ """
+
+ __slots__ = ("reason",)
+
+ def __init__(self, reason: str) -> None:
+ self.reason = reason
+
+ def __repr__(self) -> str:
+ return f"<Unmirrorable {self.reason}>"
+
+
+#: The ordinary decline: whatever the mirror cannot be built from, with the
+#: engine's own comparison resolution as the reason an owner can act on.
+UNMIRRORABLE = Unmirrorable("resolution")
+
+#: A value carrying a UTC offset, declined whatever the column's resolution.
+#: A transform such as ``CAST(:value AS TIMESTAMP)`` drops the offset, so even
+#: an engine that compares the whole instant would be probed in the wrong
+#: frame -- which is not something mapping a different column fixes.
+UNMIRRORABLE_OFFSET = Unmirrorable("offset")
+
+#: A value the driver and the engine would not spell the same way, declined
+#: whatever the column's resolution and whatever the operator. Nothing about
+#: the column or the transform fixes it -- see `literal_round_trips` -- so the
+#: advice the resolution reason carries would send an owner after the wrong
+#: thing entirely.
+UNMIRRORABLE_ESCAPING = Unmirrorable("escaping")
+
+
+def is_unmirrorable(value: Any) -> bool:
+ """Whether `mirror_probe_request` declined this request."""
+ return isinstance(value, Unmirrorable)
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def _native_generic_type(
+ column: "TableColumn",
+) -> utils.GenericDataType | None:
+ """
+ What the engine spec makes of ``column``'s declared type.
+
+ `TableColumn.type_generic` answers ``TEMPORAL`` for every column carrying
+ ``is_dttm``, which is the right answer for a chart's time axis and the
+ wrong one for a comparison: an epoch ``BIGINT`` is a number to the engine
+ however it is labelled here. Falls back to the flag where the spec has no
+ answer, so a type Superset cannot resolve is no worse off than before.
+ """
+ try:
+ column_spec = column.db_engine_spec.get_column_spec(
+ column.type, db_extra=column.db_extra
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ column_spec = None
+ if column_spec is not None and column_spec.generic_type is not None:
+ return column_spec.generic_type
+ try:
+ return column.type_generic
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+#: Declared types whose comparison ignores trailing blanks.
+#:
+#: The fixed-width character types, which the SQL standard has compare as
+#: though both sides were padded to the same length -- so ``'US'`` and
+#: ``'US '`` are equal in a ``CHARACTER(3)``, while ``lower()`` of the two is
+#: not. Spelled out rather than matched by prefix because the variable-width
+#: names start with the same letters: ``VARCHAR`` and ``CHARACTER VARYING``
+#: compare the blanks and must not land here.
+PADDED_CHARACTER_TYPES = frozenset(
+ {
+ "CHAR",
+ "NCHAR",
+ # PostgreSQL's own name for ``CHARACTER``, which is what reflection
+ # reports for a ``CHAR(n)`` column there.
+ "BPCHAR",
+ "CHARACTER",
+ "NATIONAL CHAR",
+ "NATIONAL CHARACTER",
+ }
+)
+
+
+def _is_padded_character_type(column: TableColumn) -> bool:
+ """
+ Whether ``column``'s declared type compares without its trailing blanks.
+
+ Read off the declared type rather than the engine spec's resolved one: the
+ specs map ``CHAR`` and ``VARCHAR`` onto the same `sqlalchemy.String`, so
+ the distinction this needs is gone by then. The length suffix is dropped
+ and the name matched against `PADDED_CHARACTER_TYPES`, so an unfamiliar
+ spelling answers ``False`` and the engine-level flag decides as before --
+ this gate adds a decline rather than lifting one. A column with no
+ declared type has nothing to read, and answers the same way.
+ """
+ if not isinstance(column.type, str):
+ return False
+ native = re.sub(r"\s+", " ", column.type.strip().upper())
+ return native.split("(")[0].strip() in PADDED_CHARACTER_TYPES
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ Padding is asked about per column, because it is a property of the *type*
+ rather than of the engine. ``binary_string_comparison`` speaks for an
+ engine's default text comparison, and on PostgreSQL -- which declares it
+ -- a ``CHAR(2)`` still matches a filter for ``'US '`` against a stored
+ ``'US'``, because the standard says a padded character type compares
+ without its trailing blanks. The mirror ``region_key = lower('US ')`` then
+ excludes the row. So a fixed-width character type declines whatever the
+ engine says, and an engine that ignores trailing blanks on its *variable*
+ types says so by not declaring the flag at all (see `RedshiftEngineSpec`).
+
+ The type asked for is the engine spec's reading of the column's declared
+ type, not `TableColumn.type_generic`, which answers ``TEMPORAL`` for
+ anything carrying ``is_dttm``. A ``VARCHAR`` flagged temporal is still text
+ to the engine: on MySQL a filter for ``'2026-01-01T00:00:00'`` matches a
+ stored ``'...t00:00:00'``, while the mirror ``p = hex('...T...')`` excludes
+ it -- and asking the semantic flag skipped the check entirely.
+
+ A type the spec cannot classify declines, which is what the paragraph above
+ promises and what only the exception branch used to do. PostgreSQL's
+ ``citext`` matches no type pattern, so it answered ``None`` -- neither
+ string nor not-string -- and was waved through, which is precisely wrong
+ for a type whose whole purpose is case-insensitive comparison. Declining
+ costs the pruning; admitting it costs rows.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ # Ahead of the generic-type question, which a padded type can lose: the
+ # specs map ``CHARACTER`` onto no generic type at all on some engines, and
+ # a fixed-width character type is a string whether or not Superset can say
+ # so from the name.
+ if _is_padded_character_type(column):
+ return False
+ generic_type = _native_generic_type(column)
+ if generic_type is None:
+ return False
+ if generic_type != utils.GenericDataType.STRING:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_unicode_escaped_identifier(transform: str | None) -> bool:
+ """Whether the transform names something through a ``U&"..."`` escape.
+
+ See `UNICODE_ESCAPED_IDENTIFIER_RE`. Answered on raw text for the same
+ reason as the comment above: the parse reports a name the engine does not
+ use, which is exactly what makes the denylist blind to it.
+ """
+ return (
+ bool(transform)
+ and UNICODE_ESCAPED_IDENTIFIER_RE.search(transform or "") is not None
+ )
+
+
+#: Sequence pseudo-columns, which advance a sequence when they are *read*.
+#:
+#: ``orders_seq.NEXTVAL`` parses as a qualified column reference, not a
+#: function call, so neither `SQLStatement.is_mutating` -- which walks function
+#: names -- nor the function denylist can see it. The probe would then run
+#: ``SELECT orders_seq.NEXTVAL + 1 FROM DUAL`` and advance the sequence, again
+#: on every cache expiry, for a dataset editor holding neither SQL Lab nor a
+#: DML grant. Reading one is a write however the parser classifies it.
+#:
+#: The function spelling (``nextval('s')`` on PostgreSQL) is a different shape
+#: and is caught as a function; this is only about the suffix form.
+SEQUENCE_PSEUDO_COLUMNS = frozenset({"nextval", "currval"})
+
+#: The same thing written as a call.
+#:
+#: Only the suffix form parses as a column; `nextval('s')` on PostgreSQL and
+#: DuckDB, `NEXTVAL(s)`/`SETVAL(s, 1)` on MySQL and MariaDB, and SQL Server's
+#: `NEXT VALUE FOR s` all parse as functions. `SQLStatement.is_mutating` walks
+#: function names on PostgreSQL alone -- deliberately, since the same names are
+#: read-only elsewhere -- so every other engine let these through.
+#:
+#: Matched on the name whatever the engine, because advancing a sequence is a
+#: write wherever it happens and a transform has no reason to call one.
+SEQUENCE_FUNCTIONS = frozenset(
+ {"nextval", "setval", "next_value_for", "nextvalfor", "prevval", "lastval"}
+)
+
+
+def references_sequence(statement: SQLStatement) -> bool:
+ """Whether the statement reads or advances a sequence.
+
+ Both spellings: the pseudo-column suffix, which parses as a column (see
+ `SEQUENCE_PSEUDO_COLUMNS`), and the call, which parses as a function (see
+ `SEQUENCE_FUNCTIONS`).
+
+ Answered on the parse rather than on raw text, because position is what
+ makes it the construct: a column or alias merely *called* ``nextval`` is
+ an ordinary column, and a string literal holding the word is text.
+ """
+ return bool(
+ statement.get_column_names() & SEQUENCE_PSEUDO_COLUMNS
+ or statement.get_disallowed_functions(set(SEQUENCE_FUNCTIONS))
+ )
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """
+ Whether the transform contains a balanced Jinja block.
+
+ A block is an opening delimiter followed, anywhere later, by its closing
+ one -- the same thing ``{{.*?}}`` and its two siblings match under
+ ``re.DOTALL``. Scanned with `str.find` rather than that pattern, because a
+ lazy match retried from every opening delimiter is quadratic in a run of
+ them, and this runs on stored transforms with no length bound of its own:
+ `is_transform_active` reads whatever the column holds. The earliest opening
+ delimiter is the only one worth trying, since any closing delimiter after a
+ later one is also after it.
+ """
+ if not transform:
+ return False
+ for opening, closing in JINJA_BLOCK_DELIMITERS:
+ start = transform.find(opening)
+ if start != -1 and transform.find(closing, start + len(opening)) != -1:
+ return True
+ return False
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+
+ Three spellings have to be looked for, because one name reaches the parse
+ three ways: as a function call, as a zero-argument call a dialect resolves
+ itself, and -- for the datetime keywords -- as a bare word that parses as a
+ column reference.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ # The parenthesis-free spellings, which parse as columns rather than
+ # functions and so are invisible to the walk above. See
+ # `BARE_WALL_CLOCK_KEYWORDS`.
+ found |= {
+ name.upper() for name in BARE_WALL_CLOCK_KEYWORDS & statement.get_column_names()
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error( # noqa: C901
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ And it must be a *read*. Shape is a separate question from effect: a bare
+ scalar expression can still write, so `SQLStatement.is_mutating` is asked
+ too -- the same question SQL Lab and the chart executor ask before letting
+ SQL run. See the gate itself for what that reaches and what it does not.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ # Also ahead of the parse, and for a stronger reason than cost: every gate
+ # below reasons about the parse tree, and this is the one construct that
+ # makes the parse tree describe a different statement from the one the
+ # engine runs. Checked here as well as in `validate_transform` because this
+ # is the door a row written by an earlier release still comes through.
+ if contains_executable_comment(transform):
+ return str(
+ _(
+ "A partition value transform cannot contain a MySQL "
+ "executable comment, which the database executes and every "
+ "validator reads as a comment."
+ )
+ )
+
+ if contains_unicode_escaped_identifier(transform):
+ return str(
+ _(
+ "A partition value transform cannot name anything through a "
+ 'U&"..." escape sequence, which the database decodes and '
+ "every validator reads literally."
+ )
+ )
+
+ # Same door, same reason: the name the denylist below would match is not
+ # the name the engine resolves. See `UNICODE_ESCAPED_IDENTIFIER_RE`.
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The read-only gate, which nothing above implies. The shape gates ask what
+ # the transform *selects*; this asks what evaluating it *does*, and a bare
+ # scalar expression can still write. `nextval(:value)` on PostgreSQL
+ # advances a sequence: one function call, no clause, no sub-query, and not
+ # in the default `DISALLOWED_SQL_FUNCTIONS` either -- so every gate above
+ # passes it and the probe then runs it. `setval` is the same shape, and
+ # `exp.Execute` and the opaque-`exp.Command` forms arrive the same way.
+ #
+ # The large-object writers (`lo_export`, `lowrite`, `lo_from_bytea`, ...)
+ # are caught here too, and the shipped denylist happens to name them as
+ # well -- but that is config an operator can replace, while this is not.
+ #
+ # `is_mutating` is the same question SQL Lab, `get_virtual_table_metadata`
+ # and the chart executor ask before letting SQL run, so a transform is held
+ # to the bar the rest of Superset already sets rather than to one invented
+ # here. Unconditional rather than gated on `Database.allow_dml`: a transform
+ # is a scalar function of `:value` by definition, so there is no legitimate
+ # mutating one, and the probe runs on a cache schedule nobody chose -- a
+ # write would repeat every time the entry expired.
+ #
+ # It bears saying what this does not reach. A user-defined function whose
+ # body writes is a plain call no parser can tell from `lower(:value)`, and
+ # `is_mutating`'s function-name walk is PostgreSQL-only by design, since the
+ # same names are read-only elsewhere. Neither residual is specific to this
+ # feature -- a dataset editor can already have the engine evaluate an
+ # arbitrary expression through a calculated column or a virtual dataset's
+ # SQL -- and closing them means authorizing the preview against the
+ # database, not parsing harder.
+ if statement.is_mutating():
+ return str(
+ _(
+ "A partition value transform cannot change data. It is "
+ "evaluated against the database to check that it mirrors, so "
+ "it has to be a read."
+ )
+ )
+
+ # Not reached by the walk above, which is why it is its own gate: a
+ # sequence pseudo-column is a *column* to the parser and a write to the
+ # engine. See `SEQUENCE_PSEUDO_COLUMNS`.
+ if references_sequence(statement):
+ return str(
+ _(
+ "A partition value transform cannot read a sequence. "
+ "NEXTVAL advances the sequence every time it is evaluated, "
+ "and the transform is evaluated on a cache schedule."
+ )
+ )
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the
+ probe uninspected. Rendering is not what makes that true: a string element
+ is checked by `literal_round_trips` before it is rendered -- the dialect's
+ literal processor and the engine's lexer do not always agree about what a
+ rendered literal says -- and `probe_sql_is_evaluable` re-reads the finished
+ query, which is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def _placeholder_is_bindable(transform: str) -> bool:
+ """
+ Whether SQLAlchemy's ``text()`` can see ``:value`` as a bound parameter.
+
+ `VALUE_PLACEHOLDER_RE` is ``:value\b``, which matches the placeholder in a
+ Postgres cast such as ``:value::bigint``. SQLAlchemy's own bind scan is
+ ``(?<![:\\w$]):([\\w$]+)(?![:\\w$])`` -- note the trailing exclusion -- so a
+ following colon stops it: ``text(":value::bigint")`` reports a parameter
+ named ``valu``, and ``.bindparams(bindparam("value"))`` then raises
+ ``ArgumentError``.
+
+ `_probe` swallows that, so the only symptom was a perfectly valid transform
+ whose mapping silently never pruned, and a preview reporting an engine
+ failure for SQL that was never sent. Every write-side gate passes the
+ transform: it parses, it is a bare expression, and the placeholder *is* in
+ an executable position.
+
+ Answered by attempting the bind itself rather than by pattern-matching
+ ``::`` or reading ``text()``'s private parameter map, so this cannot
+ disagree with what `build_probe_sql` is about to do -- on any dialect, or on
+ a SQLAlchemy whose scan changes.
+ """
+ try:
+ sa.text(transform).bindparams(sa.bindparam("value", value=None))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return False
+ return True
+
+
+def escape_foreign_colons(transform: str) -> str:
+ """
+ ``transform`` with every colon but the ``:value`` placeholder escaped.
+
+ `sqlalchemy.text` reads any ``:word`` as a bind parameter, including one
+ inside a string literal, and an unbound parameter renders as ``NULL``
+ under literal binds rather than raising. So ``:value || \':suffix\'``
+ compiled to ``'us' || 'NULL'``: the mirror asked for a partition value no
+ row holds and the chart dropped rows, with no error for `_probe` to
+ swallow and nothing on screen to say so.
+
+ Escaped rather than refused, because a colon in a literal is ordinary --
+ ``concat(:value, \':\', region)`` builds a composite key -- and the
+ placeholder is the only colon this module means to interpret. `text()`
+ reads ``\\:`` as a literal colon.
+
+ Only the bound path needs this. A `RawProbeValue` or an unbindable
+ placeholder is substituted as text by `parse_skeleton`, which never hands
+ the transform to `text()` at all.
+ """
+ pieces: list[str] = []
+ cursor = 0
+ for match in VALUE_PLACEHOLDER_RE.finditer(transform):
+ pieces.append(transform[cursor : match.start()].replace(":", r"\:"))
+ pieces.append(match.group(0))
+ cursor = match.end()
+ pieces.append(transform[cursor:].replace(":", r"\:"))
+ return "".join(pieces)
+
+
+def literal_round_trips(value: Any, dialect: Dialect | None, engine: str) -> bool:
+ """
+ Whether the engine reads a rendered ``value`` back as that same value.
+
+ The probe runs with no bound parameters, so every value reaches the engine
+ as literal text the driver wrote (see `build_probe_sql`). Whether that text
+ says what the value says is a question about two independent spellings: the
+ driver's escaping, and the engine's lexer. SQLAlchemy's default renderer
+ doubles apostrophes and passes backslashes through; Hive and Spark honour
+ the backslash and not the doubling, so ``'O''Brien'`` is read there as two
+ adjacent literals -- the transform is evaluated at ``OBrien``, and the
+ mirror asks for a partition key that holds none of the rows the filter
+ keeps. The same gap in the other direction lets a value close its own quote
+ and have the rest of it read as SQL.
+
+ Escaping is not the repair. Whether a backslash introduces an escape is a
+ per-session server setting -- ``standard_conforming_strings`` on Postgres,
+ ``NO_BACKSLASH_ESCAPES`` on MySQL, ``escapedStringLiterals`` on Spark -- and
+ nothing in the engine specs exposes it. SQLAlchemy reads it off the server
+ into ``_backslash_escapes`` during ``initialize(connection)``, which the
+ probe's dialect never reaches: `_dialect_for` asks the ``Database`` for a
+ dialect, not for a connection, so Postgres renders ``a\\b`` as
+ ``'a\\\\b'`` and a server with the standard setting reads four
+ characters. An engine-spec flag would have to be defaulted, and either
+ default is wrong for a dozen engines: one leaves the hole open, the other
+ corrupts the probed value.
+
+ So the premise is verified rather than declared, the way
+ `probe_sql_is_evaluable` verifies the finished statement. A value that does
+ not survive the round trip is not mirrored, which costs the query its
+ pruning and nothing else.
+
+ The short-circuit is a proof, not a guess, and it matters for cost: a
+ 200-member ``IN`` list would otherwise parse 200 times on the chart path.
+ If the renderer emitted the value between two quotes and changed nothing in
+ it, and the value carries neither a quote nor a backslash, then no lexer in
+ play can read it as anything but itself. Both exclusions are load-bearing:
+ on Hive ``a\\b`` renders verbatim and reads as ``a`` followed by a
+ backspace.
+
+ :param value: a filter value about to be rendered into the probe
+ :param dialect: the dialect that will render it, as `_dialect_for` reports
+ :param engine: ``database.backend``, whose lexer reads the result
+ :return: whether the two agree about what the literal says
+ """
+ if isinstance(value, RawProbeValue):
+ # Already SQL, with no single value for a parse to be compared against:
+ # its elements are checked before they are rendered, by
+ # `ExploreMixin._array_mirror_probe_value`. A backslash surviving into
+ # the finished text is refused here all the same, as the backstop for a
+ # renderer this module does not own.
+ return "\\" not in value.sql
+ if not isinstance(value, str):
+ # Numbers and instants are not written between delimiters, so there is
+ # no escaping for the two sides to disagree about.
+ return True
+
+ rendered = _compile_literal(sa.literal(value), dialect)
+ if rendered == f"'{value}'" and "'" not in value and "\\" not in value:
+ return True
+
+ try:
+ return (
+ SQLStatement(f"SELECT {rendered}", engine).get_select_literal_value()
+ == value
+ )
+ except SupersetParseError:
+ # A rendered literal the engine's own dialect will not parse is the
+ # strongest form of disagreement there is.
+ return False
+
+
+def value_round_trips(database: Database, value: Any) -> bool:
+ """
+ `literal_round_trips` for a caller holding a database, not a dialect.
+
+ Which renderer and which lexer apply is this module's business, so the two
+ callers outside it -- the chart path's own gate in
+ `ExploreMixin.mirror_probe_request` and the mapping summary Explore reads
+ -- ask in these terms and stay out of it.
+
+ :param database: the database whose driver renders and whose engine reads
+ :param value: a filter value about to be rendered into the probe
+ :return: whether the two agree about what the literal says
+ """
+ return literal_round_trips(value, _dialect_for(database), database.backend)
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text. That is not itself a boundary:
+ the processor's escaping is not always the escaping the engine honours, and
+ a value can close its own quote through the gap. The boundary is
+ `literal_round_trips` on the way in -- which callers must have run, like
+ `stored_expression_error` below -- and `probe_sql_is_evaluable` on the way
+ out.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ bindable = _placeholder_is_bindable(transform)
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ elif bindable:
+ # Every other colon escaped first: `text()` would read one inside a
+ # string literal as a second bind parameter and render it `NULL`.
+ # See `escape_foreign_colons`.
+ clause = sa.text(escape_foreign_colons(transform)).bindparams(
+ sa.bindparam("value", value=value)
+ )
+ rendered = _compile_literal(clause, dialect)
+ else:
+ # `text()` cannot see the placeholder (see
+ # `_placeholder_is_bindable`), so the value is rendered by the
+ # dialect's own literal processor first and substituted as SQL
+ # text. The same two steps in the other order: binding exists to
+ # get the value through that processor, and `_compile_literal`
+ # inlines the result either way, so this is the same string by a
+ # different route -- not a loosening of the "never interpolate a
+ # raw value" rule. `parse_skeleton` substitutes literally, so the
+ # rendered literal arrives here exactly as it was rendered, which
+ # is what makes `literal_round_trips`' verdict on it good for this
+ # branch as much as for the bound one.
+ rendered = parse_skeleton(
+ transform, _compile_literal(sa.literal(value), dialect)
+ )
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Five things have to hold, and all five are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+ * No comment, anywhere. A value that closes its own quote has to hide the
+ text `build_probe_sql` appended after it, and a comment is the only way
+ to do that and still balance the quotes -- so this is what makes the
+ alias check above sufficient rather than merely necessary. Read off the
+ parse rather than the text, so a comment *inside* a literal is data and
+ costs no pruning, and so the question is asked in the engine's own
+ dialect. A transform has no legitimate reason to carry one either; see
+ `EXECUTABLE_COMMENT_RE`.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ # Before the parse, because this gate's whole contract is that what the
+ # parse describes is what the engine will run, and an executable comment is
+ # precisely the text where that stops being true. The transform is already
+ # refused for carrying one; this covers the compiled statement, so no later
+ # change to how values are rendered can reintroduce it behind the gates
+ # below.
+ if contains_executable_comment(sql) or contains_unicode_escaped_identifier(sql):
+ return False
+
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if not isinstance(statement, SQLStatement):
+ # A dialect whose statements this gate cannot take apart -- KQL -- gets
+ # no probe rather than an unchecked one. It never had one: the clause
+ # inspection below is implemented for SQL statements only, and the
+ # alternative to declining here is an `AttributeError` that `_probe`
+ # swallows into the same outcome, less legibly.
+ return False
+ if statement.has_comment():
+ return False
+ if statement.has_subquery():
+ return False
+ if statement.get_clause_names() - {"from"}:
+ return False
+ if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+ """
+ The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+ Parsed rather than string-compared so that the comparison in
+ `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+ not parse answers ``None``, which no statement carrying a FROM can match --
+ the probe then declines, which is the right way for an unreadable engine
+ constant to fail.
+ """
+ if not from_suffix.strip():
+ return None
+ try:
+ return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+ except SupersetParseError:
+ return None
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ # The value side of the premise `probe_sql_is_evaluable` checks on the
+ # finished statement: a value the driver and the engine would spell
+ # differently is not probed at all -- see `literal_round_trips`.
+ #
+ # `ExploreMixin.mirror_probe_request` declines one earlier, with a reason
+ # the preview can explain, and that is the gate an owner sees. This is the
+ # one that cannot be walked around. `_collect_partition_mirror_range`
+ # appends its bounds into the sink without passing through that method at
+ # all, and both paths can hand back a value the gate never saw: on a column
+ # carrying a `python_date_format`, what is probed is
+ # `strftime(that format)` -- text no mapping gate has ever read.
+ #
+ # Above `_run_probe` on purpose. This is a property of one input, not of
+ # the transform, and a verdict recorded here would withdraw the mirror for
+ # every later value of a transform the engine evaluates perfectly well.
+ dialect = _dialect_for(database)
+ if not all(
+ literal_round_trips(value, dialect, database.backend) for value in distinct
+ ):
+ logger.warning(
+ "A filter value is not written the same way by the driver and the "
+ "database, so the partition transform is not probed at it; this "
+ "query will not prune"
+ )
+ return None
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+
+ The verdict is about the *transform*: whether the engine evaluated it at
+ all. A ``NULL`` among the results is not that -- it is this input's answer,
+ and `NULLIF(:value, 0)` returning ``NULL`` for ``n = 0`` says nothing about
+ the same transform on ``n = 2``. Counting it withdrew the promise for the
+ whole transform, and nothing restored it: a *failed* probe is deliberately
+ not cached, so the next chart re-probes and re-records, but a ``NULL`` is a
+ successful probe and *is* cached -- so the false verdict outlived every
+ later hit, and the editor reported a working mapping as not mirroring
+ while the query went on pruning. The per-input skip still happens where it
+ belongs, in the caller's own ``NULL`` guard.
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=values is not None,
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ from_suffix = database.db_engine_spec.select_without_from_suffix
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ from_suffix,
+ )
+ if not probe_sql_is_evaluable(
+ sql, database.backend, len(distinct), from_suffix
+ ):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
Review Comment:
The probe reads each transform result back through `get_df`, so it inherits the driver's default value decoding, and two of those decodings change the value before it is mirrored. On ClickHouse, Superset sets `UInt64` to decode as signed, so with `n = 1` filtered, a `UInt64` partition column and `toUInt64(:value) + toUInt64('9223372036854775808')`, the row `(n=1, p=9223372036854775809)` matches the filter but the probe returns `-9223372036854775807`, so the mirror becomes `p = -9223372036854775807 OR p IS NULL` and drops it (a `cityHash64(:value)` key would hit this for about half of all values). Likewise a `DateTime64(9)` key from `fromUnixTimestamp64Nano(1767225600123456788 + :value)` comes back at microsecond precision, so `p = '2026-01-01 00:00:00.123456'` excludes the row holding `...123456789`. Both fail silently as wrong numbers rather than an error. Should the probe decline mirroring (or read the value unsigned / as text) whenever the result cannot round-trip exactly?
##########
superset/models/helpers.py:
##########
@@ -4449,36 +4558,777 @@ def dttm_sql_literal(self, dttm: datetime, col: "TableColumn") -> str:
return f"""'{dttm.strftime("%Y-%m-%d %H:%M:%S.%f")}'"""
- def get_time_filter( # pylint: disable=too-many-arguments # noqa: C901
+ def _mirror_probe_value(self, dttm: datetime, col: Optional["TableColumn"]) -> Any:
+ """
+ ``dttm`` in the mapped column's own stored representation.
+
+ The predicate this mirror stands in for compares the column against
+ `dttm_sql_literal(dttm, col)`, so the transform has to be probed with
+ the same value. On a column stored as an epoch integer, ``T`` is a
+ function of an integer: probing it with a `datetime` either returns
+ something unrelated to the partition keys or raises, and a raise costs
+ the dataset its pruning silently.
+
+ Only the ``python_date_format`` branches of `dttm_sql_literal` are
+ reproduced, because only those produce a *value*. `convert_dttm` yields
+ engine-specific SQL text, which cannot be bound as a parameter; its own
+ divergence from the probe is handled by widening the bounds instead
+ (`_engine_literal_resolution`).
+
+ In `dttm_sql_literal`'s own order, though: it asks ``convert_dttm``
+ first and reaches the format only when the engine answers nothing. A
+ column can carry both -- a TIMESTAMP with a ``%Y%m%d``
+ ``python_date_format``, or an entry in
+ ``python_date_format_by_column_name`` -- and applying the format
+ unconditionally probed a value the real predicate never compares.
+ ``event_time >= '2026-01-01 00:00:00'`` mirrored as
+ ``partition_col >= '20260101'``, and a January 15 row keyed
+ ``2026-01-15`` sorts below that string, so the chart lost a row the
+ filter keeps.
+
+ Where the engine does answer, the `datetime` is returned unchanged and
+ the widening path takes over -- which is exactly what already happens
+ for every temporal column that carries no format at all.
+ """
+ if col is None:
+ return dttm
+
+ if col.type and self.db_engine_spec.convert_dttm(
+ col.type, dttm, db_extra=self.db_extra
+ ):
+ # The format is unreachable in `dttm_sql_literal` for this column,
+ # so reproducing it here would describe a different bound.
+ return dttm
+
+ tf = col.python_date_format
+ if not tf and self.db_extra:
+ tf = self.db_extra.get("python_date_format_by_column_name", {}).get(
+ col.column_name
+ )
+ if not tf:
+ return dttm
+
+ if tf in EPOCH_FORMATS:
+ dttm_tz_aware = dttm
+ if dttm_tz_aware.tzinfo is None:
+ dttm_tz_aware = dttm_tz_aware.replace(tzinfo=timezone.utc)
+ return int(dttm_tz_aware.timestamp()) * EPOCH_FORMATS[tf]
+ return dttm.strftime(tf)
+
+ def _engine_literal_resolution(
+ self, dttm: datetime, col: Optional["TableColumn"]
+ ) -> LiteralResolution:
+ """
+ How much of ``dttm`` survives into this engine's literal for ``col``.
+
+ The real predicate compares `dttm_sql_literal(dttm, col)`, so whatever
+ that literal throws away is a bound the engine never sees. A mirror
+ derived from the full precision then describes a *narrower* range than
+ the predicate it stands in for -- and narrower means it drops rows the
+ filter keeps.
+
+ Two things get thrown away in practice:
+
+ - the sub-second part. SQLite renders a timestamp with
+ ``timespec="seconds"``.
+ - the time of day entirely. Every engine spec with a ``types.Date``
+ branch renders ``dttm.date().isoformat()``, so Presto, Trino,
+ BigQuery and some two dozen others answer `DATE '2026-01-01'` for a
+ bound of 10:00 -- and `T(DATE '2026-01-01')` is below the mirror's
+ own lower bound, so the whole first day is dropped.
+
+ Detected rather than enumerated per engine, because the branch depends
+ on the column's type as well as the spec: instants differing only in the
+ part under test render as the same text exactly when the engine has
+ thrown that part away.
+
+ The day test uses two fixed times of day rather than ``dttm`` and one
+ alternative, so a bound that happens to sit on the hour the alternative
+ uses cannot read as "no time at all". Neither probe sits at midnight on
+ purpose: SQLite renders a DATE column at exactly midnight as a bare
+ date, so a midnight probe would differ from its alternative for a
+ reason that has nothing to do with resolution.
+
+ Likewise both sub-second probes carry a non-zero remainder. Comparing
+ against ``dttm`` truncated to the second looks like the obvious test and
+ is wrong for the same formatting-boundary reason.
+
+ A non-temporal column has no answer here, and asking anyway gets a wrong
+ one. SQLite's ``convert_dttm`` renders for ``types.String`` as well as
+ for the date types, so a ``VARCHAR`` mapped column reads as
+ second-resolution -- and a filter value that happens to *look* like an
+ instant then has its bound rounded as though the engine had truncated
+ it. On a VARCHAR ``code`` mapped onto a VARCHAR ``p`` by ``:value``,
+ ``code < '2026-07-06T10:08:11.500000'`` was mirrored as
+ ``p <= '2026-07-06 10:08:12.000000'``; a space sorts before ``T``, so a
+ row holding ``2026-07-06T09:00:00`` fell outside the mirror while
+ matching the filter.
+
+ The guard lives here rather than in each caller so this and
+ `_column_literal_resolution` cannot disagree about which column is
+ coarse -- which is the same reason that helper delegates to this one.
+
+ "Temporal" is the column's generic type, not just its ``is_dttm`` flag.
+ `get_time_filter` renders a bound through ``convert_dttm`` for any
+ ``DATE`` column, flagged or not, so a ``DATE`` column left unflagged
+ still compares a bare day -- and skipping the resolution check there
+ would hand the probe 10:00 for a bound the engine reads as midnight.
+ """
+ if col is None or not col.type or col.type_generic != GenericDataType.TEMPORAL:
+ return LiteralResolution.FULL
+
+ def render(moment: datetime) -> Optional[str]:
+ return self.db_engine_spec.convert_dttm(
+ col.type, moment, db_extra=self.db_extra
+ )
+
+ try:
+ early = render(dttm.replace(hour=1, minute=2, second=3, microsecond=444444))
+ late = render(
+ dttm.replace(hour=22, minute=33, second=44, microsecond=555555)
+ )
+ if early is not None and early == late:
+ return LiteralResolution.DAY
+
+ # Flooring to the second is a no-op on a bound that has no
+ # sub-second part, so there is nothing to detect.
+ if not dttm.microsecond:
Review Comment:
The resolution probe treats a whole-second bound as exact (`FULL`) before comparing any renders, but on SQL Server a `SMALLDATETIME` column is compared at minute resolution server-side: `CONVERT(SMALLDATETIME, '2000-01-01 00:00:29', 20)` rounds down to `00:00:00`. With mapped `t SMALLDATETIME` and a monotonic `DATEDIFF(second, CAST('2000-01-01' AS datetime2), CAST(:value AS datetime2))` transform, a range starting at `00:00:29` keeps the row `(t='2000-01-01 00:00:00', p=0)`, but the mirror adds `p >= 29` and drops it. Since the text of the literal can't reveal that coercion, should `SMALLDATETIME` (or any type the engine rounds on conversion) be treated as coarser than a second, or decline range mirroring?
##########
tests/unit_tests/connectors/sqla/partition_mapping_test.py:
##########
@@ -0,0 +1,3643 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Unit tests for ``superset.connectors.sqla.partition_mapping``."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from decimal import Decimal
+from importlib import import_module
+from typing import Any, cast
+from unittest.mock import MagicMock, patch, PropertyMock
+
+import pandas as pd
+import pytest
+from dateutil.relativedelta import relativedelta
+from flask import Flask
+from pytest_mock import MockerFixture
+from sqlalchemy.dialects import mysql, postgresql
+
+from superset.config import DISALLOWED_SQL_FUNCTIONS
+from superset.connectors.sqla.models import SqlaTable, TableColumn
+from superset.connectors.sqla.partition_mapping import (
+ _mirror_verdict_cache_key,
+ _placeholder_is_bindable,
+ _probe_cache_key,
+ _reads_as_temporal,
+ _render_literal,
+ _render_predicate,
+ BARE_WALL_CLOCK_KEYWORDS,
+ build_mirrored_predicates,
+ build_probe_sql,
+ contains_executable_comment,
+ contains_jinja,
+ contains_value_placeholder,
+ drop_unmapped_value_transforms,
+ equality_mirrors_safely,
+ evaluate_transform,
+ find_non_deterministic_functions,
+ grain_bucket_width,
+ GRAIN_BUCKET_WIDTHS,
+ is_bare_expression,
+ is_parseable,
+ is_transform_active,
+ is_unfinished,
+ known_mirror_verdict,
+ literal_round_trips,
+ MappingValidationIssue,
+ mirror_operator,
+ MIRRORABLE_ALWAYS,
+ MIRRORABLE_IF_MONOTONIC,
+ mirrorable_operators,
+ NON_DETERMINISTIC_FUNCTIONS,
+ parse_error_detail,
+ placeholder_is_executable,
+ probe_sql_is_evaluable,
+ probed_value_type_error,
+ RawProbeValue,
+ resolve_partition_mapping,
+ stored_expression_error,
+ validate_partition_mapping,
+ validate_transform,
+)
+from superset.constants import TimeGrain
+from superset.db_engine_specs.base import BaseEngineSpec
+from superset.db_engine_specs.mysql import MySQLEngineSpec
+from superset.db_engine_specs.oracle import OracleEngineSpec
+from superset.db_engine_specs.postgres import PostgresEngineSpec
+from superset.models.core import Database
+from superset.sql.parse import SQLStatement
+from superset.utils.core import FilterOperator, GenericDataType, override_user
+
+
+@pytest.fixture(autouse=True)
+def real_probe_cache(app: Flask) -> Any:
+ """
+ The test app runs a null cache, which would make every cache assertion here
+ vacuously pass. Swap in a real in-memory one for the duration.
+ """
+ from flask_caching import Cache
+
+ from superset.extensions import cache_manager
+
+ cache = Cache(config={"CACHE_TYPE": "SimpleCache", "CACHE_DEFAULT_TIMEOUT": 300})
+ cache.init_app(app)
+ original = cache_manager._cache # noqa: SLF001
+ cache_manager._cache = cache # noqa: SLF001
+ yield
+ cache_manager._cache = original # noqa: SLF001
+
+
+@pytest.fixture(autouse=True)
+def enable_partition_filter_mapping(app: Flask) -> Any:
+ """The feature ships off; every test here exercises it on."""
+ original = app.config["DEFAULT_FEATURE_FLAGS"].get("PARTITION_FILTER_MAPPING")
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = True
+ yield
+ if original is None:
+ del app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"]
+ else:
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = original
+
+
+def _table(**kwargs: Any) -> SqlaTable:
+ database = Database(database_name="test_db", sqlalchemy_uri="sqlite://")
+ defaults: dict[str, Any] = {
+ "table_name": "web_events",
+ "database": database,
+ "main_dttm_col": "event_time",
+ "columns": [
+ TableColumn(column_name="event_time", is_dttm=True, type="TIMESTAMP"),
+ TableColumn(
+ column_name="dt_epoch",
+ type="BIGINT",
+ partition_value_transform=None,
+ ),
+ TableColumn(column_name="country", type="VARCHAR"),
+ TableColumn(column_name="region_key", type="VARCHAR"),
+ ],
+ }
+ defaults.update(kwargs)
+ return SqlaTable(**defaults)
+
+
+def _mapped_table(
+ *,
+ partition_column: str = "dt_epoch",
+ mapped_column: str = "event_time",
+ transform: str | None = "unix_timestamp(:value)",
+ monotonic: bool = True,
+ partition_mapped_column: str | None = None,
+ main_dttm_col: str | None = "event_time",
+) -> SqlaTable:
+ table = _table(main_dttm_col=main_dttm_col)
+ table.partition_column = partition_column
+ table.partition_mapped_column = partition_mapped_column
+ for column in table.columns:
+ if column.column_name == mapped_column:
+ column.partition_value_transform = transform
+ column.partition_transform_is_monotonic = monotonic
+ return table
+
+
+# ---------------------------------------------------------------------------
+# §2 — operator safety matrix
+# ---------------------------------------------------------------------------
+
+
+def test_equality_and_in_are_always_mirrorable() -> None:
+ """``=`` and ``IN`` are safe for any function ``T``."""
+ assert MIRRORABLE_ALWAYS == {FilterOperator.EQUALS, FilterOperator.IN}
+
+
+def test_range_operators_require_a_monotonic_transform() -> None:
+ assert MIRRORABLE_IF_MONOTONIC == {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+ }
+
+
+def test_mirrorable_operators_excludes_ranges_when_not_monotonic() -> None:
+ assert mirrorable_operators(is_monotonic=False) == MIRRORABLE_ALWAYS
+
+
+def test_mirrorable_operators_includes_ranges_when_monotonic() -> None:
+ assert mirrorable_operators(is_monotonic=True) == (
+ MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+ )
+
+
+@pytest.mark.parametrize(
+ "operator",
+ [
+ FilterOperator.NOT_EQUALS,
+ FilterOperator.NOT_IN,
+ FilterOperator.LIKE,
+ FilterOperator.ILIKE,
+ FilterOperator.NOT_LIKE,
+ FilterOperator.NOT_ILIKE,
+ FilterOperator.IS_NULL,
+ FilterOperator.IS_NOT_NULL,
+ FilterOperator.IS_TRUE,
+ FilterOperator.IS_FALSE,
+ ],
+)
+def test_negations_and_pattern_matches_are_never_mirrorable(
+ operator: FilterOperator,
+) -> None:
+ """
+ ``T`` is not injective, so ``col != v`` does **not** imply ``T(col) != T(v)``:
+ mirroring it would drop rows the original filter keeps.
+ """
+ assert operator not in mirrorable_operators(is_monotonic=True)
+
+
+def test_equality_is_dropped_when_the_engine_does_not_compare_byte_exactly() -> None:
+ """
+ "Safe for any function ``T``" reasons about value equality: ``T`` is a
+ function, so ``col = v`` gives ``T(col) = T(v)``. The engine reasons about
+ *SQL* equality, and the two part company under a case-insensitive
+ collation -- a stored ``'us'`` satisfies a filter for ``'US'`` while the
+ mirror ``hex('US')`` excludes the row, and the chart loses it silently.
+ """
+ assert mirrorable_operators(is_monotonic=False, equality_is_safe=False) == set()
+
+
+def test_ranges_survive_an_unsafe_equality() -> None:
+ """
+ Range mirroring already rests on the owner declaring ``T``
+ order-preserving with respect to the column's own order -- an assertion
+ about the very comparison semantics this gate checks for. Equality has no
+ such declaration behind it, which is why only equality is withdrawn.
+ """
+ assert (
+ mirrorable_operators(is_monotonic=True, equality_is_safe=False)
+ == MIRRORABLE_IF_MONOTONIC
+ )
+
+
+@pytest.mark.parametrize(
+ "operator,expected",
+ [
+ (FilterOperator.GREATER_THAN, FilterOperator.GREATER_THAN_OR_EQUALS),
+ (FilterOperator.LESS_THAN, FilterOperator.LESS_THAN_OR_EQUALS),
+ (
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ ),
+ (FilterOperator.LESS_THAN_OR_EQUALS, FilterOperator.LESS_THAN_OR_EQUALS),
+ (FilterOperator.EQUALS, FilterOperator.EQUALS),
+ (FilterOperator.IN, FilterOperator.IN),
+ ],
+)
+def test_a_strict_bound_mirrors_non_strictly(
+ operator: FilterOperator, expected: FilterOperator
+) -> None:
+ """
+ Order-preserving means non-decreasing, not injective, so ``col < v``
+ implies only ``T(col) <= T(v)``. A day-key transform maps a whole day onto
+ one value and a strict mirror drops the boundary bucket. The non-strict
+ cases are already safe and pass through, which is what makes applying this
+ twice harmless.
+ """
+ assert mirror_operator(operator) == expected
+
+
+def test_relaxing_a_bound_stays_inside_the_mirrorable_set() -> None:
+ """
+ The substitution is about strictness, not about which filters mirror. The
+ Explore indicator reads `mirrorable_operators`, so leaving that set alone is
+ what keeps the glyph from promising pruning the SQL does not do -- and it is
+ also what guarantees `handle_comparison_filter` is never handed an operator
+ it has no case for.
+ """
+ assert {
+ mirror_operator(operator) for operator in MIRRORABLE_IF_MONOTONIC
+ } <= MIRRORABLE_IF_MONOTONIC
+
+
+def _column(type_: str) -> TableColumn:
+ database = Database(database_name="t", sqlalchemy_uri="sqlite://")
+ table = SqlaTable(table_name="t", database=database)
+ return TableColumn(column_name="c", type=type_, table=table)
+
+
+@pytest.mark.parametrize(
+ "type_, binary, expected",
+ [
+ ("VARCHAR", True, True),
+ ("VARCHAR", False, False),
+ # Numeric and temporal comparison is exact everywhere.
+ ("BIGINT", False, True),
+ ("TIMESTAMP", False, True),
+ ("DOUBLE", False, True),
+ ],
+)
+def test_equality_mirrors_safely_only_guards_string_columns(
+ app: Flask, type_: str, binary: bool, expected: bool
+) -> None:
+ class _Spec(BaseEngineSpec):
+ binary_string_comparison = binary
+
+ with app.app_context():
+ assert equality_mirrors_safely(_column(type_), _Spec) is expected
+
+
+@pytest.mark.parametrize(
+ "type_, expected",
+ [
+ # The padded types: `'US'` and `'US '` are equal in the column, and
+ # `lower()` of the two is not.
+ ("CHAR(2)", False),
+ ("CHAR", False),
+ ("CHARACTER(2)", False),
+ ("NCHAR(2)", False),
+ # What PostgreSQL reflection reports for a `CHAR(n)` column.
+ ("BPCHAR", False),
+ ("bpchar(2)", False),
+ ("NATIONAL CHARACTER(2)", False),
+ # The variable-width types start with the same letters and must not be
+ # caught by it.
+ ("VARCHAR(2)", True),
+ ("NVARCHAR(2)", True),
+ ("CHARACTER VARYING(2)", True),
+ ("TEXT", True),
+ ],
+)
+def test_a_padded_character_column_declines_equality_on_a_byte_exact_engine(
+ app: Flask, type_: str, expected: bool
+) -> None:
+ """
+ `binary_string_comparison` speaks for the engine's default comparison,
+ which PostgreSQL declares -- and a `CHAR(2)` there still matches a filter
+ for `'US '` against a stored `'US'`, so the mirror `lower('US ')` excludes
+ the row. Padding is a property of the type, so it is asked per column.
+ """
+
+ class _Spec(BaseEngineSpec):
+ binary_string_comparison = True
+
+ with app.app_context():
+ assert equality_mirrors_safely(_column(type_), _Spec) is expected
+
+
+def test_redshift_does_not_opt_in_to_byte_exact_comparison() -> None:
+ """
+ Redshift ignores trailing blanks for `VARCHAR` as well as `CHAR`, so the
+ `True` it inherits from `PostgresBaseEngineSpec` would be wrong.
+ """
+ from superset.db_engine_specs.redshift import RedshiftEngineSpec
+
+ assert RedshiftEngineSpec.binary_string_comparison is False
+
+
+@pytest.mark.parametrize(
+ "type_",
+ [
+ # PostgreSQL's case-insensitive text type matches no type pattern, so
+ # the spec cannot classify it -- and its whole purpose is the
+ # comparison this gate is about.
+ "citext",
+ # A column with no declared type at all.
+ "",
+ "SOME_EXTENSION_TYPE",
+ ],
+)
+def test_equality_mirrors_safely_fails_closed_on_an_unresolvable_type(
+ app: Flask, type_: str
+) -> None:
+ """
+ The gate exists to stop a silent wrong answer, so a column whose type it
+ cannot read is treated as the risky case rather than waved through.
+
+ `type_generic` answers `None` for these -- neither string nor not-string --
+ and the old reading waved them through, which for `citext` admitted exactly
+ the case-insensitive equality the gate is for. Only the exception branch
+ failed closed, though the docstring claimed otherwise.
+ """
+ with app.app_context():
+ assert equality_mirrors_safely(_column(type_), PostgresEngineSpec) is False
+
+
+def test_equality_mirrors_safely_reads_past_the_temporal_flag(app: Flask) -> None:
+ """
+ `TableColumn.type_generic` answers `TEMPORAL` for anything carrying
+ `is_dttm`, so a `VARCHAR` flagged temporal skipped the string check
+ entirely: on MySQL a filter for `'2026-01-01T00:00:00'` matches a stored
+ `'...t00:00:00'` while the mirror `hex('...T...')` excludes it.
+ """
+ with app.app_context():
+ flagged = _column("VARCHAR")
+ flagged.is_dttm = True
+ assert flagged.type_generic == GenericDataType.TEMPORAL
+ # Declines where plain text declines...
+ assert equality_mirrors_safely(flagged, MySQLEngineSpec) is False
+ # ...and is admitted where plain text is admitted.
+ assert equality_mirrors_safely(flagged, PostgresEngineSpec) is True
+
+ # A column that really is temporal is unaffected.
+ real = _column("TIMESTAMP")
+ real.is_dttm = True
+ assert equality_mirrors_safely(real, MySQLEngineSpec) is True
+
+
+def test_no_mapped_column_leaves_the_matrix_alone(app: Flask) -> None:
+ """Nothing to reason about, and the resolver bails out on it anyway."""
+ with app.app_context():
+ assert equality_mirrors_safely(None, BaseEngineSpec) is True
+
+
+@pytest.mark.parametrize(
+ "module, spec_name",
+ [
+ ("presto", "PrestoEngineSpec"),
+ ("hive", "HiveEngineSpec"),
+ ("trino", "TrinoEngineSpec"),
+ ("impala", "ImpalaEngineSpec"),
+ ("postgres", "PostgresEngineSpec"),
+ ("bigquery", "BigQueryEngineSpec"),
+ ("sqlite", "SqliteEngineSpec"),
+ ],
+)
+def test_the_byte_exact_engines_opt_in(module: str, spec_name: str) -> None:
+ """
+ The engines this feature targets compare text byte-exactly, so the gate
+ must not cost them the second canonical mapping (`lower(:value)` onto a
+ lowercased key).
+ """
+ spec = getattr(import_module(f"superset.db_engine_specs.{module}"), spec_name)
+ assert spec.binary_string_comparison is True
+
+
+@pytest.mark.parametrize("module, spec_name", [("mysql", "MySQLEngineSpec")])
+def test_a_case_insensitive_engine_does_not_opt_in(module: str, spec_name: str) -> None:
+ """
+ MySQL's default collation is `utf8mb4_0900_ai_ci`, which is exactly the
+ case the reviewer raised.
+ """
+ spec = getattr(import_module(f"superset.db_engine_specs.{module}"), spec_name)
+ assert spec.binary_string_comparison is False
+
+
+def test_the_base_spec_does_not_opt_in() -> None:
+ """A spec that has not said so does not mirror string equality."""
+ assert BaseEngineSpec.binary_string_comparison is False
+
+
+# ---------------------------------------------------------------------------
+# Time grain bucket widths
+# ---------------------------------------------------------------------------
+
+
+@pytest.mark.parametrize("grain", list(TimeGrain))
+def test_every_builtin_grain_has_a_known_bucket_width(
+ app: Flask, grain: TimeGrain
+) -> None:
+ """
+ The widening is only sound for a grain whose bucket width we know, so a
+ grain added upstream without a width here would silently stop mirroring.
+ This is the test that notices.
+ """
+ with app.app_context():
+ assert grain_bucket_width(grain.value, "sqlite") is not None
+
+
+def test_a_calendar_grain_widens_by_a_calendar_month(app: Flask) -> None:
+ """A month is not thirty days, and the month it lands in decides its width."""
+ with app.app_context():
+ width = grain_bucket_width(TimeGrain.MONTH.value, "sqlite")
+
+ assert width is not None
+ assert datetime(2026, 1, 31) + width == datetime(2026, 2, 28)
+ assert datetime(2026, 2, 1) + width == datetime(2026, 3, 1)
+
+
+def test_a_fractional_grain_has_a_width(app: Flask) -> None:
+ """
+ ``PT0.5H`` and ``P0.25Y`` are why the widths are written out rather than
+ parsed -- and the anchored week grains are intervals ``parse_duration``
+ rejects outright.
+ """
+ with app.app_context():
+ assert grain_bucket_width(TimeGrain.HALF_HOUR.value, "sqlite") == relativedelta(
+ minutes=30
+ )
+ assert grain_bucket_width(
+ TimeGrain.WEEK_ENDING_SATURDAY.value, "sqlite"
+ ) == relativedelta(days=7)
+
+
+def test_an_unknown_grain_has_no_known_width(app: Flask) -> None:
+ with app.app_context():
+ assert grain_bucket_width("P13X", "sqlite") is None
+ assert grain_bucket_width(None, "sqlite") is None
+
+
+def test_an_addon_grain_has_no_known_width(app: Flask) -> None:
+ """An operator-declared grain carries whatever duration string they typed."""
+ with app.app_context():
+ app.config["TIME_GRAIN_ADDONS"] = {"PT2S": "2 second"}
+ try:
+ assert grain_bucket_width("PT2S", "sqlite") is None
+ finally:
+ app.config["TIME_GRAIN_ADDONS"] = {}
+
+
+def test_a_builtin_grain_an_operator_redefined_has_no_known_width(
+ app: Flask,
+) -> None:
+ """
+ ``TIME_GRAIN_ADDON_EXPRESSIONS`` replaces a built-in grain's SQL for one
+ engine, so its duration no longer bounds the displacement *there* -- but it
+ still does on every other engine.
+ """
+ with app.app_context():
+ app.config["TIME_GRAIN_ADDON_EXPRESSIONS"] = {
+ "sqlite": {"P1D": "DATETIME({col}, 'start of year')"}
+ }
+ try:
+ assert grain_bucket_width(TimeGrain.DAY.value, "sqlite") is None
+ assert grain_bucket_width(TimeGrain.DAY.value, "hive") is not None
+ finally:
+ app.config["TIME_GRAIN_ADDON_EXPRESSIONS"] = {}
+
+
+def test_the_width_table_is_keyed_on_grain_durations(app: Flask) -> None:
+ """Keys are the ISO duration a filter carries, not the enum member name."""
+ assert GRAIN_BUCKET_WIDTHS[TimeGrain.DAY] == relativedelta(days=1)
+ assert set(GRAIN_BUCKET_WIDTHS) == {grain.value for grain in TimeGrain}
+
+
+# ---------------------------------------------------------------------------
+# §4.1 — resolving the effective mapping, and the defensive bail-outs
+# ---------------------------------------------------------------------------
+
+
+def test_resolve_returns_the_mapping_when_everything_lines_up(app: Flask) -> None:
+ with app.app_context():
+ mapping = resolve_partition_mapping(_mapped_table())
+
+ assert mapping is not None
+ assert mapping.partition_column == "dt_epoch"
+ assert mapping.mapped_column == "event_time"
+ assert mapping.value_transform == "unix_timestamp(:value)"
+ assert mapping.is_monotonic is True
+
+
+def test_effective_mapped_column_follows_main_dttm_col(app: Flask) -> None:
+ """No explicit override: the mapping follows the default datetime column."""
+ with app.app_context():
+ mapping = resolve_partition_mapping(_mapped_table())
+
+ assert mapping is not None
+ assert mapping.mapped_column == "event_time"
+
+
+def test_explicit_override_wins_over_main_dttm_col(app: Flask) -> None:
+ table = _mapped_table(
+ mapped_column="country",
+ transform="lower(:value)",
+ monotonic=False,
+ partition_mapped_column="country",
+ )
+ table.partition_column = "region_key"
+
+ with app.app_context():
+ mapping = resolve_partition_mapping(table)
+
+ assert mapping is not None
+ assert mapping.mapped_column == "country"
+ assert mapping.partition_column == "region_key"
+ assert mapping.is_monotonic is False
+
+
+def test_resolve_returns_none_when_the_feature_flag_is_off(app: Flask) -> None:
+ table = _mapped_table()
+ with app.app_context():
+ with patch(
+ "superset.connectors.sqla.partition_mapping.feature_flag_manager."
+ "is_feature_enabled",
+ return_value=False,
+ ):
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_without_a_partition_column(app: Flask) -> None:
+ table = _mapped_table()
+ table.partition_column = None
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_partition_column_no_longer_exists(
+ app: Flask,
+) -> None:
+ """A column sync can drop the physical partition column out from under us."""
+ table = _mapped_table()
+ table.partition_column = "dt_epoch_gone"
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_the_mapped_column_no_longer_exists(
+ app: Flask,
+) -> None:
+ table = _mapped_table(main_dttm_col="vanished")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_on_self_mapping(app: Flask) -> None:
+ """
+ ``partition_column == effective mapped column`` mirrors a column onto itself.
+ Save-time validation rejects it, but rows predating that validation exist.
+ """
+ table = _mapped_table(
+ partition_column="event_time",
+ mapped_column="event_time",
+ )
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+@pytest.mark.parametrize("transform", [None, "", " "])
+def test_resolve_returns_none_without_a_transform(
+ app: Flask, transform: str | None
+) -> None:
+ table = _mapped_table(transform=transform)
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_the_transform_lacks_the_placeholder(
+ app: Flask,
+) -> None:
+ table = _mapped_table(transform="unix_timestamp(event_time)")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_for_a_non_deterministic_transform(app: Flask) -> None:
+ """
+ The query-time gate is `is_transform_active`, the same one the Explore
+ indicator reads. Anything narrower would let a transform that reached
+ storage without passing `UpdateDatasetCommand` -- through import, or a
+ hand-written bundle -- mirror a filter with a value frozen at probe time,
+ while the editor reported the mapping as inactive and nothing on screen
+ said otherwise.
+ """
+ table = _mapped_table(transform="unix_timestamp(:value) + rand()")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_for_a_multi_expression_transform(app: Flask) -> None:
+ """A select list is not an expression; the probe cannot align its columns."""
+ table = _mapped_table(transform="lower(:value), 'x'")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_for_an_unparseable_transform(app: Flask) -> None:
+ table = _mapped_table(transform="unix_timestamp(:value")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_the_mapped_column_has_an_advanced_data_type(
+ app: Flask,
+) -> None:
+ """
+ ``translate_filter`` builds its own predicate shape from *translated* values,
+ so the ``(operator, value)`` pair the operator matrix reasons about does not
+ exist. Mirroring anyway would silently apply the wrong values (§4.1).
+ """
+ table = _mapped_table()
+ for column in table.columns:
+ if column.column_name == "event_time":
+ column.advanced_data_type = "port"
+
+ with app.app_context():
+ with patch.dict(app.config["ADVANCED_DATA_TYPES"], {"port": MagicMock()}):
+ with patch(
+ "superset.connectors.sqla.partition_mapping.feature_flag_manager."
+ "is_feature_enabled",
+ side_effect=lambda flag: (
+ flag in {"PARTITION_FILTER_MAPPING", "ENABLE_ADVANCED_DATA_TYPES"}
+ ),
+ ):
+ assert resolve_partition_mapping(table) is None
+
+
+def test_advanced_data_type_does_not_block_when_the_flag_is_off(app: Flask) -> None:
+ """An inert ``advanced_data_type`` is not a reason to skip mirroring."""
+ table = _mapped_table()
+ for column in table.columns:
+ if column.column_name == "event_time":
+ column.advanced_data_type = "port"
+
+ with app.app_context():
+ with patch(
+ "superset.connectors.sqla.partition_mapping.feature_flag_manager."
+ "is_feature_enabled",
+ side_effect=lambda flag: flag == "PARTITION_FILTER_MAPPING",
+ ):
+ assert resolve_partition_mapping(table) is not None
+
+
+# ---------------------------------------------------------------------------
+# §5 — transform inspection helpers
+# ---------------------------------------------------------------------------
+
+
+@pytest.mark.parametrize(
+ "transform,expected",
+ [
+ ("unix_timestamp(:value)", True),
+ ("lower(:value)", True),
+ ("CAST(:value AS BIGINT)", True),
+ ("unix_timestamp(event_time)", False),
+ (":values", False),
+ ("", False),
+ (None, False),
+ ],
+)
+def test_contains_value_placeholder(transform: str | None, expected: bool) -> None:
+ assert contains_value_placeholder(transform) is expected
+
+
+@pytest.mark.parametrize(
+ "transform,expected",
+ [
+ ("unix_timestamp(:value)", False),
+ ("{{ current_username() }}", True),
+ ("lower({% if x %}:value{% endif %})", True),
+ ("lower(:value) -- {# comment #}", True),
+ ],
+)
+def test_contains_jinja(transform: str, expected: bool) -> None:
+ assert contains_jinja(transform) is expected
+
+
+def test_contains_jinja_answers_as_the_block_pattern_does() -> None:
+ """
+ The scan has to agree with the lazy, ``DOTALL`` pattern it stands in for
+ on every input, including overlapping and unclosed delimiters, so that no
+ stored transform changes verdict. Every string of up to seven characters
+ over the delimiter characters, a newline and a filler is checked.
+ """
+ import itertools
+ import re
+
+ pattern = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+ for length in range(8):
+ for chars in itertools.product("{}%#\na", repeat=length):
+ text = "".join(chars)
+ assert contains_jinja(text) is (pattern.search(text) is not None), text
+
+
+@pytest.mark.parametrize("opening", ["{{", "{%", "{#"])
+def test_contains_jinja_is_linear_in_a_run_of_opening_delimiters(
+ opening: str,
+) -> None:
+ """
+ A run of opening delimiters with no closing one made the lazy pattern retry
+ from every position, which is quadratic. Stored transforms are not
+ length-bounded here, so a long run has to stay cheap.
+ """
+ import time
+
+ started = time.monotonic()
+ assert contains_jinja(opening * 200_000) is False
+ assert time.monotonic() - started < 1
+
+
+@pytest.mark.parametrize(
+ ("transform", "expected"),
+ [
+ ("lower(:value)", False),
+ ("lower(:value) /* an ordinary comment */", False),
+ ("lower(:value) -- a line comment", False),
+ (":value /*!50000 + 1 */", True),
+ (":value /*M!50000 + 1 */", True),
+ (":value /*! + 1 */", True),
+ ("", False),
+ (None, False),
+ ],
+)
+def test_contains_executable_comment(transform: str | None, expected: bool) -> None:
+ assert contains_executable_comment(transform) is expected
+
+
+@pytest.mark.parametrize(
+ "transform",
+ [
+ "unix_timestamp(:value)",
+ "lower(:value)",
+ "CAST(:value AS BIGINT)",
+ "date_format(:value, 'yyyyMMdd')",
+ ],
+)
+def test_pure_transforms_report_no_non_deterministic_functions(
+ transform: str,
+) -> None:
+ assert find_non_deterministic_functions(transform, "hive") == set()
+
+
+@pytest.mark.parametrize(
+ "transform,expected_name",
+ [
+ ("date_diff(:value, now())", "NOW"),
+ ("CAST(:value AS BIGINT) + rand()", "RAND"),
+ ("CAST(:value AS DATE) - current_date", "CURRENT_DATE"),
+ ],
+)
+def test_non_deterministic_functions_are_reported(
+ transform: str, expected_name: str
+) -> None:
+ """
+ The probe runs at a different moment and in a different session from the
+ chart query, and its result is cached, so anything time- or
+ randomness-dependent freezes a snapshot of probe time into the predicate.
+ """
+ assert expected_name in find_non_deterministic_functions(transform, "hive")
+
+
+@pytest.mark.parametrize(
+ ("engine", "transform", "expected_name"),
+ [
+ # `now()` is statement-stable on PostgreSQL; these two are not even
+ # that, and the ANSI four did not name them.
+ ("postgresql", "age(clock_timestamp(), :value)", "CLOCK_TIMESTAMP"),
+ ("postgresql", "age(statement_timestamp(), :value)", "STATEMENT_TIMESTAMP"),
+ # Every engine spells "now" its own way, and the gate matches by name.
+ ("mysql", "datediff(sysdate(), :value)", "SYSDATE"),
+ ("mysql", "datediff(curdate(), :value)", "CURDATE"),
+ ("oracle", "datediff(day, :value, LOCALTIMESTAMP)", "LOCALTIMESTAMP"),
+ ("oracle", "SYSTIMESTAMP - :value", "SYSTIMESTAMP"),
+ ("mssql", "DATEDIFF(day, :value, GETDATE())", "GETDATE"),
+ ("mssql", "DATEDIFF(day, :value, SYSUTCDATETIME())", "SYSUTCDATETIME"),
+ ("clickhouse", "now64() - :value", "NOW64"),
+ ("bigquery", "DATE_DIFF(CURRENT_DATETIME(), :value, DAY)", "CURRENT_DATETIME"),
+ ],
+)
+def test_every_engine_s_spelling_of_now_is_reported(
+ engine: str, transform: str, expected_name: str
+) -> None:
+ """
+ The list is matched by SQL function name, so a spelling it does not carry
+ passes the gate. A relative partition key such as
+ `datediff(day, :value, LOCALTIMESTAMP)` is then probed once, cached, and
+ keeps emitting yesterday's partition value after midnight -- so the chart
+ silently drops rows.
+ """
+ assert expected_name in find_non_deterministic_functions(transform, engine)
+
+
+@pytest.mark.parametrize(
+ ("engine", "transform", "expected_name"),
+ [
+ # MySQL takes these with no parentheses at all...
+ ("mysql", "datediff(UTC_DATE, :value)", "UTC_DATE"),
+ ("mysql", "datediff(utc_timestamp, :value)", "UTC_TIMESTAMP"),
+ ("mysql", "datediff(CURRENT_DATE, :value)", "CURRENT_DATE"),
+ # ...as do Oracle and PostgreSQL for their own spellings.
+ # sqlglot normalizes Oracle's bare `SYSDATE` to `CURRENT_TIMESTAMP`,
+ # so it is caught as a function under that name -- which is a pass:
+ # what matters is that the gate reports it, not what it is called.
+ ("oracle", ":value - SYSDATE", "CURRENT_TIMESTAMP"),
+ ("oracle", ":value - SYSTIMESTAMP", "SYSTIMESTAMP"),
+ ("postgresql", "age(LOCALTIMESTAMP, :value)", "LOCALTIMESTAMP"),
+ ],
+)
+def test_a_bare_wall_clock_keyword_is_reported(
+ engine: str, transform: str, expected_name: str
+) -> None:
+ """
+ Written without parentheses these parse as *column references*, so the
+ function-name walk could not see them and probe time was frozen into a
+ cached mirror.
+ """
+ assert expected_name in find_non_deterministic_functions(transform, engine)
+
+
+def test_the_bare_list_stays_to_names_that_need_no_parentheses() -> None:
+ """
+ Refusing a bare name costs an owner a column genuinely called that, so the
+ list is only the datetime keywords SQL lets you write without `()`.
+ `rand`, `uuid` and `newid` always need them, and are plausible column
+ names.
+ """
+ assert BARE_WALL_CLOCK_KEYWORDS <= {
+ name.lower() for name in NON_DETERMINISTIC_FUNCTIONS
+ }
+ assert not BARE_WALL_CLOCK_KEYWORDS & {"rand", "random", "uuid", "newid"}
+ # A column by one of those names is still an ordinary column.
+ assert find_non_deterministic_functions("lower(:value) || uuid", "postgresql") == (
+ set()
+ )
+
+
+@pytest.mark.parametrize(
+ ("engine", "transform"),
+ [
+ # The canonical transforms, which must not be swept up by the names
+ # added above.
+ ("hive", "unix_timestamp(:value)"),
+ ("postgresql", "to_char(:value, 'YYYYMMDD')"),
+ ("postgresql", "extract(epoch from :value)"),
+ ("mysql", "date_format(:value, '%Y%m%d')"),
+ ("oracle", "trunc(:value)"),
+ ("mssql", "CONVERT(date, :value)"),
+ ],
+)
+def test_the_canonical_transforms_are_still_pure(engine: str, transform: str) -> None:
+ """The list grew; this is the half that says it did not grow into the
+ transforms this feature exists for."""
+ assert find_non_deterministic_functions(transform, engine) == set()
+
+
+def test_niladic_unix_timestamp_is_rejected_but_the_unary_form_is_not() -> None:
+ """
+ On Hive/Impala ``unix_timestamp()`` means "now" while ``unix_timestamp(x)``
+ -- the canonical temporal transform -- is pure. The distinction is the whole
+ reason this check inspects arity rather than just the name.
+ """
+ assert find_non_deterministic_functions("unix_timestamp(:value)", "hive") == set()
+ assert find_non_deterministic_functions(
+ "unix_timestamp(:value) - unix_timestamp()", "hive"
+ )
+
+
+# ---------------------------------------------------------------------------
+# §4.2 — probe evaluation
+# ---------------------------------------------------------------------------
+
+
+def _user(username: str) -> Any:
+ """A stand-in for `override_user`, which only needs `.username` here."""
+ user = MagicMock()
+ user.username = username
+ user.is_anonymous = False
+ return user
+
+
+def _database_returning(values: list[Any]) -> Database:
+ """A real ``Database`` (so the dialect is real) with only ``get_df`` stubbed."""
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ return_value=pd.DataFrame(
+ [values], columns=[f"v{i}" for i in range(len(values))]
+ )
+ )
+ return database
+
+
+def _database_returning_frame(frame: pd.DataFrame) -> Database:
+ """
+ ``_database_returning`` for a probe result whose column dtypes matter.
+
+ The flat-list sibling builds its frame from one Python list, so pandas
+ infers a single dtype and the row-versus-cell distinction cannot be seen.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ return_value=frame
+ )
+ return database
+
+
+def _probe(database: Database) -> MagicMock:
+ """
+ The stubbed ``get_df``, typed for call assertions.
+
+ ``Database.get_df`` is a real method, so mypy reads its declared signature
+ rather than the mock that replaced it and rejects ``.call_args`` and
+ friends.
+ """
+ return cast(MagicMock, database.get_df)
+
+
+def test_evaluate_transform_returns_one_value_per_input(app: Flask) -> None:
+ database = _database_returning([1767225600, 1769904000])
+
+ with app.app_context():
+ result = evaluate_transform(
+ database,
+ None,
+ "default",
+ "unix_timestamp(:value)",
+ ["2026-01-01 00:00:00", "2026-02-01 00:00:00"],
+ )
+
+ assert result == [1767225600, 1769904000]
+ _probe(database).assert_called_once()
+
+
+def test_evaluate_transform_binds_values_rather_than_interpolating(
+ app: Flask,
+) -> None:
+ """
+ Filter values are attacker-controlled (a Gamma user picks them), so they must
+ be bound and escaped, never pasted into the probe SQL.
+ """
+ database = _database_returning(["o''brien"])
+
+ with app.app_context():
+ evaluate_transform(database, None, None, "lower(:value)", ["O'Brien"])
+
+ sql = _probe(database).call_args.kwargs["sql"]
+ assert "O'Brien" not in sql
+ assert "O''Brien" in sql
+
+
+@pytest.mark.parametrize(
+ ("transform", "expected"),
+ [
+ ("lower(:value)", True),
+ ("CAST(:value AS BIGINT)", True),
+ ("date_format(:value, '%Y%m%d')", True),
+ # The cast shorthand: a trailing colon stops SQLAlchemy's bind scan.
+ (":value::bigint", False),
+ ("(:value::date)::text", False),
+ ],
+)
+def test_a_postgres_cast_shorthand_is_not_bindable(
+ transform: str, expected: bool
+) -> None:
+ """
+ `VALUE_PLACEHOLDER_RE` is `:value\b`, which matches inside `:value::bigint`.
+ SQLAlchemy's own scan ends with `(?![:\\w$])`, so the following colon stops
+ it: `text(":value::bigint")` reports a parameter named `valu`, and asking it
+ to bind `value` raises.
+
+ Pinned because the two regexes disagreeing is the whole bug: every
+ write-side gate accepted the transform and the probe then died on an
+ `ArgumentError` that `_probe` swallows.
+ """
+ assert _placeholder_is_bindable(transform) is expected
+
+
+def test_a_cast_shorthand_transform_still_probes(app: Flask) -> None:
+ """
+ The transform is valid SQL, passes every gate, and used to prune nothing:
+ `build_probe_sql` raised, `_probe` swallowed it, and the only symptom was a
+ mapping that silently never mirrored -- with the preview reporting an engine
+ failure for SQL that was never sent.
+ """
+ database = _database_returning([20260115])
+
+ with app.app_context():
+ result = evaluate_transform(
+ database, None, None, ":value::bigint", ["20260115"]
+ )
+
+ assert result == [20260115]
+ assert _probe(database).call_count == 1
+ assert "::bigint" in _probe(database).call_args.kwargs["sql"]
+
+
+def test_a_cast_shorthand_value_is_still_escaped_by_the_dialect(
+ app: Flask,
+) -> None:
+ """
+ The fallback substitutes where the bind path binds, so it has to earn the
+ same guarantee its sibling above pins: the value is rendered by the
+ dialect's literal processor, not pasted in.
+
+ Binding was only ever the vehicle for reaching that processor --
+ `_compile_literal` inlines the result either way -- so this renders first
+ and substitutes second. Same string, different order.
+
+ Rendering is necessary and not sufficient: whether the engine reads the
+ rendered text back as this value is a separate question, and the one
+ `literal_round_trips` answers. SQLite's engine honours the doubling its
+ driver emits, which is why this value is probed here at all.
+ """
+ database = _database_returning(["x"])
+
+ with app.app_context():
+ evaluate_transform(database, None, None, ":value::text", ["O'Brien"])
+
+ sql = _probe(database).call_args.kwargs["sql"]
+ assert "O'Brien" not in sql
+ assert "O''Brien" in sql
+
+
+def test_evaluate_transform_dedupes_repeated_values(app: Flask) -> None:
+ """Three inputs, two distinct: the probe evaluates the transform twice."""
+ database = _database_returning(["us", "us"])
+
+ with app.app_context():
+ result = evaluate_transform(
+ database, None, None, "lower(:value)", ["US", "US", "us"]
+ )
+
+ assert result == ["us", "us", "us"]
+ sql = _probe(database).call_args.kwargs["sql"]
+ assert sql.count("lower") == 2
+
+
+def test_evaluate_transform_fails_open_on_a_short_result_row(app: Flask) -> None:
+ """A row narrower than the probe asked for means the results cannot be
+ aligned back to their inputs; pruning is skipped rather than guessed at."""
+ database = _database_returning(["us"])
+
+ with app.app_context():
+ assert (
+ evaluate_transform(database, None, None, "lower(:value)", ["US", "CA"])
+ is None
+ )
+
+
+def test_evaluate_transform_fails_open_on_a_wide_result_row(app: Flask) -> None:
+ """
+ Too many columns is the dangerous direction. A transform whose select list
+ holds two expressions returns 2N columns for N inputs, and reading the first
+ N interleaves the expressions instead of taking one per value -- a predicate
+ built from the wrong values rather than one that is merely short. A frame of
+ `('us', 'x', 'ca', 'x')` read as the first two columns would have yielded
+ `('us', 'x')` and dropped every CA row.
+
+ The transform is a perfectly ordinary `lower(:value)` and the width comes
+ from the stubbed frame, which is the only way to reach the guard: a
+ transform that really does carry two expressions -- `lower(:value), 'x'` --
+ is refused by `stored_expression_error` for not being a single expression,
+ so `get_df` is never called and `None` comes back for an unrelated reason.
+ Asserting the probe *ran* is what separates the two, and it is what makes
+ relaxing the guard from `!=` to `<` fail here rather than pass: four columns
+ for two inputs is not fewer than two.
+ """
+ database = _database_returning(["us", "x", "ca", "x"])
+
+ with app.app_context():
+ assert (
+ evaluate_transform(database, None, None, "lower(:value)", ["US", "CA"])
+ is None
+ )
+
+ assert _probe(database).call_count == 1
+
+
+def test_the_probe_select_carries_the_engine_s_from_clause(app: Flask) -> None:
+ """
+ A `SELECT` with no `FROM` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from. Without this every probe on those engines
+ raises, which `evaluate_transform` swallows -- so the only symptom is a
+ correctly configured mapping that silently never prunes.
+ """
+ assert build_probe_sql("lower(:value)", ["US"]) == "SELECT lower('US') AS v0"
+ assert build_probe_sql("lower(:value)", ["US"], None, " FROM DUAL").endswith(
+ " FROM DUAL"
+ )
+ assert OracleEngineSpec.select_without_from_suffix == " FROM DUAL"
+ assert BaseEngineSpec.select_without_from_suffix == ""
+
+
+@pytest.mark.parametrize(
+ ("module", "spec_name", "suffix"),
+ [
+ ("oracle", "OracleEngineSpec", " FROM DUAL"),
+ ("db2", "Db2EngineSpec", " FROM SYSIBM.SYSDUMMY1"),
+ ],
+)
+def test_the_probe_reads_the_from_suffix_off_the_engine_spec(
+ app: Flask, mocker: MockerFixture, module: str, spec_name: str, suffix: str
+) -> None:
+ """
+ The sibling above hands `build_probe_sql` a suffix directly, so it never
+ exercises the step that reads `select_without_from_suffix` off the engine
+ spec and forwards it. Drop that forwarding and the sibling stays green
+ while Oracle and Db2 stop pruning entirely -- a bare `SELECT ...` raises
+ there, `evaluate_transform` swallows it, and the only symptom is a
+ correctly configured mapping that silently never prunes.
+
+ So this drives the real entry point and asserts on the SQL the engine is
+ handed, plus that the result is accepted.
+ """
+ spec = getattr(import_module(f"superset.db_engine_specs.{module}"), spec_name)
+ database = _database_returning(["us"])
+ mocker.patch.object(
+ type(database), "db_engine_spec", PropertyMock(return_value=spec)
+ )
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, "lower(:value)", ["US"]) == [
+ "us"
+ ]
+
+ sql = _probe(database).call_args.kwargs["sql"]
+ assert sql.endswith(suffix)
+ # And the gate that re-parses the compiled probe accepts that shape, rather
+ # than the suffix being appended only to be refused downstream.
+ assert probe_sql_is_evaluable(sql, spec.engine, 1, suffix) is True
+
+
+@pytest.mark.parametrize(
+ ("transform", "expected"),
+ [
+ (":value || ':suffix'", "SELECT 'us' || ':suffix' AS v0"),
+ ("concat(:value, ':x')", "SELECT concat('us', ':x') AS v0"),
+ ("replace(:value, ':a', ':b')", "SELECT replace('us', ':a', ':b') AS v0"),
+ # The separator shape, which is the ordinary reason to write one.
+ ("concat(:value, ':', 'x')", "SELECT concat('us', ':', 'x') AS v0"),
+ # A time format carries two.
+ (
+ "to_char(:value, 'HH24:MI:SS')",
+ "SELECT to_char('us', 'HH24:MI:SS') AS v0",
+ ),
+ # And the placeholder itself still binds.
+ ("lower(:value)", "SELECT lower('us') AS v0"),
+ ],
+)
+def test_a_colon_in_a_literal_is_not_read_as_a_bind(
+ transform: str, expected: str
+) -> None:
+ """
+ `text()` reads any `:word` as a bind parameter, including inside a string
+ literal, and an unbound one renders as `NULL` under literal binds rather
+ than raising. So `:value || ':suffix'` compiled to `'us' || 'NULL'`: the
+ mirror asked for a partition value no row holds and the chart dropped
+ rows, with no error for `_probe` to swallow.
+ """
+ assert build_probe_sql(transform, ["us"]) == expected
+
+
+def test_a_colon_literal_survives_the_unbindable_path_too() -> None:
+ """
+ The other branch substitutes textually through `parse_skeleton` and never
+ hands the transform to `text()`, so it was never affected -- pinned so the
+ escaping added for the bound path cannot leak into it as a stray backslash.
+ """
+ assert build_probe_sql(":value::bigint", [7]) == "SELECT 7::bigint AS v0"
+
+
+@pytest.mark.parametrize("dialect", [mysql.dialect(), postgresql.dialect()])
+def test_the_probe_select_does_not_double_percent_signs(dialect: Any) -> None:
+ """
+ `TextClause` compilation runs the dialect's `post_process_text`, which
+ doubles every `%` on any paramstyle whose DBAPI later interpolates
+ parameters -- MySQL and Postgres, and every spec inheriting from them. The
+ probe has no such interpolation pass: it executes with no bound parameters
+ at all. Left doubled, `date_format(:value, '%Y%m%d')` asks the warehouse
+ for the literal string `%%Y%%m%%d`, so the probe returns that instead of a
+ date and the mirrored predicate drops every row the filter keeps.
+ """
+ sql = build_probe_sql("date_format(:value, '%Y%m%d')", ["2026-01-15"], dialect)
+
+ assert "'%Y%m%d'" in sql
+ assert "%%" not in sql
+
+
+def test_the_probe_select_is_unchanged_on_a_dialect_that_does_not_double() -> None:
+ """
+ Pins the no-dialect path, which is also the blind spot: the default dialect
+ does not double percent signs, so no assertion made through it can see the
+ bug the two cases above cover.
+ """
+ assert (
+ build_probe_sql("date_format(:value, '%Y%m%d')", ["2026-01-15"])
+ == "SELECT date_format('2026-01-15', '%Y%m%d') AS v0"
+ )
+
+
+def test_a_raw_probe_value_is_substituted_literally() -> None:
+ r"""
+ `RawProbeValue.sql` is rendered from a filter value, so it reaches
+ `parse_skeleton` as the *replacement* for `:value`. Read as a replacement
+ template, a backslash in it is an escape: `array('a\nb')` -- which is how a
+ dialect renders the two characters `\` and `n` -- would become a real
+ newline, so the engine is asked about a different array than the predicate
+ compares and the mirror can exclude rows the filter keeps.
+ """
+ sql = build_probe_sql("toYYYYMM(:value)", [RawProbeValue(r"array('a\nb')")])
+
+ assert sql == r"SELECT toYYYYMM(array('a\nb')) AS v0"
+
+
+def test_a_raw_probe_value_does_not_re_inject_the_placeholder() -> None:
+ r"""
+ `\g<0>` in a replacement template expands to the whole match, which would
+ put `:value` back into the probe -- an unbound parameter the engine refuses.
+ """
+ sql = build_probe_sql("toYYYYMM(:value)", [RawProbeValue(r"'a\g<0>b'")])
+
+ assert sql == r"SELECT toYYYYMM('a\g<0>b') AS v0"
+ assert ":value" not in sql
+
+
+def test_a_raw_probe_value_with_a_group_reference_does_not_raise() -> None:
+ r"""
+ `\1` is an invalid group reference for this pattern, so as a replacement
+ template it raised `re.PatternError` rather than probing anything.
+ """
+ sql = build_probe_sql("toYYYYMM(:value)", [RawProbeValue(r"'a\1b'")])
+
+ assert sql == r"SELECT toYYYYMM('a\1b') AS v0"
+
+
+def test_a_probed_literal_keeps_its_percent_sign(app: Flask) -> None:
+ """
+ The preview panel renders probed values through the same dialect, so a
+ value that merely contains a `%` would be shown doubled.
+ """
+ database = Database(database_name="pct_db", sqlalchemy_uri="postgresql://h/d")
+
+ with app.app_context():
+ assert _render_literal(database, "100%") == "'100%'"
+
+
+def test_the_probe_reads_each_cell_without_row_wide_dtype_coercion(
+ app: Flask,
+) -> None:
+ """
+ A row is a Series, so it carries one dtype across every probe column: a row
+ mixing an exact int64 with a float unifies to float64 and an integer
+ partition key above 2^53 comes back rounded. The mirror then asks for a key
+ the warehouse does not hold, and the row the filter matched is dropped.
+ """
+ database = _database_returning_frame(
+ pd.DataFrame({"v0": [9007199254740993], "v1": [1.5]})
+ )
+
+ with app.app_context():
+ probed = evaluate_transform(
+ database, None, None, "CAST(:value AS NUMERIC)", ["9007199254740993", "1.5"]
+ )
+
+ assert probed == [9007199254740993, 1.5]
+
+
+def test_evaluate_transform_pins_catalog_and_schema(app: Flask) -> None:
+ """
+ The probe runs in a different session from the chart query; pinning the
+ catalog and schema keeps session settings as close as the pool allows.
+ """
+ database = _database_returning([1])
+
+ with app.app_context():
+ evaluate_transform(database, "prod", "analytics", "lower(:value)", ["x"])
+
+ kwargs = _probe(database).call_args.kwargs
+ assert kwargs["catalog"] == "prod"
+ assert kwargs["schema"] == "analytics"
+
+
+def test_evaluate_transform_fails_open_when_the_probe_raises(app: Flask) -> None:
+ """A wedged engine must not break the chart — it just stops pruning."""
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ side_effect=RuntimeError("connection reset")
+ )
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, "lower(:value)", ["x"]) is None
+
+
+def test_evaluate_transform_fails_open_on_an_empty_result(app: Flask) -> None:
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ return_value=pd.DataFrame()
+ )
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, "lower(:value)", ["x"]) is None
+
+
+def test_evaluate_transform_returns_none_for_no_values(app: Flask) -> None:
+ database = _database_returning([])
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, "lower(:value)", []) is None
+
+ _probe(database).assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "transform",
+ [
+ "(SELECT password FROM ab_user LIMIT 1) || :value",
+ "lower(:value) UNION ALL SELECT password FROM ab_user",
+ "lower(:value); DROP TABLE ab_user",
+ "password || :value FROM ab_user",
+ "lower(:value) FROM ab_user WHERE 1 = 1",
+ ],
+ ids=[
+ "subquery",
+ "set-operation",
+ "multi-statement",
+ "bare-from",
+ "from-and-where",
+ ],
+)
+def test_a_transform_that_is_not_a_storable_expression_never_runs(
+ app: Flask, transform: str
+) -> None:
+ """
+ The probe is where a transform stops being text and becomes SQL.
+
+ `build_probe_sql` binds `:value` and splices the rest in verbatim, so a
+ transform that was never a single harmless expression is arbitrary SQL
+ against the dataset's database -- read back out of the emitted predicate
+ by anyone who can open "View query". The write-side gates refuse these,
+ but they can only speak for rows written after they existed, so the last
+ word belongs here.
+ """
+ database = _database_returning(["irrelevant"])
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, transform, ["us"]) is None
+
+ _probe(database).assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "transform, unfinished",
+ [
+ ("unix_timestamp(:value", True),
+ ("unix_timestamp(:value))", True),
+ ("unix_timestamp(:value) +", True),
+ ("unix_timestamp(:value)", False),
+ ("unix_timestamp(:value); DROP TABLE ab_user", False),
+ ("unix_timestamp(:value) UNION ALL SELECT password FROM ab_user", False),
+ ("password || :value FROM ab_user", False),
+ ],
+)
+def test_is_unfinished_separates_not_sql_yet_from_the_wrong_sql(
+ transform: str, unfinished: bool
+) -> None:
+ """
+ The two deserve opposite treatment -- a half-typed transform is stored and
+ parked inactive, the wrong SQL is refused -- and neither `is_parseable` nor
+ parsing as a single statement tells them apart, because the multi-statement
+ form fails both exactly as unfinished text does. Parsing as a script does.
+ """
+ assert is_unfinished(transform, "hive") is unfinished
+
+
+def test_a_transform_smuggling_its_own_from_clause_is_refused(app: Flask) -> None:
+ """
+ The hole this gate was added for.
+
+ `is_parseable` counts only the projection, so `password || :value FROM
+ ab_user` reads as a single select expression and passed every write-side
+ gate -- including with `ALLOW_ADHOC_SUBQUERY` off, since a top-level FROM
+ is not a sub-query. `build_probe_sql` then emitted `SELECT password || 'us'
+ AS v0 FROM ab_user`, where its own alias is read as a table alias on the
+ FROM clause the transform brought with it: valid SQL, one row, and the
+ secret handed back through the predicate the preview panel renders.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ transform = "password || :value FROM ab_user"
+
+ assert is_parseable(transform, "sqlite") is True
+ assert is_bare_expression(transform, "sqlite") is False
+
+ with app.app_context():
+ reason = stored_expression_error(database, None, None, transform)
+ assert reason is not None
+
+ blocking = _blocking(validate_transform(transform, "sqlite"))
+ assert len(blocking) == 1
+ assert "single SQL expression" in str(blocking[0].message)
+ assert is_transform_active(transform, "sqlite") is False
+
+
+def test_a_subquery_transform_is_refused_even_with_adhoc_subquery_enabled(
+ app: Flask,
+) -> None:
+ """
+ `validate_adhoc_subquery` admits a sub-query under `ALLOW_ADHOC_SUBQUERY`
+ and returns RLS-rewritten SQL -- which this path has no way to propagate,
+ because `build_probe_sql` splices the original transform text. So the probe
+ ran a sub-query with no row-level-security predicates at all and reported
+ the hidden row in `emitted_predicate`. A transform is a scalar function of
+ `:value`, so refusing the sub-query outright is both correct and what makes
+ the missing RLS rewrite moot.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ transform = "(SELECT secret FROM vault LIMIT 1) || :value"
+
+ with app.app_context():
+ app.config["DEFAULT_FEATURE_FLAGS"]["ALLOW_ADHOC_SUBQUERY"] = True
+ try:
+ reason = stored_expression_error(database, None, None, transform)
+ finally:
+ del app.config["DEFAULT_FEATURE_FLAGS"]["ALLOW_ADHOC_SUBQUERY"]
+
+ assert reason is not None
+ assert "sub-query" in reason
+
+
+@pytest.mark.parametrize(
+ "comment",
+ ["/*!50000 + (SELECT secret FROM vault LIMIT 1) */", "/*M!50000 + 1 */"],
+)
+def test_an_executable_comment_is_refused_by_every_gate(
+ app: Flask, comment: str
+) -> None:
+ """
+ The one construct that made the shape gates describe a statement the engine
+ would not run.
+
+ sqlglot reads a MySQL executable comment as comment data: the pinned parse
+ below reports no sub-query and no clause, so `stored_expression_error` and
+ `probe_sql_is_evaluable` both passed it, while MySQL and MariaDB execute
+ what is inside. An owner with dataset write and no SQL Lab could put one in
+ a transform, call the preview and read a table back out of
+ `emitted_predicate`, with no RLS on the hidden query.
+
+ Refused on every engine, not only the two that honour it -- hence SQLite
+ here. There is no legitimate transform carrying one, and a per-engine gate
+ would store on Postgres what detonates after the dataset is re-pointed.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ transform = f"(:value {comment})"
+
+ # The premise: no parse-tree gate can see it.
+ statement = SQLStatement(f"SELECT (1 {comment}) AS v0", "mysql")
+ assert statement.has_subquery() is False
+ assert statement.get_clause_names() == set()
+
+ with app.app_context():
+ assert stored_expression_error(database, None, None, transform) is not None
+
+ blocking = [
+ issue for issue in validate_transform(transform, "mysql") if issue.blocking
+ ]
+ assert len(blocking) == 1
+ assert "executable comment" in str(blocking[0].message)
+
+
+def test_an_executable_comment_stops_the_probe_before_the_engine(app: Flask) -> None:
+ """
+ The gate above is the save path. This is the row an earlier release stored:
+ `_probe` consults `stored_expression_error` on every call, so a transform
+ already in the metadata database never reaches `get_df`.
+ """
+ database = _database_returning(["x"])
+ transform = "(:value /*!50000 + (SELECT secret FROM vault LIMIT 1) */)"
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, transform, ["US"]) is None
+
+ assert _probe(database).call_count == 0
+
+
+def test_a_unicode_escaped_identifier_is_refused_by_every_gate(app: Flask) -> None:
+ """
+ The second construct that made the gates reason about a name the engine
+ does not use. sqlglot reports `U&"\\0071uery_to_xml"` as an anonymous
+ function literally called `\\0071uery_to_xml`, so the function denylist --
+ which matches on the reported name -- never sees `query_to_xml`, while
+ PostgreSQL decodes the escape and runs it. An owner with dataset write and
+ no SQL Lab could read rows outside their RLS scope back out of
+ `emitted_predicate`.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="postgresql://u@h/d")
+ transform = "CAST(U&\"\\0071uery_to_xml\"(:value, false, true, '') AS TEXT)"
+
+ # The premise: the denylist is matching the wrong name.
+ statement = SQLStatement(
+ "SELECT CAST(U&\"\\0071uery_to_xml\"('x', false, true, '') AS TEXT) AS v0",
+ "postgresql",
+ )
+ assert statement.get_disallowed_functions({"query_to_xml"}) == set()
+
+ with app.app_context():
+ assert stored_expression_error(database, None, None, transform) is not None
+
+ blocking = [
+ issue for issue in validate_transform(transform, "postgresql") if issue.blocking
+ ]
+ assert len(blocking) == 1
+ assert "escape sequence" in str(blocking[0].message)
+
+
+def test_a_unicode_escaped_identifier_stops_the_probe_before_the_engine(
+ app: Flask,
+) -> None:
+ """The row an earlier release stored, as for the executable comment."""
+ database = _database_returning(["x"])
+ transform = "U&\"\\0071uery_to_xml\"(:value, false, true, '') || ''"
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, transform, ["US"]) is None
+
+ assert _probe(database).call_count == 0
+
+
+def test_an_ordinary_quoted_identifier_is_still_allowed(app: Flask) -> None:
+ """
+ Only the escape prefix is refused. A plainly quoted identifier names what
+ it says, so the denylist sees the real name and rejecting it would cost an
+ owner a transform that works.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="postgresql://u@h/d")
+
+ with app.app_context():
+ assert (
+ stored_expression_error(database, None, None, 'lower("Mixed Case")') is None
+ )
+
+
+def test_the_escape_gate_reads_raw_text_and_says_so(app: Flask) -> None:
+ """
+ The prefix is refused wherever it appears, including inside a string
+ literal -- the same trade the executable-comment gate makes, and for the
+ same reason: a gate whose whole job is to fire before the parse cannot ask
+ the parse whether the text is quoted. `concat(:value, 'u&"x"')` is refused,
+ which costs an owner nothing anyone writes.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="postgresql://u@h/d")
+
+ with app.app_context():
+ assert (
+ stored_expression_error(database, None, None, "concat(:value, 'u&\"x\"')")
+ is not None
+ )
+
+
+def test_a_plain_comment_is_still_allowed_through_the_shape_gates(
+ app: Flask,
+) -> None:
+ """
+ Only the executable form is refused. An ordinary comment is inert on every
+ engine, so rejecting it would cost an owner a transform that works -- and
+ the placeholder gate already covers the case that matters, a `:value` the
+ comment swallows.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+
+ with app.app_context():
+ assert (
+ stored_expression_error(database, None, None, "lower(:value) /* ok */")
+ is None
+ )
+
+
+def test_a_transform_calling_a_disallowed_function_is_refused(app: Flask) -> None:
+ """
+ The probe executes the transform, so the operator's function denylist has
+ to apply to it for the same reason it applies in SQL Lab.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ transform = "version() || :value"
+
+ with app.app_context():
+ original = app.config["DISALLOWED_SQL_FUNCTIONS"]
+ try:
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = {"sqlite": {"version"}}
+ reason = stored_expression_error(database, None, None, transform)
+ assert reason is not None
+ assert "version" in reason
+
+ # Named, rather than echoing the operator's whole denylist back.
+ assert "current_user" not in reason
+
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = {}
+ assert stored_expression_error(database, None, None, transform) is None
+ finally:
+ # Restored: `app.config` is shared, and leaving it emptied silently
+ # disabled this gate for every test that ran afterwards.
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = original
+
+
+@pytest.mark.parametrize(
+ "function",
+ [
+ "database_to_xml",
+ "database_to_xmlschema",
+ "database_to_xml_and_xmlschema",
+ "schema_to_xml",
+ "schema_to_xmlschema",
+ "schema_to_xml_and_xmlschema",
+ "table_to_xml",
+ "table_to_xmlschema",
+ "table_to_xml_and_xmlschema",
+ "query_to_xml",
+ "query_to_xmlschema",
+ "query_to_xml_and_xmlschema",
+ ],
+)
+def test_the_whole_postgres_xml_family_is_denied_by_default(function: str) -> None:
+ """
+ These read tables with no FROM clause and no sub-query, so every gate that
+ reasons about table references is blind to them -- the denylist is the only
+ thing that can refuse them, and it has to name each shape. `schema_to_xml`
+ and three siblings were missing, so a bare scalar call cleared
+ `stored_expression_error` entirely and returned connection-user-readable
+ schema contents through preview.
+
+ Asserted against the shipped default rather than through the gate, because
+ the gap was an incomplete enumeration rather than broken wiring -- and
+ because `app.config` is ambient here, which the behavioural test below
+ handles by setting the denylist itself.
+ """
+ assert function in DISALLOWED_SQL_FUNCTIONS["postgresql"]
+
+
+def test_a_denied_read_capable_function_is_refused_despite_having_no_from(
+ app: Flask,
+) -> None:
+ """
+ The wiring half: a bare scalar call passes the length, single-statement,
+ bare-expression, sub-query and placeholder gates, so the denylist is what
+ has to stop it.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="postgresql://u@h/d")
+ transform = "schema_to_xml('public', true, false, '') || :value"
+
+ with app.app_context():
+ original = app.config["DISALLOWED_SQL_FUNCTIONS"]
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = {"postgresql": {"schema_to_xml"}}
+ try:
+ reason = stored_expression_error(database, None, None, transform)
+ finally:
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = original
+
+ assert reason is not None
+ assert "schema_to_xml" in reason
+
+
+@pytest.mark.parametrize("function", ["ts_rewrite", "ts_stat"])
+def test_the_postgres_full_text_query_functions_are_denied_by_default(
+ function: str,
+) -> None:
+ """
+ `ts_stat('select ...')` and `ts_rewrite(q, 'select ...')` run their *text*
+ argument as a query. The query is a string, so these have the same blind
+ spot the XML family above does: no FROM clause and no sub-query for a
+ table-reference gate to reason about, which leaves the denylist as the only
+ thing that can refuse them.
+ """
+ assert function in DISALLOWED_SQL_FUNCTIONS["postgresql"]
+
+
+@pytest.mark.parametrize(
+ "function",
+ [
+ "getxml",
+ "getxmltype",
+ "newcontext",
+ "newcontextfromhierarchy",
+ # No function argument to inspect at all: the table is named by the
+ # path string handed to the constructor.
+ "dburitype",
+ # The same reader reached through its factory, and the sibling URI
+ # types. Without a case each, deleting these three from `config.py`
+ # left the suite green and reopened the factory path.
+ "geturi",
+ "xdburitype",
+ "httpuritype",
+ ],
+)
+def test_the_oracle_query_running_xml_functions_are_denied_by_default(
+ function: str,
+) -> None:
+ """
+ `DBMS_XMLGEN.GETXML('select secret from vault')` runs its text argument as
+ a query -- the same blind spot as the PostgreSQL families above, on the
+ engine both reviewers named. Listed bare because the package prefix never
+ reaches the matcher: sqlglot parses the call as an anonymous function named
+ `GETXML`, and `get_disallowed_functions` compares against that name.
+ """
+ assert function in DISALLOWED_SQL_FUNCTIONS["oracle"]
+
+
+def test_a_package_qualified_denied_function_is_refused(app: Flask) -> None:
+ """
+ The wiring half for the bare-name listing above: the denylist entry has to
+ match a call written with its package prefix, which is the only way anyone
+ writes these.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="oracle://u@h/d")
+ transform = "DBMS_XMLGEN.GETXML('select secret from vault') || :value"
+
+ with app.app_context():
+ reason = stored_expression_error(database, None, None, transform)
+
+ assert reason is not None
+ assert "getxml" in reason
+
+
+def test_a_denied_query_running_text_function_is_refused(app: Flask) -> None:
+ """
+ The wiring half, and the only thing that proves the *name* matching works
+ for these two: neither is a function sqlglot models, so each reaches
+ `get_disallowed_functions` through its ANONYMOUS branch rather than as a
+ typed node. A denylist entry that only matched modelled functions would
+ pass the enumeration test above and still let these through.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="postgresql://u@h/d")
+ transform = "ts_stat('select 1') || :value"
+
+ with app.app_context():
+ original = app.config["DISALLOWED_SQL_FUNCTIONS"]
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = {"postgresql": {"ts_stat"}}
+ try:
+ reason = stored_expression_error(database, None, None, transform)
+ finally:
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = original
+
+ assert reason is not None
+ assert "ts_stat" in reason
+
+
+def test_the_function_denylist_is_keyed_on_the_engine_spec_name(
+ app: Flask, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """
+ Every other denylist gate in the codebase keys on the engine spec's own
+ name, which is also the name the config documentation tells an operator to
+ write, so this one does too -- a spec covering several SQLAlchemy backends
+ through `engine_aliases` reports the one canonical name under which its
+ entry exists.
+
+ Tested through an *aliased* engine, which is the only way to tell the two
+ names apart. On `sqlite://` the backend and the spec name are both
+ `"sqlite"`, so the assertion held whichever one the gate read, and the test
+ did not check what its name promises. `postgres://` is
+ `PostgresEngineSpec.engine_aliases`, so the URL's backend is `postgres`
+ while the spec -- and the config key an operator writes -- is `postgresql`.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="postgres://u@h/d")
+
+ with app.app_context():
+ # The premise, asserted rather than assumed: if this alias ever goes
+ # away, the test below stops discriminating and should say so here.
+ assert database.backend == "postgres"
+ assert database.db_engine_spec.engine == "postgresql"
+
+ # Denied only under the spec's name. Keyed on `database.backend` the
+ # gate would find no entry and let the call through.
+ #
+ # `monkeypatch`, because `app` is module-scoped: assigning to
+ # `app.config` outlived the test and the next one to read the shipped
+ # defaults -- `test_a_package_qualified_denied_function_is_refused` --
+ # then found this stub and failed under any ordering that put it second.
+ monkeypatch.setitem(
+ app.config, "DISALLOWED_SQL_FUNCTIONS", {"postgresql": {"version"}}
+ )
+ reason = stored_expression_error(database, None, None, "version() || :value")
+
+ assert reason is not None
+ assert "version" in reason
+
+
+def test_the_denylist_key_falls_back_when_the_engine_spec_cannot_load(
+ app: Flask, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """
+ Resolving the engine spec loads the SQLAlchemy dialect entrypoint, which
+ imports the driver package. A deployment missing an optional driver that
+ raises on import rather than being absent must not have its dataset
+ imports turned into hard failures by this gate, so the key falls back to
+ the URL's backend -- the same string for every engine without aliases.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+
+ with (
+ app.app_context(),
+ patch.object(
+ type(database),
+ "db_engine_spec",
+ new_callable=lambda: property(
+ lambda self: (_ for _ in ()).throw(ModuleNotFoundError("no driver"))
+ ),
+ ),
+ ):
+ # `monkeypatch` for the same reason as the test above: `app` is
+ # module-scoped, so a plain assignment leaks into every later test.
+ monkeypatch.setitem(
+ app.config, "DISALLOWED_SQL_FUNCTIONS", {"sqlite": {"version"}}
+ )
+ assert (
+ stored_expression_error(database, None, None, "version() || :value")
+ is not None
+ )
+
+
+# ---------------------------------------------------------------------------
+# §5 — save-time validation, in two tiers
+# ---------------------------------------------------------------------------
+
+
+def _issues(**kwargs: Any) -> list[MappingValidationIssue]:
+ defaults: dict[str, Any] = {
+ "column_names": {"event_time", "dt_epoch", "country", "region_key"},
+ "partition_column": "dt_epoch",
+ "partition_mapped_column": None,
+ "main_dttm_col": "event_time",
+ "transform": "unix_timestamp(:value)",
+ "engine": "hive",
+ }
+ defaults.update(kwargs)
+ return validate_partition_mapping(**defaults)
+
+
+def _blocking(issues: list[MappingValidationIssue]) -> list[MappingValidationIssue]:
+ return [issue for issue in issues if issue.blocking]
+
+
+def _warnings(issues: list[MappingValidationIssue]) -> list[MappingValidationIssue]:
+ return [issue for issue in issues if not issue.blocking]
+
+
+def test_a_well_formed_mapping_raises_nothing() -> None:
+ assert _issues() == []
+
+
+def test_no_partition_column_means_nothing_to_validate() -> None:
+ assert _issues(partition_column=None, transform=None) == []
+
+
+# Tier 1 — blocks the save
+
+
+def test_an_unknown_partition_column_blocks_the_save() -> None:
+ issues = _issues(partition_column="nope")
+ assert len(_blocking(issues)) == 1
+ assert issues[0].field == "partition_column"
+
+
+def test_an_unknown_mapped_column_override_blocks_the_save() -> None:
+ issues = _issues(partition_mapped_column="nope")
+ assert len(_blocking(issues)) == 1
+ assert issues[0].field == "partition_mapped_column"
+
+
+def test_an_explicit_self_mapping_blocks_the_save() -> None:
+ issues = _blocking(_issues(partition_mapped_column="dt_epoch"))
+ assert len(issues) == 1
+ assert "itself" in issues[0].message
+
+
+def test_an_implicit_self_mapping_is_reported_without_blocking() -> None:
+ """
+ Still caught -- checking only the explicit override would miss the case an
+ owner actually hits, where `partition_column` names the column that is
+ *already* the default datetime column -- but Tier 2 rather than Tier 1.
+
+ Blocking it made the state unescapable. `fetch_metadata` could choose the
+ partition column as the default datetime column without anyone asking, and
+ once it had, every later write failed validation -- including one that
+ changed nothing but the description, and including the write that would
+ have set the override that fixes it. The mapping is inert either way, since
+ `resolve_partition_mapping` bails out on it, so reporting is the whole job.
+ """
+ issues = _issues(partition_column="event_time", main_dttm_col="event_time")
+
+ assert _blocking(issues) == []
+ reported = [issue for issue in issues if "points at itself" in str(issue.message)]
+ assert len(reported) == 1
+ assert reported[0].field == "partition_mapped_column"
+ # And it names the two ways out, since neither is obvious from the error.
+ assert "override" in str(reported[0].message)
+ assert "default datetime column" in str(reported[0].message)
+
+
+def test_an_explicit_self_mapping_still_blocks_the_save() -> None:
+ """The counterpart: asked for directly, it is the mistake it looks like."""
+ issues = _blocking(
+ _issues(partition_column="event_time", partition_mapped_column="event_time")
+ )
+ assert len(issues) == 1
+ assert "itself" in str(issues[0].message)
+
+
+def test_an_override_clears_the_implicit_self_mapping_report() -> None:
+ """
+ The way out the message names has to actually work: setting an override
+ away from the partition column leaves no self-mapping at all.
+ """
+ issues = _issues(
+ partition_column="event_time",
+ main_dttm_col="event_time",
+ partition_mapped_column="country",
+ )
+
+ assert _blocking(issues) == []
+ assert not [issue for issue in issues if "points at itself" in str(issue.message)]
+
+
+def test_jinja_in_the_transform_blocks_the_save() -> None:
+ """
+ The probe would render the template in a different context at a different
+ time from the chart query, so v1 disallows it outright.
+ """
+ issues = _blocking(_issues(transform="unix_timestamp('{{ ds }}' , :value)"))
+ assert len(issues) == 1
+ assert "Jinja" in issues[0].message
+
+
+@pytest.mark.parametrize(
+ "transform",
+ [
+ "unix_timestamp(:value) - unix_timestamp()",
+ "date_diff(:value, now())",
+ "CAST(:value AS BIGINT) + rand()",
+ ],
+)
+def test_a_non_deterministic_transform_blocks_the_save(transform: str) -> None:
+ issues = _blocking(_issues(transform=transform))
+ assert len(issues) == 1
+ assert issues[0].field == "partition_value_transform"
+
+
+# Tier 2 — saves, but the mapping stays inactive
+
+
+def test_an_unparseable_transform_saves_with_a_warning() -> None:
+ """The PRD is explicit: a bad transform still saves, it just stays inactive."""
+ issues = _issues(transform="unix_timestamp(:value")
+ assert _blocking(issues) == []
+ assert len(_warnings(issues)) == 1
+
+
+def test_a_parse_failure_names_what_the_parser_choked_on() -> None:
+ """
+ "Could not be parsed" tells an owner nothing they can act on. When the
+ parser hands us a position, pass it along.
+ """
+ issues = _issues(transform="unix_timestamp(:value")
+ message = str(_warnings(issues)[0].message)
+ assert "position" in message
+
+
+def test_a_misspelled_function_is_not_a_parse_error() -> None:
+ """
+ sqlglot parses unknown functions happily -- they are anonymous calls, not
+ syntax errors -- so a typo like this reaches the engine and is reported
+ from there instead. Pinning it so the distinction is not lost.
+ """
+ assert parse_error_detail("unix_timestmp(:value)", "postgresql") is None
+
+
+def test_a_transform_without_the_placeholder_saves_with_a_warning() -> None:
+ issues = _issues(transform="unix_timestamp(event_time)")
+ assert _blocking(issues) == []
+ assert len(_warnings(issues)) == 1
+
+
+def test_a_missing_transform_saves_with_a_warning() -> None:
+ issues = _issues(transform=None)
+ assert _blocking(issues) == []
+ assert len(_warnings(issues)) == 1
+
+
+def test_an_unparseable_transform_skips_the_checks_that_need_a_parse() -> None:
+ """
+ The Jinja and non-determinism checks require a successful parse. When there
+ is nothing to inspect, fall through to a warning rather than reporting a
+ blocking error the owner cannot act on.
+ """
+ issues = _issues(transform="now(:value")
+ assert _blocking(issues) == []
+
+
+# ---------------------------------------------------------------------------
+# §4.2 — the probe cache
+# ---------------------------------------------------------------------------
+
+
+def test_a_repeated_probe_is_served_from_cache(app: Flask) -> None:
+ """
+ Day-aligned ranges ("Last month") repeat constantly across charts, so the
+ hit rate is what keeps the added round trip off the hot path.
+ """
+ database = _database_returning([1767225600])
+
+ with app.app_context():
+ first = evaluate_transform(
+ database, None, None, "unix_timestamp(:value)", ["2026-01-01"]
+ )
+ second = evaluate_transform(
+ database, None, None, "unix_timestamp(:value)", ["2026-01-01"]
+ )
+
+ assert first == second == [1767225600]
+ _probe(database).assert_called_once()
+
+
+def test_the_cache_key_includes_the_transform(app: Flask) -> None:
+ """Editing the transform must not serve the old transform's results."""
+ database = _database_returning([1])
+
+ with app.app_context():
+ evaluate_transform(database, None, None, "unix_timestamp(:value)", ["x"])
+ evaluate_transform(database, None, None, "lower(:value)", ["x"])
+
+ assert _probe(database).call_count == 2
+
+
+def test_the_cache_key_includes_the_values(app: Flask) -> None:
+ database = _database_returning([1])
+
+ with app.app_context():
+ evaluate_transform(database, None, None, "lower(:value)", ["x"])
+ evaluate_transform(database, None, None, "lower(:value)", ["y"])
+
+ assert _probe(database).call_count == 2
+
+
+def test_the_cache_key_includes_the_catalog_and_schema(app: Flask) -> None:
+ """
+ The transform is evaluated against a pinned catalog and schema; the same
+ expression can resolve differently under a different one.
+ """
+ database = _database_returning([1])
+
+ with app.app_context():
+ evaluate_transform(database, "prod", "analytics", "lower(:value)", ["x"])
+ evaluate_transform(database, "prod", "staging", "lower(:value)", ["x"])
Review Comment:
The test is named for catalog and schema, but both calls use the catalog `"prod"` and only the schema changes, so removing `catalog` from `_probe_cache_key` leaves it green. With catalog-local `map_key(:value)` returning different keys in `prod.analytics` and `staging.analytics`, a cache hit would serve the first catalog's answer and prune matching rows in the second. Could the second call change only the catalog and assert two warehouse calls with distinct results?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "hughhhh (via GitHub)" <gi...@apache.org>.
hughhhh commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4319661281
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/PartitionColumnFields.tsx:
##########
@@ -0,0 +1,319 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { useMemo } from 'react';
+import { t } from '@apache-superset/core/translation';
+import { css, useTheme } from '@apache-superset/core/theme';
+import { Alert } from '@apache-superset/core/components';
+import {
+ Button,
+ Flex,
+ Icons,
+ InfoTooltip,
+ Label,
+ Select,
+ Tooltip,
+ Typography,
+} from '@superset-ui/core/components';
+import {
+ mappedColumnIsImplicit,
+ mappingIsActive,
+ partitionMappingErrors,
+ resolveMappedColumn,
+ suggestedMappedColumn,
+} from './utils';
+import type {
+ PartitionMappingColumn,
+ PartitionMappingDatasource,
+ PartitionMappingIssue,
+} from './types';
+
+interface PartitionColumnFieldsProps {
+ datasource: PartitionMappingDatasource;
+ /**
+ * Physical columns: what the partition-column dropdown may offer, and where
+ * a replacement mapped column may be suggested from. A calculated column
+ * belongs in neither -- the engine cannot partition on an expression, and
+ * the mapping picker only renders on a physical column's row.
+ */
+ columns: PartitionMappingColumn[];
+ /**
+ * Every column on the dataset, physical and calculated. What *exists* is a
+ * different question from what may be picked, and validation asks the first:
+ * the backend accepts a calculated column as the mapped-column override, so
+ * checking existence against the physical columns alone reported a column
+ * that is really there as missing -- and blocked Save with no way out, since
+ * the dropdown cannot offer it back.
+ */
+ allColumns: PartitionMappingColumn[];
+ onPartitionColumnChange: (columnName: string | null) => void;
+ /** Open the given column's row expand in the Columns table. */
+ onNavigateToColumn: (columnName: string) => void;
+ /**
+ * Whether the mapped column's own preview says the transform mirrors, or
+ * `null`/undefined when no verdict is in yet. The checks this section can
+ * make are all static -- a transform the database rejects clears every one
+ * of them -- so without the preview's answer the banner claimed a speed-up
+ * the query never delivers.
+ */
+ previewMirrors?: boolean | null;
+}
+
+/**
+ * "Partition column" and the computed "Maps to partition" (wireframes 1a, 1g).
+ *
+ * "Maps to partition" is deliberately read-only. It reflects
+ * `partition_mapped_column ?? main_dttm_col`, and a peer dropdown would let it
+ * drift from the default datetime column silently. The only way to override it
+ * is from the target column's own row, where a transform has to be supplied
+ * alongside.
+ */
+export default function PartitionColumnFields({
+ datasource,
+ columns,
+ allColumns,
+ onPartitionColumnChange,
+ onNavigateToColumn,
+ previewMirrors,
+}: PartitionColumnFieldsProps) {
+ const theme = useTheme();
+
+ const options = useMemo(
+ () =>
+ columns.map(column => ({
+ value: column.column_name,
+ label: column.column_name,
+ customLabel: (
+ <Flex align="center" gap={theme.sizeUnit}>
+ <span>{column.column_name}</span>
+ {column.type && <Label>{column.type}</Label>}
+ </Flex>
+ ),
+ })),
+ [columns, theme.sizeUnit],
+ );
+
+ const mappedColumn = resolveMappedColumn(datasource);
+ const isImplicit = mappedColumnIsImplicit(datasource);
+ // The static checks are necessary, not sufficient: an unparseable expression
+ // or a function the database does not have needs the engine to spot, and the
+ // mapped column's row already asks it. Deferring to that answer where there
+ // is one is what keeps this banner and that panel from contradicting each
+ // other. A stored transform whose last probe failed says the same thing
+ // through the datasource's own summary, which is what an owner sees on
+ // reopening the editor.
+ const isActive =
+ mappingIsActive(datasource, allColumns) &&
+ previewMirrors !== false &&
Review Comment:
Fixed. The stored verdict applies only while the box still holds the transform it was about — `storedVerdictApplies = liveTransform === datasource.partition_filter_mapping?.evaluated_transform` — so a successful edit is no longer vetoed by the summary computed when the editor opened.
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/PartitionMappingSection.tsx:
##########
@@ -0,0 +1,344 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { useEffect } from 'react';
+import { t } from '@apache-superset/core/translation';
+import { css, useTheme } from '@apache-superset/core/theme';
+import { Alert } from '@apache-superset/core/components';
+import {
+ Button,
+ Checkbox,
+ Flex,
+ Icons,
+ InfoTooltip,
+ Input,
+ Loading,
+ Typography,
+} from '@superset-ui/core/components';
+import { useDebouncedCommit } from './useDebouncedCommit';
+import { usePartitionMappingPreview } from './usePartitionMappingPreview';
+import {
+ partitionRowState,
+ previewOperatorFor,
+ sampleValuesFor,
+ valueTransformIssues,
+} from './utils';
+import type {
+ PartitionMappingColumn,
+ PartitionMappingDatasource,
+} from './types';
+
+interface PartitionMappingSectionProps {
+ /** Injected by Field when `passItemToControl` is set. */
+ item?: PartitionMappingColumn;
+ /** The column's `partition_value_transform`, injected by Field. */
+ value?: string | null;
+ onChange?: (newValue: string | null) => void;
+ datasource: PartitionMappingDatasource;
+ /** Move the mapping onto this column, pre-filling a transform if we have one. */
+ onMoveMappingHere: (columnName: string) => void;
+ onRemoveMapping: () => void;
+ onMonotonicChange: (columnName: string, isMonotonic: boolean) => void;
+ /**
+ * Report whether the previewed transform mirrors, so the dataset-level
+ * banner can stop claiming a mirror this panel has already refused. A
+ * one-way report rather than a lift of the debounced transform this panel
+ * owns -- `null` while there is no verdict to report.
+ */
+ onPreviewVerdict?: (mirrors: boolean | null) => void;
+}
+
+/**
+ * The "Partition filter mapping" subsection of a column's row expand
+ * (wireframes 1c, 1h).
+ *
+ * Three states, because the model is one partition column and one mapped
+ * column: the mapped column carries the transform, every other column offers to
+ * take the mapping over, and the partition column itself shows nothing -- it is
+ * the target, not a source.
+ */
+export default function PartitionMappingSection({
+ item,
+ value,
+ onChange,
+ datasource,
+ onMoveMappingHere,
+ onRemoveMapping,
+ onMonotonicChange,
+ onPreviewVerdict,
+}: PartitionMappingSectionProps) {
+ const theme = useTheme();
+ const columnName = item?.column_name ?? '';
+ const state = partitionRowState(datasource, columnName);
+ const isMonotonic = Boolean(item?.partition_transform_is_monotonic);
+ const isTemporal = Boolean(item?.is_dttm);
+
+ // The editor's commit path echoes the value back several renders later, so an
+ // input driven straight off `value` loses whatever is typed in the meantime.
+ const {
+ value: transform,
+ onChange: onTransformChange,
+ flush: flushTransform,
+ } = useDebouncedCommit(value, (next: string) => onChange?.(next || null));
+
+ const { preview, loading } = usePartitionMappingPreview({
+ datasetId: datasource.id,
+ mappedColumn: columnName,
+ partitionColumn: datasource.partition_column ?? '',
+ // The local value, not the committed one: a preview is a statement about
+ // the expression in the box. Keying it off the commit would stack the
+ // commit debounce, the round trip and the preview's own debounce, and show
+ // a predicate for text that is no longer on screen.
+ valueTransform: transform,
+ sampleValues: sampleValuesFor(item),
+ operator: previewOperatorFor(item),
+ isMonotonic,
+ enabled: state === 'mapped',
+ });
+
+ // Reported rather than read upward, because the transform the preview judges
+ // is the local, debounced one this panel holds. `null` while a request is in
+ // flight: the previous verdict belongs to text that is no longer on screen.
+ useEffect(() => {
+ onPreviewVerdict?.(loading || !preview ? null : preview.valid);
Review Comment:
Fixed. Only the mapped column's row reports to `onPreviewVerdict`, so expanding another column no longer resets the dataset banner's verdict to `null`.
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/useDebouncedCommit.ts:
##########
@@ -0,0 +1,100 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { debounce } from 'lodash-es';
+import { Constants } from '@superset-ui/core/components';
+
+/**
+ * Local text state that commits upward on a debounce.
+ *
+ * The dataset editor's commit path is asynchronous and snapshot-based: a value
+ * handed to `onChange` travels Field -> Fieldset -> CollectionTable ->
+ * DatasourceEditor -> DatasourceModal and arrives back on the `value` prop
+ * several renders later, and the callback that commits it was built during an
+ * earlier render. An input driven straight off that prop therefore loses any
+ * keystroke that lands while a commit is in flight -- which is why every other
+ * control in the editor types into local state and commits on a debounce, and
+ * why Fieldset's own comment says the editor assumes exactly that. This is
+ * TextControl's contract (src/explore/components/controls/TextControl), minus
+ * the ControlHeader and the number parsing this field does not want.
+ */
+export function useDebouncedCommit(
+ value: string | null | undefined,
+ commit: (next: string) => void,
+ delay: number = Constants.FAST_DEBOUNCE,
+) {
+ const [localValue, setLocalValue] = useState(value ?? '');
+ const [prevValue, setPrevValue] = useState(value);
+ // What was last handed to `commit`. A commit's own echo arrives as a prop
+ // change like any other, and the re-seed below cannot tell the two apart --
+ // so a commit landing while typing continues (a blur or Enter flushes
+ // immediately) used to reset the input to the committed text and drop every
+ // keystroke since. State rather than a ref because the re-seed reads it
+ // during render, which is exactly what a ref is not for.
+ const [lastCommitted, setLastCommitted] = useState<string | undefined>(
+ undefined,
+ );
+
+ // The commit fires from a timer, so the callback is handed in at call time
+ // rather than captured when the debounce was built -- otherwise it would
+ // close over whichever render happened to create it, and fire a stale
+ // callback that writes to a superseded owner.
+ const debouncedCommit = useRef(
+ debounce((next: string, commitFn: (value: string) => void) => {
+ setLastCommitted(next);
+ commitFn(next);
+ }, delay),
+ );
+
+ useEffect(() => () => debouncedCommit.current.cancel(), []);
+
+ const onChange = useCallback(
+ (next: string) => {
+ setLocalValue(next);
+ debouncedCommit.current(next, commit);
Review Comment:
Fixed. The commit callback is handed to the debounce at call time rather than captured when it was built, so the timer can no longer fire a callback closed over a superseded collection snapshot.
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/usePartitionMappingPreview.ts:
##########
@@ -0,0 +1,153 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { SupersetClient, getClientErrorObject } from '@superset-ui/core';
+import { t } from '@apache-superset/core/translation';
+import { useDebounceValue } from 'src/hooks/useDebounceValue';
+import type { PartitionMappingPreview } from './types';
+import { transformCanPreview } from './utils';
+
+interface PreviewRequest {
+ datasetId?: number;
+ mappedColumn: string;
+ partitionColumn: string;
+ valueTransform: string;
+ sampleValues: string[];
+ operator: string;
+ isMonotonic: boolean;
+ /** Skip entirely when the section isn't showing a mapping. */
+ enabled: boolean;
+}
+
+/**
+ * Preview the predicate a transform would emit, debounced.
+ *
+ * The endpoint fires a real warehouse query, so the transform is debounced
+ * before it leaves the browser, and a transform that cannot work is not sent at
+ * all. Neither is a guard -- the server keeps a per-user, per-dataset budget of
+ * its own, and remains the authority on whether a transform is usable. The
+ * point is that a half-written transform should not spend that budget and leave
+ * none for the finished one.
+ */
+export function usePartitionMappingPreview({
+ datasetId,
+ mappedColumn,
+ partitionColumn,
+ valueTransform,
+ sampleValues,
+ operator,
+ isMonotonic,
+ enabled,
+}: PreviewRequest) {
+ const [preview, setPreview] = useState<PartitionMappingPreview | null>(null);
+ const [loading, setLoading] = useState(false);
+ // Which request the displayed state belongs to. `AbortController` alone is
+ // not enough: aborting settles nothing, so a handler still runs and has to
+ // ask whether it is still the current one. See the effect below.
+ const latestRequest = useRef(0);
+
+ const debouncedTransform = useDebounceValue(valueTransform, 500);
+ // `sampleValues` is a fresh array on every render, so depending on it
+ // directly would refire the effect -- and spend the preview budget -- on
+ // every keystroke elsewhere in the row. Depend on its serialized form and
+ // hand the effect a value whose identity tracks that same key.
+ const sampleKey = JSON.stringify(sampleValues);
+ const samples = useMemo<string[]>(() => JSON.parse(sampleKey), [sampleKey]);
+
+ useEffect(() => {
+ const transform = debouncedTransform?.trim();
+ // Claimed before the early return as well, so a request already in flight
+ // cannot come back and overwrite what this run decided.
+ latestRequest.current += 1;
+ const requestId = latestRequest.current;
+
+ if (
+ !enabled ||
+ !datasetId ||
+ !mappedColumn ||
+ !transformCanPreview(transform, mappedColumn, partitionColumn)
+ ) {
+ setPreview(null);
+ // The spinner belongs to a request this run has just superseded. Its own
+ // handlers see the abort and stop short of clearing it, so clearing it
+ // here is the only thing that does -- otherwise clearing the transform
+ // mid-flight left the panel spinning for good.
+ setLoading(false);
+ return undefined;
+ }
+
+ const controller = new AbortController();
+ setLoading(true);
+
+ SupersetClient.post({
+ endpoint: `/api/v1/dataset/${datasetId}/partition_mapping/preview/`,
+ jsonPayload: {
+ mapped_column: mappedColumn,
+ // The candidate, not the saved one: the owner is previewing a mapping
+ // they have not committed yet.
+ partition_column: partitionColumn,
+ value_transform: transform,
+ sample_values: samples,
+ operator,
+ is_monotonic: isMonotonic,
+ },
+ signal: controller.signal,
+ })
+ .then(({ json }) => {
+ // This hits a live warehouse query, so responses can arrive out of
+ // order. Without this an older one overwrites the current preview and
+ // reports "Valid" for a transform the input no longer holds.
+ if (requestId !== latestRequest.current) {
+ return;
+ }
+ setPreview(json.result as PartitionMappingPreview);
+ })
+ .catch(async error => {
+ if (requestId !== latestRequest.current) {
+ return;
+ }
+ const clientError = await getClientErrorObject(error);
+ setPreview({
+ valid: false,
+ error:
+ clientError.message ||
Review Comment:
Fixed. `message` is preferred only when `typeof clientError.message === 'string'`, otherwise it falls through to `clientError.error`, so a marshmallow 400 with an object-valued `message` no longer reaches `Alert description` as a React child.
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/utils.ts:
##########
@@ -0,0 +1,510 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { t } from '@apache-superset/core/translation';
+import type {
+ PartitionMappingColumn,
+ PartitionMappingDatasource,
+ PartitionMappingIssue,
+ PartitionRowState,
+} from './types';
+
+/**
+ * Jinja delimiters.
+ *
+ * A transform is evaluated in a different context and at a different time from
+ * the chart query, so a template would not render the same way -- the backend
+ * rejects one outright. Shared so the check that declines to preview a Jinja
+ * transform and the check that blocks saving it cannot drift apart.
+ */
+const JINJA_PATTERN = /\{\{|\{%|\{#/;
+
+/**
+ * The column whose filters are mirrored.
+ *
+ * `partition_mapped_column` is an explicit override; `null` means "follow the
+ * default datetime column", so re-pointing that column moves the mapping with
+ * it. Mirrors `SqlaTable.partition_filter_mapping_summary` on the backend.
+ */
+export function resolveMappedColumn(
+ datasource: PartitionMappingDatasource,
+): string | null {
+ if (!datasource.partition_column) {
+ return null;
+ }
+ return datasource.partition_mapped_column || datasource.main_dttm_col || null;
+}
+
+/** Whether the mapped column came from `main_dttm_col` rather than an override. */
+export function mappedColumnIsImplicit(
+ datasource: PartitionMappingDatasource,
+): boolean {
+ return Boolean(
+ datasource.partition_column &&
+ !datasource.partition_mapped_column &&
+ datasource.main_dttm_col,
+ );
+}
+
+/**
+ * Whether a transform is worth spending a preview request on.
+ *
+ * A necessary condition, never a sufficient one: the server stays the authority
+ * on whether a transform is usable, and anything this cannot see -- an
+ * unparseable expression, a non-deterministic function -- still comes back from
+ * it. What this catches is the cases that are knowably hopeless while the owner
+ * is still typing, which would otherwise spend the per-user preview budget and
+ * leave none for the transform they eventually finish writing.
+ */
+export function transformCanPreview(
+ transform: string | null | undefined,
+ mappedColumn?: string | null,
+ partitionColumn?: string | null,
+): boolean {
+ const trimmed = transform?.trim();
+ if (!trimmed) {
+ return false;
+ }
+ // Without the placeholder there is no value to substitute, so the transform
+ // is inert however well-formed it is.
+ if (!/:value\b/.test(trimmed)) {
+ return false;
+ }
+ // Jinja is rejected on save, so previewing it is pointless.
+ if (JINJA_PATTERN.test(trimmed)) {
+ return false;
+ }
+ // A column cannot stand in for itself; the backend rejects this outright.
+ if (mappedColumn && partitionColumn && mappedColumn === partitionColumn) {
+ return false;
+ }
+ return true;
+}
+
+/**
+ * Whether the mapping will actually mirror anything.
+ *
+ * Drives the choice between the green "filters will automatically apply"
+ * message and the warning that nothing is mirrored yet, so "non-blank text in
+ * the box" is not a good enough test: a transform with no `:value` to
+ * substitute, or one carrying Jinja, is as inert as an empty one and the
+ * backend's own summary reports it inactive. Claiming otherwise tells an owner
+ * their queries are pruning when they are not.
+ *
+ * Shares `transformCanPreview`'s conditions rather than restating them, and is
+ * necessary rather than sufficient for the same reason: an unparseable
+ * expression or a non-deterministic function needs a SQL parser to spot, so the
+ * server stays the authority -- `valueTransformIssues` surfaces what it says at
+ * the transform field itself.
+ */
+export function mappingIsActive(
+ datasource: PartitionMappingDatasource,
+ columns: PartitionMappingColumn[],
+): boolean {
+ const mappedColumnName = resolveMappedColumn(datasource);
+ if (!mappedColumnName || mappedColumnName === datasource.partition_column) {
+ return false;
+ }
+ const mappedColumn = columns.find(
+ column => column.column_name === mappedColumnName,
+ );
+ return transformCanPreview(
+ mappedColumn?.partition_value_transform,
+ mappedColumnName,
+ datasource.partition_column,
+ );
+}
+
+/**
+ * What is wrong with one column's value transform, if anything.
+ *
+ * Split out of `partitionMappingErrors` because the two callers disagree about
+ * which text to judge. The save gate reads the committed column record; the
+ * field's own message has to describe the text on screen, which lags the commit
+ * by a debounce. Passing the transform separately lets both ask the same
+ * question about different values instead of reimplementing the checks.
+ */
+export function valueTransformIssues(
+ column: PartitionMappingColumn | undefined,
+ transform: string | null | undefined,
+): PartitionMappingIssue[] {
+ if (!column) {
+ return [];
+ }
+
+ if (JINJA_PATTERN.test(transform ?? '')) {
+ return [
+ {
+ field: 'partition_value_transform',
+ message: t(
+ 'Jinja templating is not supported in a partition value transform. The transform is evaluated in a different context and at a different time from the chart query, so a template would not render the same way.',
+ ),
+ },
+ ];
+ }
+
+ // A temporal column falls back on the engine's own default, so leaving the box
+ // empty there only makes the mapping inactive -- which the dataset-level
+ // warning already says. A non-temporal column has nothing to fall back on.
+ if (!column.is_dttm && !transform?.trim()) {
+ return [
+ {
+ field: 'partition_value_transform',
+ message: t(
+ 'A value transform is required on %(name)s, which is not a temporal column. Use :value for each value.',
+ { name: column.column_name },
+ ),
+ },
+ ];
+ }
+
+ return [];
+}
+
+/**
+ * Everything wrong with the mapping that should stop the save.
+ *
+ * The client half of `validate_partition_mapping` in
+ * `superset/connectors/sqla/partition_mapping.py`, restricted to its blocking
+ * (Tier 1) issues. Those are the ones the PUT would reject anyway, so catching
+ * them here turns a 400 toast arriving after the modal closed into a disabled
+ * Save button that says why. Tier 2 is deliberately absent: an unparseable
+ * transform, or one missing `:value`, is "saved but stays inactive until it
+ * parses" per the PRD, and must not cost the owner the rest of their edits.
+ *
+ * One check is stricter than the backend's: an empty transform on a
+ * non-temporal mapped column blocks. The backend files that as Tier 2 for every
+ * column, but a non-temporal column has no default transform to fall back on --
+ * the field carries a required marker saying exactly this -- so the marker
+ * should mean something.
+ *
+ * Callers gate on the feature flag themselves, the way the two mount sites in
+ * `DatasourceEditor` already do; a dataset carrying a stale `partition_column`
+ * on an engine that cannot use one must not block a save the backend accepts.
+ */
+export function partitionMappingErrors(
+ datasource: PartitionMappingDatasource,
+ columns: PartitionMappingColumn[],
+): PartitionMappingIssue[] {
+ const partitionColumn = datasource.partition_column;
+ if (!partitionColumn) {
+ return [];
+ }
+
+ const issues: PartitionMappingIssue[] = [];
+ const columnNames = new Set(columns.map(column => column.column_name));
+
+ if (!columnNames.has(partitionColumn)) {
+ issues.push({
+ field: 'partition_column',
+ message: t('Partition column %(name)s is not a column on this dataset.', {
+ name: partitionColumn,
+ }),
+ });
+ }
+
+ const override = datasource.partition_mapped_column;
+ if (override && !columnNames.has(override)) {
+ issues.push({
+ field: 'partition_mapped_column',
+ message: t('Mapped column %(name)s is not a column on this dataset.', {
+ name: override,
+ }),
+ });
+ }
+
+ const mappedColumnName = resolveMappedColumn(datasource);
+ if (mappedColumnName === partitionColumn) {
Review Comment:
Fixed. Only the explicit self-mapping blocks: `blocking: Boolean(datasource.partition_mapped_column)`. The implicit case is shown as a warning the owner can save through, matching `validate_partition_mapping`'s tiers.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4330415114
##########
superset/db_engine_specs/postgres.py:
##########
@@ -178,6 +178,9 @@ class PostgresBaseEngineSpec(BaseEngineSpec):
engine = ""
engine_name = "PostgreSQL"
+ # The engine's default text comparison is binary, so a mirrored
+ # ``partition_col = T(v)`` agrees with the ``col = v`` it stands in for.
+ binary_string_comparison = True
Review Comment:
Netezza inherits this flag through `PostgresBaseEngineSpec`, but its string comparison ignores trailing spaces (unlike PostgreSQL's binary comparison). With VARCHAR columns and a transform like `:value || 'x'`, the row `(country='US', p='USx')` satisfies `country = 'US '`, yet the mirrored predicate asks for `p = 'US x'` and silently drops it. Should this be declared on the concrete specs where binary comparison is verified instead of on the shared base?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,3524 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Writing the value into the probe
+--------------------------------
+The probe evaluates the transform at a *literal*, because it runs with no bound
+parameters at all -- so every value is written into SQL text by the driver's
+literal renderer and read back by the engine's lexer, and the two do not always
+agree. SQLAlchemy's default renderer doubles apostrophes and leaves backslashes
+alone; Hive honours backslash escapes and not doubling, so ``'O''Brien'`` is
+read there as two adjacent literals and ``'x\\''`` ends four characters into a
+value the filter carries whole. A disagreement is either a mirror built from a
+value nobody filtered on -- dropping rows the filter keeps -- or, where the
+value closes its own quote, an expression of the filterer's choosing running in
+the probe.
+
+Which side is right is not knowable from the driver: it is a per-session server
+setting (``standard_conforming_strings``, ``NO_BACKSLASH_ESCAPES``,
+``spark.sql.parser.escapedStringLiterals``), and SQLAlchemy's own view of it is
+only correct on a dialect that has connected. So escaping is not what makes
+this safe. `literal_round_trips` renders the literal and reads it back in the
+engine's own dialect instead, and a value that does not survive the trip is not
+mirrored -- the usual trade, pruning for correctness. `probe_sql_is_evaluable`
+re-reads the finished statement behind it.
+
+The probe's *answers* make the same trip, in the other direction. The chart
+query is compiled with ``literal_binds``, so a probed partition key is rendered
+into its SQL by the same renderer and read by the same lexer -- and
+``concat(:value, chr(92), 'b')`` turns the unremarkable input ``a`` into the key
+``a\\b``, which Hive reads back as ``a`` followed by a backspace. So
+`_predicates_from_probe` asks `literal_round_trips` about each result too, and
+declines the request rather than emitting a predicate no row can satisfy: the
+mirror is ``AND``-ed onto the query, so a mirror that matches nothing costs the
+chart its rows rather than its pruning.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: The opening and closing delimiters of each kind of Jinja block. The probe
+#: would render these in a different context at a different time from the chart
+#: query, so a transform holding one is rejected at save time.
+JINJA_BLOCK_DELIMITERS = (("{{", "}}"), ("{%", "%}"), ("{#", "#}"))
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: A PostgreSQL Unicode-escaped identifier, ``U&"..."``.
+#:
+#: The second construct that breaks the premise above, and in the same way:
+#: ``U&"\\0071uery_to_xml"(...)`` parses as an anonymous function whose name is
+#: the *literal* ``\\0071uery_to_xml``, so the function denylist is matching a
+#: name the engine never sees -- PostgreSQL decodes the escape and runs
+#: ``query_to_xml``, handing a dataset owner rows from outside their RLS scope
+#: through the preview's ``emitted_predicate``.
+#:
+#: Normalizing the escapes and re-checking would be the other repair, and is
+#: worse: it means reimplementing one engine's identifier decoding well enough
+#: to be a security boundary. Refusing the construct is exact, and costs
+#: nothing real -- a transform is a scalar function of ``:value``, and there is
+#: no reason to name a function or column through an escape sequence.
+#:
+#: Refused on every engine, like the executable comment, so a transform stored
+#: on SQLite cannot detonate when the dataset is re-pointed at PostgreSQL. The
+#: ``&`` may be separated from the ``U`` by nothing at all, but whitespace or a
+#: comment between the prefix and the string is not accepted by PostgreSQL
+#: either, so the strict form is the whole surface.
+#:
+#: Matched in raw text, so the prefix is refused inside a string literal too.
+#: That is the same trade the executable comment makes and has the same
+#: justification: a gate whose contract is to fire *before* the parse cannot
+#: ask the parse whether the text was quoted. ``concat(:value, 'u&"x"')`` is
+#: refused, which costs an owner nothing anyone writes.
+UNICODE_ESCAPED_IDENTIFIER_RE = re.compile(r'\bU&"', re.IGNORECASE)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate: a transform such as
+#: ``datediff(day, :value, LOCALTIMESTAMP)`` for a relative partition key is
+#: evaluated once and then keeps emitting yesterday's answer, so the chart
+#: silently drops rows after midnight.
+#:
+#: Matched by SQL function name, so every engine's spelling of "now" has to be
+#: named -- the ANSI four were not enough. Listed rather than delegated to the
+#: engine specs because the risk is the same everywhere and a spec that had not
+#: got round to declaring its own would fail open; a name no engine has is
+#: inert, so over-listing costs nothing.
+NON_DETERMINISTIC_FUNCTIONS = {
+ # ANSI, and the engines that spell it this way.
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "LOCALTIME",
+ "LOCALTIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+ # PostgreSQL. `now()` is statement-stable; these two are not even that.
+ "CLOCK_TIMESTAMP",
+ "STATEMENT_TIMESTAMP",
+ "TIMEOFDAY",
+ # MySQL and MariaDB.
+ "CURDATE",
+ "CURTIME",
+ "SYSDATE",
+ "UTC_DATE",
+ "UTC_TIME",
+ "UTC_TIMESTAMP",
+ "UUID_SHORT",
+ # Oracle.
+ "SYSTIMESTAMP",
+ "SYS_GUID",
+ # SQL Server.
+ "GETDATE",
+ "GETUTCDATE",
+ "SYSDATETIME",
+ "SYSUTCDATETIME",
+ "SYSDATETIMEOFFSET",
+ "NEWID",
+ # BigQuery.
+ "CURRENT_DATETIME",
+ "GENERATE_UUID",
+ # Snowflake.
+ "RANDSTR",
+ "UUID_STRING",
+ # ClickHouse.
+ "NOW64",
+ "RANDCANONICAL",
+ "GENERATEUUIDV4",
+ # H2 and Derby, which the test fixtures use.
+ "RANDOM_UUID",
+}
+
+#: The wall-clock names an engine evaluates with no parentheses at all.
+#:
+#: These parse as *column references*, not functions, so the name-based walk
+#: below cannot see them: `datediff(UTC_DATE, :value)` on MySQL and
+#: `:value - SYSDATE` on Oracle both cleared the gate and froze probe time into
+#: a cached mirror.
+#:
+#: A subset of `NON_DETERMINISTIC_FUNCTIONS` rather than the whole of it,
+#: because refusing a bare name costs an owner a column genuinely called that.
+#: Only the names SQL lets you write without ``()`` are listed -- the datetime
+#: keywords -- so `rand`, `uuid` and `newid`, which always need parentheses and
+#: are plausible column names, stay out.
+BARE_WALL_CLOCK_KEYWORDS = frozenset(
+ {
+ "current_date",
+ "current_time",
+ "current_timestamp",
+ "localtime",
+ "localtimestamp",
+ "utc_date",
+ "utc_time",
+ "utc_timestamp",
+ "sysdate",
+ "systimestamp",
+ }
+)
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+class Unmirrorable:
+ """
+ A filter no mirror can stand in for, and why.
+
+ Returned by `ExploreMixin.mirror_probe_request` for a value the engine
+ compares more coarsely than the filter carries, one it cannot render as a
+ literal, one whose rendered literal the engine would not read back as the
+ same value, one in a time frame the transform would discard, or an ``IN``
+ list with a member of any of those kinds. An object rather than `None`,
+ because `None` is a filter value in its own right.
+
+ The reason rides along because the preview has to explain the decline to
+ the owner, and the two declines want different advice: "the engine compares
+ less of this value than you typed, so map a column it compares in full" is
+ sound guidance for a `DATE` column and actively misleading for an
+ offset-bearing bound on a `TIMESTAMP` one, which already is such a column.
+ Carried rather than re-derived so the preview's explanation cannot come
+ apart from the chart path's decision.
+
+ Lives here rather than beside that method so the preview can read it too:
+ `superset.models.helpers` imports this module, so these can only cross the
+ boundary in this direction. Both callers recognise the same instances -- a
+ preview that answered "valid" for a request the chart path declines is the
+ drift this is here to prevent.
+ """
+
+ __slots__ = ("reason",)
+
+ def __init__(self, reason: str) -> None:
+ self.reason = reason
+
+ def __repr__(self) -> str:
+ return f"<Unmirrorable {self.reason}>"
+
+
+#: The ordinary decline: whatever the mirror cannot be built from, with the
+#: engine's own comparison resolution as the reason an owner can act on.
+UNMIRRORABLE = Unmirrorable("resolution")
+
+#: A value carrying a UTC offset, declined whatever the column's resolution.
+#: A transform such as ``CAST(:value AS TIMESTAMP)`` drops the offset, so even
+#: an engine that compares the whole instant would be probed in the wrong
+#: frame -- which is not something mapping a different column fixes.
+UNMIRRORABLE_OFFSET = Unmirrorable("offset")
+
+#: A value the driver and the engine would not spell the same way, declined
+#: whatever the column's resolution and whatever the operator. Nothing about
+#: the column or the transform fixes it -- see `literal_round_trips` -- so the
+#: advice the resolution reason carries would send an owner after the wrong
+#: thing entirely.
+UNMIRRORABLE_ESCAPING = Unmirrorable("escaping")
+
+
+def is_unmirrorable(value: Any) -> bool:
+ """Whether `mirror_probe_request` declined this request."""
+ return isinstance(value, Unmirrorable)
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def _native_generic_type(
+ column: "TableColumn",
+) -> utils.GenericDataType | None:
+ """
+ What the engine spec makes of ``column``'s declared type.
+
+ `TableColumn.type_generic` answers ``TEMPORAL`` for every column carrying
+ ``is_dttm``, which is the right answer for a chart's time axis and the
+ wrong one for a comparison: an epoch ``BIGINT`` is a number to the engine
+ however it is labelled here. Falls back to the flag where the spec has no
+ answer, so a type Superset cannot resolve is no worse off than before.
+ """
+ try:
+ column_spec = column.db_engine_spec.get_column_spec(
+ column.type, db_extra=column.db_extra
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ column_spec = None
+ if column_spec is not None and column_spec.generic_type is not None:
+ return column_spec.generic_type
+ try:
+ return column.type_generic
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+#: Declared types whose comparison ignores trailing blanks.
+#:
+#: The fixed-width character types, which the SQL standard has compare as
+#: though both sides were padded to the same length -- so ``'US'`` and
+#: ``'US '`` are equal in a ``CHARACTER(3)``, while ``lower()`` of the two is
+#: not. Spelled out rather than matched by prefix because the variable-width
+#: names start with the same letters: ``VARCHAR`` and ``CHARACTER VARYING``
+#: compare the blanks and must not land here.
+PADDED_CHARACTER_TYPES = frozenset(
+ {
+ "CHAR",
+ "NCHAR",
+ # PostgreSQL's own name for ``CHARACTER``, which is what reflection
+ # reports for a ``CHAR(n)`` column there.
+ "BPCHAR",
+ "CHARACTER",
+ "NATIONAL CHAR",
+ "NATIONAL CHARACTER",
+ }
+)
+
+
+def _is_padded_character_type(column: TableColumn) -> bool:
+ """
+ Whether ``column``'s declared type compares without its trailing blanks.
+
+ Read off the declared type rather than the engine spec's resolved one: the
+ specs map ``CHAR`` and ``VARCHAR`` onto the same `sqlalchemy.String`, so
+ the distinction this needs is gone by then. The length suffix is dropped
+ and the name matched against `PADDED_CHARACTER_TYPES`, so an unfamiliar
+ spelling answers ``False`` and the engine-level flag decides as before --
+ this gate adds a decline rather than lifting one. A column with no
+ declared type has nothing to read, and answers the same way.
+ """
+ if not isinstance(column.type, str):
+ return False
+ native = re.sub(r"\s+", " ", column.type.strip().upper())
+ return native.split("(")[0].strip() in PADDED_CHARACTER_TYPES
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ Padding is asked about per column, because it is a property of the *type*
+ rather than of the engine. ``binary_string_comparison`` speaks for an
+ engine's default text comparison, and on PostgreSQL -- which declares it
+ -- a ``CHAR(2)`` still matches a filter for ``'US '`` against a stored
+ ``'US'``, because the standard says a padded character type compares
+ without its trailing blanks. The mirror ``region_key = lower('US ')`` then
+ excludes the row. So a fixed-width character type declines whatever the
+ engine says, and an engine that ignores trailing blanks on its *variable*
+ types says so by not declaring the flag at all (see `RedshiftEngineSpec`).
+
+ The type asked for is the engine spec's reading of the column's declared
+ type, not `TableColumn.type_generic`, which answers ``TEMPORAL`` for
+ anything carrying ``is_dttm``. A ``VARCHAR`` flagged temporal is still text
+ to the engine: on MySQL a filter for ``'2026-01-01T00:00:00'`` matches a
+ stored ``'...t00:00:00'``, while the mirror ``p = hex('...T...')`` excludes
+ it -- and asking the semantic flag skipped the check entirely.
+
+ A type the spec cannot classify declines, which is what the paragraph above
+ promises and what only the exception branch used to do. PostgreSQL's
+ ``citext`` matches no type pattern, so it answered ``None`` -- neither
+ string nor not-string -- and was waved through, which is precisely wrong
+ for a type whose whole purpose is case-insensitive comparison. Declining
+ costs the pruning; admitting it costs rows.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ # Ahead of the generic-type question, which a padded type can lose: the
+ # specs map ``CHARACTER`` onto no generic type at all on some engines, and
+ # a fixed-width character type is a string whether or not Superset can say
+ # so from the name.
+ if _is_padded_character_type(column):
+ return False
+ generic_type = _native_generic_type(column)
+ if generic_type is None:
+ return False
+ if generic_type != utils.GenericDataType.STRING:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_unicode_escaped_identifier(transform: str | None) -> bool:
+ """Whether the transform names something through a ``U&"..."`` escape.
+
+ See `UNICODE_ESCAPED_IDENTIFIER_RE`. Answered on raw text for the same
+ reason as the comment above: the parse reports a name the engine does not
+ use, which is exactly what makes the denylist blind to it.
+ """
+ return (
+ bool(transform)
+ and UNICODE_ESCAPED_IDENTIFIER_RE.search(transform or "") is not None
+ )
+
+
+#: Sequence pseudo-columns, which advance a sequence when they are *read*.
+#:
+#: ``orders_seq.NEXTVAL`` parses as a qualified column reference, not a
+#: function call, so neither `SQLStatement.is_mutating` -- which walks function
+#: names -- nor the function denylist can see it. The probe would then run
+#: ``SELECT orders_seq.NEXTVAL + 1 FROM DUAL`` and advance the sequence, again
+#: on every cache expiry, for a dataset editor holding neither SQL Lab nor a
+#: DML grant. Reading one is a write however the parser classifies it.
+#:
+#: The function spelling (``nextval('s')`` on PostgreSQL) is a different shape
+#: and is caught as a function; this is only about the suffix form.
+SEQUENCE_PSEUDO_COLUMNS = frozenset({"nextval", "currval"})
+
+#: The same thing written as a call.
+#:
+#: Only the suffix form parses as a column; `nextval('s')` on PostgreSQL and
+#: DuckDB, `NEXTVAL(s)`/`SETVAL(s, 1)` on MySQL and MariaDB, and SQL Server's
+#: `NEXT VALUE FOR s` all parse as functions. `SQLStatement.is_mutating` walks
+#: function names on PostgreSQL alone -- deliberately, since the same names are
+#: read-only elsewhere -- so every other engine let these through.
+#:
+#: Matched on the name whatever the engine, because advancing a sequence is a
+#: write wherever it happens and a transform has no reason to call one.
+SEQUENCE_FUNCTIONS = frozenset(
+ {"nextval", "setval", "next_value_for", "nextvalfor", "prevval", "lastval"}
+)
+
+
+def references_sequence(statement: SQLStatement) -> bool:
+ """Whether the statement reads or advances a sequence.
+
+ Both spellings: the pseudo-column suffix, which parses as a column (see
+ `SEQUENCE_PSEUDO_COLUMNS`), and the call, which parses as a function (see
+ `SEQUENCE_FUNCTIONS`).
+
+ Answered on the parse rather than on raw text, because position is what
+ makes it the construct: a column or alias merely *called* ``nextval`` is
+ an ordinary column, and a string literal holding the word is text.
+ """
+ return bool(
+ statement.get_column_names() & SEQUENCE_PSEUDO_COLUMNS
+ or statement.get_disallowed_functions(set(SEQUENCE_FUNCTIONS))
+ )
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """
+ Whether the transform contains a balanced Jinja block.
+
+ A block is an opening delimiter followed, anywhere later, by its closing
+ one -- the same thing ``{{.*?}}`` and its two siblings match under
+ ``re.DOTALL``. Scanned with `str.find` rather than that pattern, because a
+ lazy match retried from every opening delimiter is quadratic in a run of
+ them, and this runs on stored transforms with no length bound of its own:
+ `is_transform_active` reads whatever the column holds. The earliest opening
+ delimiter is the only one worth trying, since any closing delimiter after a
+ later one is also after it.
+ """
+ if not transform:
+ return False
+ for opening, closing in JINJA_BLOCK_DELIMITERS:
+ start = transform.find(opening)
+ if start != -1 and transform.find(closing, start + len(opening)) != -1:
+ return True
+ return False
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+
+ Three spellings have to be looked for, because one name reaches the parse
+ three ways: as a function call, as a zero-argument call a dialect resolves
+ itself, and -- for the datetime keywords -- as a bare word that parses as a
+ column reference.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ # The parenthesis-free spellings, which parse as columns rather than
+ # functions and so are invisible to the walk above. See
+ # `BARE_WALL_CLOCK_KEYWORDS`.
+ found |= {
+ name.upper() for name in BARE_WALL_CLOCK_KEYWORDS & statement.get_column_names()
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error( # noqa: C901
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ And it must be a *read*. Shape is a separate question from effect: a bare
+ scalar expression can still write, so `SQLStatement.is_mutating` is asked
+ too -- the same question SQL Lab and the chart executor ask before letting
+ SQL run. See the gate itself for what that reaches and what it does not.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ # Also ahead of the parse, and for a stronger reason than cost: every gate
+ # below reasons about the parse tree, and this is the one construct that
+ # makes the parse tree describe a different statement from the one the
+ # engine runs. Checked here as well as in `validate_transform` because this
+ # is the door a row written by an earlier release still comes through.
+ if contains_executable_comment(transform):
+ return str(
+ _(
+ "A partition value transform cannot contain a MySQL "
+ "executable comment, which the database executes and every "
+ "validator reads as a comment."
+ )
+ )
+
+ if contains_unicode_escaped_identifier(transform):
+ return str(
+ _(
+ "A partition value transform cannot name anything through a "
+ 'U&"..." escape sequence, which the database decodes and '
+ "every validator reads literally."
+ )
+ )
+
+ # Same door, same reason: the name the denylist below would match is not
+ # the name the engine resolves. See `UNICODE_ESCAPED_IDENTIFIER_RE`.
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The read-only gate, which nothing above implies. The shape gates ask what
+ # the transform *selects*; this asks what evaluating it *does*, and a bare
+ # scalar expression can still write. `nextval(:value)` on PostgreSQL
+ # advances a sequence: one function call, no clause, no sub-query, and not
+ # in the default `DISALLOWED_SQL_FUNCTIONS` either -- so every gate above
+ # passes it and the probe then runs it. `setval` is the same shape, and
+ # `exp.Execute` and the opaque-`exp.Command` forms arrive the same way.
+ #
+ # The large-object writers (`lo_export`, `lowrite`, `lo_from_bytea`, ...)
+ # are caught here too, and the shipped denylist happens to name them as
+ # well -- but that is config an operator can replace, while this is not.
+ #
+ # `is_mutating` is the same question SQL Lab, `get_virtual_table_metadata`
+ # and the chart executor ask before letting SQL run, so a transform is held
+ # to the bar the rest of Superset already sets rather than to one invented
+ # here. Unconditional rather than gated on `Database.allow_dml`: a transform
+ # is a scalar function of `:value` by definition, so there is no legitimate
+ # mutating one, and the probe runs on a cache schedule nobody chose -- a
+ # write would repeat every time the entry expired.
+ #
+ # It bears saying what this does not reach. A user-defined function whose
+ # body writes is a plain call no parser can tell from `lower(:value)`, and
+ # `is_mutating`'s function-name walk is PostgreSQL-only by design, since the
+ # same names are read-only elsewhere. Neither residual is specific to this
+ # feature -- a dataset editor can already have the engine evaluate an
+ # arbitrary expression through a calculated column or a virtual dataset's
+ # SQL -- and closing them means authorizing the preview against the
+ # database, not parsing harder.
+ if statement.is_mutating():
+ return str(
+ _(
+ "A partition value transform cannot change data. It is "
+ "evaluated against the database to check that it mirrors, so "
+ "it has to be a read."
+ )
+ )
+
+ # Not reached by the walk above, which is why it is its own gate: a
+ # sequence pseudo-column is a *column* to the parser and a write to the
+ # engine. See `SEQUENCE_PSEUDO_COLUMNS`.
+ if references_sequence(statement):
+ return str(
+ _(
+ "A partition value transform cannot read a sequence. "
+ "NEXTVAL advances the sequence every time it is evaluated, "
+ "and the transform is evaluated on a cache schedule."
+ )
+ )
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the
+ probe uninspected. Rendering is not what makes that true: a string element
+ is checked by `literal_round_trips` before it is rendered -- the dialect's
+ literal processor and the engine's lexer do not always agree about what a
+ rendered literal says -- and `probe_sql_is_evaluable` re-reads the finished
+ query, which is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def _placeholder_is_bindable(transform: str) -> bool:
+ """
+ Whether SQLAlchemy's ``text()`` can see ``:value`` as a bound parameter.
+
+ `VALUE_PLACEHOLDER_RE` is ``:value\b``, which matches the placeholder in a
+ Postgres cast such as ``:value::bigint``. SQLAlchemy's own bind scan is
+ ``(?<![:\\w$]):([\\w$]+)(?![:\\w$])`` -- note the trailing exclusion -- so a
+ following colon stops it: ``text(":value::bigint")`` reports a parameter
+ named ``valu``, and ``.bindparams(bindparam("value"))`` then raises
+ ``ArgumentError``.
+
+ `_probe` swallows that, so the only symptom was a perfectly valid transform
+ whose mapping silently never pruned, and a preview reporting an engine
+ failure for SQL that was never sent. Every write-side gate passes the
+ transform: it parses, it is a bare expression, and the placeholder *is* in
+ an executable position.
+
+ Answered by attempting the bind itself rather than by pattern-matching
+ ``::`` or reading ``text()``'s private parameter map, so this cannot
+ disagree with what `build_probe_sql` is about to do -- on any dialect, or on
+ a SQLAlchemy whose scan changes.
+ """
+ try:
+ sa.text(transform).bindparams(sa.bindparam("value", value=None))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return False
+ return True
+
+
+def escape_foreign_colons(transform: str) -> str:
+ """
+ ``transform`` with every colon but the ``:value`` placeholder escaped.
+
+ `sqlalchemy.text` reads any ``:word`` as a bind parameter, including one
+ inside a string literal, and an unbound parameter renders as ``NULL``
+ under literal binds rather than raising. So ``:value || \':suffix\'``
+ compiled to ``'us' || 'NULL'``: the mirror asked for a partition value no
+ row holds and the chart dropped rows, with no error for `_probe` to
+ swallow and nothing on screen to say so.
+
+ Escaped rather than refused, because a colon in a literal is ordinary --
+ ``concat(:value, \':\', region)`` builds a composite key -- and the
+ placeholder is the only colon this module means to interpret. `text()`
+ reads ``\\:`` as a literal colon.
+
+ Only the bound path needs this. A `RawProbeValue` or an unbindable
+ placeholder is substituted as text by `parse_skeleton`, which never hands
+ the transform to `text()` at all.
+ """
+ pieces: list[str] = []
+ cursor = 0
+ for match in VALUE_PLACEHOLDER_RE.finditer(transform):
+ pieces.append(transform[cursor : match.start()].replace(":", r"\:"))
+ pieces.append(match.group(0))
+ cursor = match.end()
+ pieces.append(transform[cursor:].replace(":", r"\:"))
+ return "".join(pieces)
+
+
+def literal_round_trips(value: Any, dialect: Dialect | None, engine: str) -> bool:
+ """
+ Whether the engine reads a rendered ``value`` back as that same value.
+
+ The probe runs with no bound parameters, so every value reaches the engine
+ as literal text the driver wrote (see `build_probe_sql`). Whether that text
+ says what the value says is a question about two independent spellings: the
+ driver's escaping, and the engine's lexer. SQLAlchemy's default renderer
+ doubles apostrophes and passes backslashes through; Hive and Spark honour
+ the backslash and not the doubling, so ``'O''Brien'`` is read there as two
+ adjacent literals -- the transform is evaluated at ``OBrien``, and the
+ mirror asks for a partition key that holds none of the rows the filter
+ keeps. The same gap in the other direction lets a value close its own quote
+ and have the rest of it read as SQL.
+
+ Escaping is not the repair. Whether a backslash introduces an escape is a
+ per-session server setting -- ``standard_conforming_strings`` on Postgres,
+ ``NO_BACKSLASH_ESCAPES`` on MySQL, ``escapedStringLiterals`` on Spark -- and
+ nothing in the engine specs exposes it. SQLAlchemy reads it off the server
+ into ``_backslash_escapes`` during ``initialize(connection)``, which the
+ probe's dialect never reaches: `_dialect_for` asks the ``Database`` for a
+ dialect, not for a connection, so Postgres renders ``a\\b`` as
+ ``'a\\\\b'`` and a server with the standard setting reads four
+ characters. An engine-spec flag would have to be defaulted, and either
+ default is wrong for a dozen engines: one leaves the hole open, the other
+ corrupts the probed value.
+
+ So the premise is verified rather than declared, the way
+ `probe_sql_is_evaluable` verifies the finished statement. A value that does
+ not survive the round trip is not mirrored, which costs the query its
+ pruning and nothing else.
+
+ The short-circuit is a proof, not a guess, and it matters for cost: a
+ 200-member ``IN`` list would otherwise parse 200 times on the chart path.
+ If the renderer emitted the value between two quotes and changed nothing in
+ it, and the value carries neither a quote nor a backslash, then no lexer in
+ play can read it as anything but itself. Both exclusions are load-bearing:
+ on Hive ``a\\b`` renders verbatim and reads as ``a`` followed by a
+ backspace.
+
+ :param value: a filter value about to be rendered into the probe
+ :param dialect: the dialect that will render it, as `_dialect_for` reports
+ :param engine: ``database.backend``, whose lexer reads the result
+ :return: whether the two agree about what the literal says
+ """
+ if isinstance(value, RawProbeValue):
+ # Already SQL, with no single value for a parse to be compared against:
+ # its elements are checked before they are rendered, by
+ # `ExploreMixin._array_mirror_probe_value`. A backslash surviving into
+ # the finished text is refused here all the same, as the backstop for a
+ # renderer this module does not own.
+ return "\\" not in value.sql
+ if not isinstance(value, str):
+ # Numbers and instants are not written between delimiters, so there is
+ # no escaping for the two sides to disagree about.
+ return True
+
+ rendered = _compile_literal(sa.literal(value), dialect)
+ if rendered == f"'{value}'" and "'" not in value and "\\" not in value:
+ return True
+
+ try:
+ return (
+ SQLStatement(f"SELECT {rendered}", engine).get_select_literal_value()
+ == value
+ )
+ except SupersetParseError:
+ # A rendered literal the engine's own dialect will not parse is the
+ # strongest form of disagreement there is.
+ return False
+
+
+def value_round_trips(database: Database, value: Any) -> bool:
+ """
+ `literal_round_trips` for a caller holding a database, not a dialect.
+
+ Which renderer and which lexer apply is this module's business, so the two
+ callers outside it -- the chart path's own gate in
+ `ExploreMixin.mirror_probe_request` and the mapping summary Explore reads
+ -- ask in these terms and stay out of it.
+
+ :param database: the database whose driver renders and whose engine reads
+ :param value: a filter value about to be rendered into the probe
+ :return: whether the two agree about what the literal says
+ """
+ return literal_round_trips(value, _dialect_for(database), database.backend)
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text. That is not itself a boundary:
+ the processor's escaping is not always the escaping the engine honours, and
+ a value can close its own quote through the gap. The boundary is
+ `literal_round_trips` on the way in -- which callers must have run, like
+ `stored_expression_error` below -- and `probe_sql_is_evaluable` on the way
+ out.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ bindable = _placeholder_is_bindable(transform)
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ elif bindable:
+ # Every other colon escaped first: `text()` would read one inside a
+ # string literal as a second bind parameter and render it `NULL`.
+ # See `escape_foreign_colons`.
+ clause = sa.text(escape_foreign_colons(transform)).bindparams(
+ sa.bindparam("value", value=value)
+ )
+ rendered = _compile_literal(clause, dialect)
+ else:
+ # `text()` cannot see the placeholder (see
+ # `_placeholder_is_bindable`), so the value is rendered by the
+ # dialect's own literal processor first and substituted as SQL
+ # text. The same two steps in the other order: binding exists to
+ # get the value through that processor, and `_compile_literal`
+ # inlines the result either way, so this is the same string by a
+ # different route -- not a loosening of the "never interpolate a
+ # raw value" rule. `parse_skeleton` substitutes literally, so the
+ # rendered literal arrives here exactly as it was rendered, which
+ # is what makes `literal_round_trips`' verdict on it good for this
+ # branch as much as for the bound one.
+ rendered = parse_skeleton(
+ transform, _compile_literal(sa.literal(value), dialect)
+ )
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Five things have to hold, and all five are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+ * No comment, anywhere. A value that closes its own quote has to hide the
+ text `build_probe_sql` appended after it, and a comment is the only way
+ to do that and still balance the quotes -- so this is what makes the
+ alias check above sufficient rather than merely necessary. Read off the
+ parse rather than the text, so a comment *inside* a literal is data and
+ costs no pruning, and so the question is asked in the engine's own
+ dialect. A transform has no legitimate reason to carry one either; see
+ `EXECUTABLE_COMMENT_RE`.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ # Before the parse, because this gate's whole contract is that what the
+ # parse describes is what the engine will run, and an executable comment is
+ # precisely the text where that stops being true. The transform is already
+ # refused for carrying one; this covers the compiled statement, so no later
+ # change to how values are rendered can reintroduce it behind the gates
+ # below.
+ if contains_executable_comment(sql) or contains_unicode_escaped_identifier(sql):
+ return False
+
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if not isinstance(statement, SQLStatement):
+ # A dialect whose statements this gate cannot take apart -- KQL -- gets
+ # no probe rather than an unchecked one. It never had one: the clause
+ # inspection below is implemented for SQL statements only, and the
+ # alternative to declining here is an `AttributeError` that `_probe`
+ # swallows into the same outcome, less legibly.
+ return False
+ if statement.has_comment():
+ return False
+ if statement.has_subquery():
+ return False
+ if statement.get_clause_names() - {"from"}:
+ return False
+ if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+ """
+ The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+ Parsed rather than string-compared so that the comparison in
+ `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+ not parse answers ``None``, which no statement carrying a FROM can match --
+ the probe then declines, which is the right way for an unreadable engine
+ constant to fail.
+ """
+ if not from_suffix.strip():
+ return None
+ try:
+ return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+ except SupersetParseError:
+ return None
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ # The value side of the premise `probe_sql_is_evaluable` checks on the
+ # finished statement: a value the driver and the engine would spell
+ # differently is not probed at all -- see `literal_round_trips`.
+ #
+ # `ExploreMixin.mirror_probe_request` declines one earlier, with a reason
+ # the preview can explain, and that is the gate an owner sees. This is the
+ # one that cannot be walked around. `_collect_partition_mirror_range`
+ # appends its bounds into the sink without passing through that method at
+ # all, and both paths can hand back a value the gate never saw: on a column
+ # carrying a `python_date_format`, what is probed is
+ # `strftime(that format)` -- text no mapping gate has ever read.
+ #
+ # Above `_run_probe` on purpose. This is a property of one input, not of
+ # the transform, and a verdict recorded here would withdraw the mirror for
+ # every later value of a transform the engine evaluates perfectly well.
+ dialect = _dialect_for(database)
+ if not all(
+ literal_round_trips(value, dialect, database.backend) for value in distinct
+ ):
+ logger.warning(
+ "A filter value is not written the same way by the driver and the "
+ "database, so the partition transform is not probed at it; this "
+ "query will not prune"
+ )
+ return None
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+
+ The verdict is about the *transform*: whether the engine evaluated it at
+ all. A ``NULL`` among the results is not that -- it is this input's answer,
+ and `NULLIF(:value, 0)` returning ``NULL`` for ``n = 0`` says nothing about
+ the same transform on ``n = 2``. Counting it withdrew the promise for the
+ whole transform, and nothing restored it: a *failed* probe is deliberately
+ not cached, so the next chart re-probes and re-records, but a ``NULL`` is a
+ successful probe and *is* cached -- so the false verdict outlived every
+ later hit, and the editor reported a working mapping as not mirroring
+ while the query went on pruning. The per-input skip still happens where it
+ belongs, in the caller's own ``NULL`` guard.
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=values is not None,
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ from_suffix = database.db_engine_spec.select_without_from_suffix
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ from_suffix,
+ )
+ if not probe_sql_is_evaluable(
+ sql, database.backend, len(distinct), from_suffix
+ ):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _execution_identity(database: Database) -> str | None:
+ """
+ Who the warehouse will run the probe as, when that can vary by caller.
+
+ `_probe_cache_key` keys on the `Database` record, which is the *connection*
+ -- not the identity it is opened under. Two hooks make that identity a
+ function of the Superset user instead:
+
+ * ``impersonate_user`` on the database, which hands the effective username
+ to `db_engine_spec.impersonate_user`;
+ * ``DB_CONNECTION_MUTATOR``, which receives the effective username and may
+ return an entirely different account's URL.
+
+ Under either one, a cached probe result computed under user A's grants was
+ served to user B, and the preview echoed it back in ``emitted_predicate``.
+ A transform wrapping a read-capable function the denylist does not name --
+ Oracle's ``DBMS_XMLGEN.GETXML`` is the worked example -- then leaks across
+ users who were never allowed the same rows.
+
+ Returns ``None`` when neither hook is configured, which is the common case
+ and deliberately leaves the key as it was: the cache exists to keep a
+ synchronous warehouse round trip off the chart-query path, and keying every
+ deployment on the username would cost every deployment the hit rate to fix
+ the two that need it.
+
+ The *Superset* username rather than the resolved warehouse account, because
+ it is the input both hooks branch on, and reading it needs no URL parse and
+ puts no credential in the key.
+ """
+ if not (database.impersonate_user or app.config["DB_CONNECTION_MUTATOR"]):
+ return None
+ return get_username()
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
Review Comment:
`hashlib.md5` here raises `ValueError` on a FIPS-mode OpenSSL build, and `_probe_cache_key` is called from `evaluate_transform` with no surrounding try. With `PARTITION_FILTER_MAPPING` on, any chart filtering on a mapped column (and the preview endpoint) would then return a 500 instead of just skipping pruning, which contradicts the module's "a failure costs pruning, never correctness" promise. Could this use `superset.utils.hashing` (or `usedforsecurity=False`) like the rest of the codebase?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4200141981
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/PartitionColumnFields.tsx:
##########
@@ -0,0 +1,319 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { useMemo } from 'react';
+import { t } from '@apache-superset/core/translation';
+import { css, useTheme } from '@apache-superset/core/theme';
+import { Alert } from '@apache-superset/core/components';
+import {
+ Button,
+ Flex,
+ Icons,
+ InfoTooltip,
+ Label,
+ Select,
+ Tooltip,
+ Typography,
+} from '@superset-ui/core/components';
+import {
+ mappedColumnIsImplicit,
+ mappingIsActive,
+ partitionMappingErrors,
+ resolveMappedColumn,
+ suggestedMappedColumn,
+} from './utils';
+import type {
+ PartitionMappingColumn,
+ PartitionMappingDatasource,
+ PartitionMappingIssue,
+} from './types';
+
+interface PartitionColumnFieldsProps {
+ datasource: PartitionMappingDatasource;
+ /**
+ * Physical columns: what the partition-column dropdown may offer, and where
+ * a replacement mapped column may be suggested from. A calculated column
+ * belongs in neither -- the engine cannot partition on an expression, and
+ * the mapping picker only renders on a physical column's row.
+ */
+ columns: PartitionMappingColumn[];
+ /**
+ * Every column on the dataset, physical and calculated. What *exists* is a
+ * different question from what may be picked, and validation asks the first:
+ * the backend accepts a calculated column as the mapped-column override, so
+ * checking existence against the physical columns alone reported a column
+ * that is really there as missing -- and blocked Save with no way out, since
+ * the dropdown cannot offer it back.
+ */
+ allColumns: PartitionMappingColumn[];
+ onPartitionColumnChange: (columnName: string | null) => void;
+ /** Open the given column's row expand in the Columns table. */
+ onNavigateToColumn: (columnName: string) => void;
+ /**
+ * Whether the mapped column's own preview says the transform mirrors, or
+ * `null`/undefined when no verdict is in yet. The checks this section can
+ * make are all static -- a transform the database rejects clears every one
+ * of them -- so without the preview's answer the banner claimed a speed-up
+ * the query never delivers.
+ */
+ previewMirrors?: boolean | null;
+}
+
+/**
+ * "Partition column" and the computed "Maps to partition" (wireframes 1a, 1g).
+ *
+ * "Maps to partition" is deliberately read-only. It reflects
+ * `partition_mapped_column ?? main_dttm_col`, and a peer dropdown would let it
+ * drift from the default datetime column silently. The only way to override it
+ * is from the target column's own row, where a transform has to be supplied
+ * alongside.
+ */
+export default function PartitionColumnFields({
+ datasource,
+ columns,
+ allColumns,
+ onPartitionColumnChange,
+ onNavigateToColumn,
+ previewMirrors,
+}: PartitionColumnFieldsProps) {
+ const theme = useTheme();
+
+ const options = useMemo(
+ () =>
+ columns.map(column => ({
+ value: column.column_name,
+ label: column.column_name,
+ customLabel: (
+ <Flex align="center" gap={theme.sizeUnit}>
+ <span>{column.column_name}</span>
+ {column.type && <Label>{column.type}</Label>}
+ </Flex>
+ ),
+ })),
+ [columns, theme.sizeUnit],
+ );
+
+ const mappedColumn = resolveMappedColumn(datasource);
+ const isImplicit = mappedColumnIsImplicit(datasource);
+ // The static checks are necessary, not sufficient: an unparseable expression
+ // or a function the database does not have needs the engine to spot, and the
+ // mapped column's row already asks it. Deferring to that answer where there
+ // is one is what keeps this banner and that panel from contradicting each
+ // other. A stored transform whose last probe failed says the same thing
+ // through the datasource's own summary, which is what an owner sees on
+ // reopening the editor.
+ const isActive =
+ mappingIsActive(datasource, allColumns) &&
+ previewMirrors !== false &&
+ datasource.partition_filter_mapping?.evaluable !== false;
+ const { partition_column: partitionColumn } = datasource;
+
+ // `field` is what the issues carry it for: a message about the partition
+ // column belongs under the partition column, not only in the Save button's
+ // tooltip, where an owner has to guess which of the two selects is at fault.
+ const issues = useMemo(
+ () => partitionMappingErrors(datasource, allColumns),
+ [datasource, allColumns],
+ );
+ const issueFor = (field: PartitionMappingIssue['field']) =>
+ issues.find(issue => issue.field === field)?.message;
+
+ // "Map a different column instead" normally opens the currently-mapped
+ // column's row, which is where the picker lives. When the mapped column *is*
+ // the partition column -- the self-mapping the backend rejects, and reachable
+ // in one click because the picker offers every column -- that row renders no
+ // mapping section at all, so the one guided way out of the broken state led
+ // nowhere. Offer a column that is not the partition column instead.
+ //
+ // Null only when there is no mapped column at all, which is also when the
+ // block below does not render -- but a dataset whose every column is the
+ // partition column would otherwise be offered a link to nothing, so the link
+ // is guarded rather than the type asserted away.
+ const differentColumnTarget =
+ mappedColumn && mappedColumn !== partitionColumn
+ ? mappedColumn
+ : (suggestedMappedColumn(columns, partitionColumn) ?? mappedColumn);
+
+ return (
+ <Flex vertical gap={theme.sizeUnit} data-test="partition-column-fields">
+ <Flex align="center" gap={theme.sizeUnit}>
+ <Typography.Text>{t('Partition column')}</Typography.Text>
+ <InfoTooltip
+ tooltip={t(
+ 'The physical column the engine partitions on. Filters on the mapped column are mirrored onto it so the engine can prune partitions.',
+ )}
+ />
+ </Flex>
+ <Select
+ ariaLabel={t('Partition column')}
+ options={options}
+ value={partitionColumn ?? undefined}
+ onChange={value => onPartitionColumnChange((value as string) ?? null)}
+ onClear={() => onPartitionColumnChange(null)}
+ placeholder={t('None')}
+ allowClear
+ data-test="partition-column-select"
+ />
+ {issueFor('partition_column') && (
+ <Typography.Text type="danger" data-test="partition-column-error">
+ {issueFor('partition_column')}
+ </Typography.Text>
+ )}
+ <Typography.Text type="secondary">
+ {t(
+ "Column used for partition pruning on this table. Selecting one hides it from Explore's dimension and filter pickers by default.",
+ )}
+ </Typography.Text>
+
+ {partitionColumn && (
+ <Flex vertical gap={theme.sizeUnit} data-test="maps-to-partition">
+ <Flex align="center" gap={theme.sizeUnit}>
+ <Typography.Text type="secondary">
+ {t('Maps to partition')}
+ </Typography.Text>
+ <InfoTooltip
+ tooltip={t(
+ 'The column whose filters are mirrored. It follows the default datetime column unless a different column holds the mapping.',
+ )}
+ />
+ </Flex>
+
+ {mappedColumn ? (
+ <>
+ <Flex align="center" gap={theme.sizeUnit}>
+ <Label>{mappedColumn}</Label>
+ {isImplicit && (
+ <>
+ <Typography.Text type="secondary">
+ {t('Default datetime column')}
+ </Typography.Text>
+ <Tooltip
+ title={t(
+ 'Set from the default datetime column above, so re-pointing that column moves the mapping with it.',
+ )}
+ >
+ <Icons.LockOutlined
+ iconSize="s"
+ iconColor={theme.colorTextTertiary}
+ />
+ </Tooltip>
+ </>
+ )}
+ </Flex>
+ {issueFor('partition_mapped_column') && (
+ <Typography.Text
+ type="danger"
+ data-test="partition-mapped-column-error"
+ >
+ {issueFor('partition_mapped_column')}
+ </Typography.Text>
+ )}
+ <Typography.Text type="secondary">
+ {t(
+ 'Filters on this column are mirrored onto the partition column.',
+ )}
+ {differentColumnTarget && (
+ <>
+ {' '}
+ <Button
+ buttonStyle="link"
+ onClick={() => onNavigateToColumn(differentColumnTarget)}
+ data-test="map-a-different-column"
+ >
+ {t('Map a different column instead →')}
+ </Button>
+ </>
+ )}
+ </Typography.Text>
+ {isActive ? (
+ <Alert
+ type="info"
+ showIcon
+ icon={<Icons.FilterOutlined />}
+ message={
+ <span>
+ {t(
+ 'Filters on %(mapped)s will automatically apply an equivalent filter to %(partition)s.',
+ { mapped: mappedColumn, partition: partitionColumn },
+ )}{' '}
+ <Button
+ buttonStyle="link"
+ onClick={() => onNavigateToColumn(mappedColumn)}
+ >
+ {t('Customize the value transform →')}
+ </Button>
+ </span>
+ }
+ />
+ ) : (
+ <Alert
+ type="warning"
+ showIcon
+ message={t(
+ 'No value transform is set on %(mapped)s, so nothing is mirrored yet and queries will scan every partition.',
+ { mapped: mappedColumn },
+ )}
+ />
+ )}
+ </>
+ ) : (
+ <>
+ <Flex align="center" gap={theme.sizeUnit}>
+ <Label
+ css={css`
+ color: ${theme.colorTextTertiary};
+ `}
+ >
+ {t('No mapping')}
+ </Label>
+ <Button
+ buttonStyle="link"
+ onClick={() => {
+ const candidate = suggestedMappedColumn(
+ columns,
+ partitionColumn,
+ );
+ if (candidate) {
+ onNavigateToColumn(candidate);
+ }
+ }}
+ data-test="map-a-column"
+ >
+ {t('Map a column →')}
+ </Button>
+ </Flex>
+ <Typography.Text type="secondary">
+ {t(
+ 'Normally the default datetime column, but none is set on this dataset.',
+ )}
+ </Typography.Text>
+ <Alert
+ type="warning"
+ showIcon
+ message={t(
+ '%(partition)s is hidden from Explore, but no filter is mirrored onto it — queries will scan every partition until a column is mapped.',
Review Comment:
Designating a partition column no longer clears its `filterable`/`groupby` flags, so this warning now tells the owner a column is hidden from Explore while it is still offered there.
```suggestion
'No filter is mirrored onto %(partition)s — queries will scan every partition until a column is mapped.',
```
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2395 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+#: Returned by `ExploreMixin.mirror_probe_request` for a filter no mirror can
+#: stand in for: one the engine compares more coarsely than the value carries, a
+#: value it cannot render as a literal, or an ``IN`` list with a member of
+#: either kind. A sentinel rather than `None`, because `None` is a filter value
+#: in its own right.
+#:
+#: Lives here rather than beside that method so the preview can read it too:
+#: `superset.models.helpers` imports this module, so the sentinel can only cross
+#: the boundary in this direction. Both callers have to recognise the same
+#: object -- a preview that answered "valid" for a request the chart path
+#: declines is the drift this is here to prevent.
+UNMIRRORABLE = object()
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error(
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the probe
+ uninspected -- string elements are escaped by the dialect's own literal
+ processor. `probe_sql_is_evaluable` then re-reads the finished query, which
+ is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ else:
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ rendered = _compile_literal(clause, dialect)
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Four things have to hold, and all four are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if not isinstance(statement, SQLStatement):
+ # A dialect whose statements this gate cannot take apart -- KQL -- gets
+ # no probe rather than an unchecked one. It never had one: the clause
+ # inspection below is implemented for SQL statements only, and the
+ # alternative to declining here is an `AttributeError` that `_probe`
+ # swallows into the same outcome, less legibly.
+ return False
+ if statement.has_subquery():
+ return False
+ if statement.get_clause_names() - {"from"}:
+ return False
+ if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+ """
+ The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+ Parsed rather than string-compared so that the comparison in
+ `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+ not parse answers ``None``, which no statement carrying a FROM can match --
+ the probe then declines, which is the right way for an unreadable engine
+ constant to fail.
+ """
+ if not from_suffix.strip():
+ return None
+ try:
+ return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+ except SupersetParseError:
+ return None
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=values is not None and not any(value is None for value in values),
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ from_suffix = database.db_engine_spec.select_without_from_suffix
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ from_suffix,
+ )
+ if not probe_sql_is_evaluable(
+ sql, database.backend, len(distinct), from_suffix
+ ):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _mirror_verdict_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str:
+ """
+ `_probe_cache_key` without the values.
+
+ Whether a transform can be evaluated at all is a property of the transform
+ and the connection, not of the filter that happened to be probing it, so
+ one chart's answer settles the question for the next one.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_verdict:{digest}"
+
+
+def record_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ *,
+ mirrors: bool,
+) -> None:
+ """
+ Remember whether this transform produced a mirror, for the UI to read.
+
+ Advisory only. Nothing in the query path consults it: a probe that failed
+ once is retried on the next chart exactly as it is today, because declining
+ to prune for a whole cache timeout over one transient engine blip is the
+ trade `evaluate_transform` deliberately refuses -- see the comment where it
+ declines to cache a failure.
+
+ What this is for is the *claim*. `is_transform_active` parses the transform
+ and no more, so a transform the database rejects -- a misspelled function
+ is the common case -- is "active", and the editor's banner and Explore's
+ pruning glyph promise a speed-up that never happens. A promise is exactly
+ the thing that may be withheld on one bad answer and restored on a good
+ one, which is why this is a separate entry from the probe's own results
+ rather than a relaxation of that rule.
+
+ Written by `_run_probe`, so the preview endpoint -- which shares the
+ evaluator -- settles the question before the owner has even saved.
+ """
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(
+ _mirror_verdict_cache_key(database, catalog, schema, transform),
+ mirrors,
+ timeout=timeout,
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform verdict", exc_info=True)
+
+
+def known_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> bool | None:
+ """
+ The last verdict `record_mirror_verdict` stored, or `None` if there is none.
+
+ `None` is the honest answer on a cold cache and is deliberately not `False`:
+ reporting a working mapping as broken until something probes it would
+ trade one wrong claim for another. The alternative -- probing from the
+ read side -- would put a warehouse round trip on every Explore and
+ dashboard load, and a failing transform is not cached at all, so it would
+ be a round trip every single time.
+ """
+ try:
+ verdict = cache_manager.cache.get(
+ _mirror_verdict_cache_key(database, catalog, schema, transform)
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return verdict if isinstance(verdict, bool) else None
+
+
+def _compile_literal(element: Any, dialect: Dialect | None) -> str:
+ """
+ Compile with inline literals, undoing the paramstyle's percent doubling.
+
+ Both ``TextClause`` and literal compilation run the dialect's
+ ``post_process_text``, which doubles every ``%`` whenever the identifier
+ preparer asks it to -- true for MySQL and Postgres and for every spec
+ inheriting their paramstyle. That doubling exists so a later DBAPI
+ parameter-interpolation pass can undo it, and the probe has no such pass:
+ it executes with no bound parameters at all. So a transform of
+ ``date_format(:value, '%Y%m%d')`` reaches the warehouse asking for the
+ literal string ``%%Y%%m%%d``, the probe returns that instead of a date, and
+ the mirrored predicate drops every row the filter keeps.
+
+ The same normalization ``Database.compile_sqla_query`` applies for the same
+ reason. ``_double_percents`` is private and not guaranteed on a third-party
+ dialect, hence the ``getattr`` default.
+ """
+ compiled = str(
+ element.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
+ )
+ if dialect is not None and getattr(
+ dialect.identifier_preparer, "_double_percents", False
+ ):
+ compiled = compiled.replace("%%", "%")
+ return compiled
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be *asked* to stand in for itself, and the transform
+ cannot carry Jinja or call a non-deterministic function. Tier 2
+ (``blocking=False``) is everything that merely leaves the mapping inactive
+ -- including a self-mapping nobody asked for, where the partition column
+ merely happens to be the default datetime column.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column == partition_column:
+ # Asked for explicitly, so report it as the mistake it is.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+ elif not partition_mapped_column and main_dttm_col == partition_column:
+ # Resolved onto itself only because the default datetime column happens
+ # to be the partition column -- a state metadata sync could produce
+ # without anyone asking for it. The mapping is inert either way, since
+ # `resolve_partition_mapping` bails out on it, so this reports and lets
+ # the write through: blocking here means a dataset already in the state
+ # can never be saved again, not even to change its description, and
+ # there is no field whose edit would clear the error first.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "%(name)s is both the partition column and the default "
+ "datetime column, so the mapping points at itself and "
+ "stays inactive. Set a mapped column override, or change "
+ "the default datetime column.",
+ name=partition_column,
+ ),
+ blocking=False,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_bare_expression(transform, engine):
+ # Blocking, and deliberately placed in `validate_transform` rather than
+ # only at the probe: one issue here closes the PUT, the importer, the
+ # query-time gate through `is_transform_active`, the Explore indicator's
+ # active verdict and the preview endpoint, all of which already consult
+ # this function.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform must be a single SQL expression. It "
+ "cannot carry a FROM, WHERE, GROUP BY or any other clause, "
+ "and it cannot contain a sub-query."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not contains_value_placeholder(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform must contain the :value placeholder, "
+ "which stands for the filter value being mirrored."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not placeholder_is_executable(transform, engine):
+ # Blocking, and for the same reason the shape gate above is: this is
+ # the function the PUT, the importer, `is_transform_active`, the
+ # Explore indicator and the preview all consult, so one issue here
+ # closes every door at once. A placeholder inside a string literal is
+ # a sub-query the engine will run once a filter value closes the quote;
+ # one inside a comment silently eats the probe's own alias.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The :value placeholder must appear where the engine will "
+ "evaluate it. It cannot sit inside a string literal or a "
+ "comment."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if functions := find_non_deterministic_functions(transform, engine):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform calls %(functions)s, whose result "
+ "depends on when and where it runs. The transform is "
+ "evaluated in a separate session and the result is cached, "
+ "so the emitted predicate would freeze a snapshot of that "
+ "moment.",
+ functions=", ".join(sorted(functions)),
+ ),
+ blocking=True,
+ )
+ ]
+
+ return []
+
+
+@lru_cache(maxsize=LRU_CACHE_MAX_SIZE)
+def is_transform_active(transform: str | None, engine: str) -> bool:
+ """
+ Whether Superset will mirror filters through this transform.
+
+ `validate_transform` with the messages discarded, so the Explore indicator
+ cannot advertise a mapping the save path recorded as inactive. Anything
+ cheaper here would be a second, weaker statement of the same rule, free to
+ drift from the one the save path applies.
+
+ Blocking issues count too. Jinja and non-deterministic transforms are
+ rejected on PUT, but `CreateDatasetCommand` and import do not validate the
+ mapping, so one can still reach the database -- and it would never mirror a
+ filter either.
+
+ Memoized because `partition_filter_mapping_summary` is serialized on every
+ Explore and dashboard load and this parses the transform. The key is
+ everything the answer depends on: `validate_transform` reads no session, no
+ locale and no config beyond `SQL_MAX_PARSE_LENGTH`, which bounds the parser
+ rather than changing a verdict within that bound.
+ """
+ return not validate_transform(transform, engine)
+
+
+def preview_partition_mapping( # pylint: disable=too-many-return-statements
+ datasource: SqlaTable,
+ *,
+ mapped_column: str,
+ value_transform: str | None,
+ sample_values: list[str],
+ operator: FilterOperator = FilterOperator.EQUALS,
+ is_monotonic: bool = False,
+ partition_column: str | None = None,
+) -> dict[str, Any]:
+ """
+ Evaluate a candidate mapping and describe the predicate it would emit.
+
+ Shares the evaluator -- and therefore the probe cache -- with the query
+ path, so preview and runtime cannot drift and a previewed transform warms
+ the chart path for free. The predicate itself comes from
+ `build_mirrored_predicates`, the same builder the query path uses, so
+ operator shapes cannot drift either: what the panel shows is what a chart
+ would emit.
+
+ Validation runs first and the engine second: a half-typed transform is by
+ definition unparseable, so most of what a text input produces costs zero
+ queries.
+
+ Every part of the mapping is taken from the request rather than the stored
+ dataset. The editor previews while the owner is still editing -- a mapping
+ that has to be saved before it can be checked is not a preview.
+ """
+ partition_column = partition_column or datasource.partition_column
+ if not partition_column:
+ return {
+ "valid": False,
+ "reason": "unconfigured",
+ "error": _("No partition column is set."),
+ }
+
+ columns_by_name = {str(column.column_name): column for column in datasource.columns}
+ if mapped_column not in columns_by_name:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _("%(name)s is not a column on this dataset.", name=mapped_column),
+ }
+
+ # The bail-out `resolve_partition_mapping` makes at query time, and that
+ # `partition_filter_mapping_summary` repeats for the Explore indicator.
+ # Without it here, preview reports a valid emitted predicate for a mapping
+ # no chart will ever mirror -- the one answer a preview panel must not give.
+ if has_active_advanced_data_type(columns_by_name[mapped_column]):
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _(
+ "%(name)s has an advanced data type, so its filters are "
+ "translated into their own predicate shape and cannot be "
+ "mirrored onto the partition column.",
+ name=mapped_column,
+ ),
+ }
+
+ engine = datasource.database.backend
+ for issue in validate_partition_mapping(
+ column_names=set(columns_by_name),
+ partition_column=str(partition_column),
+ partition_mapped_column=mapped_column,
+ main_dttm_col=datasource.main_dttm_col,
+ transform=value_transform,
+ engine=engine,
+ ):
+ return {
+ "valid": False,
+ # The parse failure is the one an owner sees constantly, and it is
+ # the only one the mockup gives its own headline to.
+ "reason": (
+ "parse"
+ if issue.field == "partition_value_transform"
+ and not is_parseable(value_transform, engine)
+ else "validation"
+ ),
+ "error": str(issue.message),
+ }
+
+ # The policy every other stored expression goes through. The save path
+ # applies it in `UpdateDatasetCommand._validate_partition_mapping`, but
+ # preview evaluates a candidate transform that has not been saved, so
+ # without this the gate had a door around it. See
+ # `stored_expression_error` for what is being kept out and why.
+ if reason := stored_expression_error(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ cast(str, value_transform),
+ ):
+ return {"valid": False, "reason": "validation", "error": reason}
+
+ mapping = PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=mapped_column,
+ value_transform=cast(str, value_transform),
+ is_monotonic=is_monotonic,
+ equality_is_safe=equality_mirrors_safely(
+ columns_by_name[mapped_column], datasource.database.db_engine_spec
+ ),
+ )
+ sample_input = _render_sample_input(
+ datasource, mapped_column, operator, sample_values
+ )
+
+ if operator not in PREVIEWABLE_OPERATORS:
+ # Checked before `mirrors`, which lets `TEMPORAL_RANGE` through when the
+ # transform is declared monotonic -- and the single sample value would
+ # then reach `handle_comparison_filter`, which has no case for a range
+ # and raises. The request schema rejects it too; this keeps the function
+ # honest for any other caller.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is mirrored as a pair of bounds, which "
+ "a preview of a single value cannot describe.",
+ operator=operator.value,
+ ),
+ }
+
+ if not mapping.mirrors(operator):
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is only mirrored when the transform "
+ "preserves ordering, which this one is not declared to do.",
+ operator=operator.value,
+ ),
+ }
+
+ return _preview_probe(
+ datasource,
+ mapping,
+ columns_by_name[mapped_column],
+ operator,
+ sample_values,
+ sample_input,
+ )
+
+
+def _preview_probe(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ mapped_col: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+ sample_input: str,
+) -> dict[str, Any]:
+ """
+ The half of a preview that needs the warehouse.
+
+ Split out from `preview_partition_mapping` so that the gates which answer
+ from the stored mapping alone stay readable as the single run of guard
+ clauses they are. Everything here has either run a query or decided not to.
+ """
+ value = datasource.mirror_probe_request(
+ operator,
+ _probe_input(datasource, mapped_col, operator, sample_values),
+ mapped_col,
+ )
+ if value is UNMIRRORABLE:
+ # The same step the chart path applies, so the preview cannot promise a
+ # mirror the query declines. Its own reason: the transform is fine and
+ # the engine evaluates it, the filter just carries more of the value
+ # than the engine compares on this column -- which is the column's type
+ # talking, not a broken expression.
+ return {
+ "valid": False,
+ "reason": "resolution",
+ "sample_input": sample_input,
+ "error": _(
+ "This engine compares less of a %(operator)s value on "
+ "%(column)s than the filter carries, so there is no mirror a "
+ "predicate on the partition column could stand in for. Map a "
+ "column the engine compares in full to mirror this operator.",
+ operator=operator.value,
+ column=mapped_col.column_name,
+ ),
+ }
+ errors: list[str] = []
+ type_errors: list[str] = []
+ predicates = build_mirrored_predicates(
+ datasource,
+ mapping,
+ [(operator, value)],
+ errors=errors,
+ type_errors=type_errors,
+ )
+ if type_errors:
+ # Its own reason, because "the database would not evaluate this" and
+ # "it evaluated and answered with the wrong kind of thing" are
+ # different problems with different fixes, and the owner is the only
+ # one who can tell which transform they meant to write.
+ return {
+ "valid": False,
+ "reason": "type",
+ "sample_input": sample_input,
+ "error": type_errors[0],
+ }
+ if not predicates:
+ return {
+ "valid": False,
+ "reason": "engine",
+ "sample_input": sample_input,
+ "error": (
+ _(
+ "The transform could not be evaluated against the "
+ "database: %(reason)s",
+ reason=errors[0],
+ )
+ if errors
+ else _("The transform could not be evaluated against the database.")
+ ),
+ }
+
+ return {
+ "valid": True,
+ "sample_input": sample_input,
+ "emitted_predicate": _render_predicate(datasource, predicates[0]),
+ }
+
+
+def _probe_input(
+ datasource: SqlaTable,
+ column: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+) -> Any:
+ """
+ The sample values as the query path would bind them.
+
+ The request carries samples as strings, and the probe is keyed on exactly
+ what it is handed, so passing them through raw asks the engine a different
+ question from the one a chart asks. A sample of ``2025`` on a numeric
+ column has to arrive as the integer the chart compares: under a transform
+ of ``typeof(:value)`` the raw string previewed ``'text'`` where the chart
+ emitted ``'integer'``. And because `_probe_cache_key` keys on each value's
+ ``repr``, the two also missed each other's cache entirely -- so the "a
+ previewed transform warms the chart path for free" claim in
+ `preview_partition_mapping`'s docstring did not actually hold.
+
+ Coerced by `filter_values_handler`, the same function the query path uses,
+ rather than by a second implementation of the same rules. Everything the
+ query path then does to the coerced value -- rendering an expression as a
+ literal, widening a bound, declining a comparison the engine resolves too
+ coarsely -- is `ExploreMixin.mirror_probe_request`'s, and the caller hands
+ this result straight to it.
+
+ Ranges are not previewable (see `PREVIEWABLE_OPERATORS`), so the bound
+ conversion `_collect_partition_mirror_range` applies -- a ``datetime`` into
+ the column's stored representation -- has no counterpart here.
+
+ :returns: `UNMIRRORABLE` where the samples cannot be coerced at all
Review Comment:
`_probe_input` always returns `handled` and never `UNMIRRORABLE`; the decline happens in `mirror_probe_request`.
```suggestion
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4162516989
##########
superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterOption/AdhocFilterOption.test.tsx:
##########
@@ -108,3 +108,115 @@ test('should render the Popover on clicking the right caret', async () => {
await userEvent.click(rightCaret);
expect(screen.getByRole('tooltip')).toBeInTheDocument();
});
+
+// A monotonic transform, so ranges mirror alongside equality.
+const MONOTONIC_MAPPING = {
+ partition_column: 'dt_epoch',
+ mapped_column: 'value',
+ active: true,
+ is_monotonic: true,
+ mirrorable_operators: ['<', '<=', '==', '>', '>=', 'IN', 'TEMPORAL_RANGE'],
+};
+
+const withMapping = (
+ mapping: Record<string, unknown> | null,
+ adhocFilter = simpleAdhocFilter,
+) =>
+ setup({
+ ...mockedProps,
+ adhocFilter,
+ datasource: { partition_filter_mapping: mapping },
+ });
+
+const glyph = () => screen.queryByTestId('partition-pruning-indicator');
+
+test('a filter on the mapped column carries the partition pruning glyph', () => {
+ // Wireframe 1d: the chart author never configured any of this and only sees
+ // an explanation of why the query got faster.
+ render(withMapping(MONOTONIC_MAPPING));
+
+ expect(glyph()).toBeInTheDocument();
+});
+
+test('a filter on any other column carries no glyph', () => {
+ render(
+ withMapping({ ...MONOTONIC_MAPPING, mapped_column: 'some_other_column' }),
+ );
+
+ expect(glyph()).not.toBeInTheDocument();
+});
+
+test('an inactive mapping leaves the chip alone', () => {
+ render(withMapping({ ...MONOTONIC_MAPPING, active: false }));
+
+ expect(glyph()).not.toBeInTheDocument();
+});
+
+test('a negated filter on the mapped column carries no glyph', () => {
+ // The query path never mirrors a negation -- the transform need not be
+ // injective, so `value != 10` would mirror to a predicate that drops rows the
+ // original filter keeps. Labelling it would promise a speed-up the SQL does
+ // not contain.
+ render(
+ withMapping(
+ MONOTONIC_MAPPING,
+ simpleAdhocFilter.duplicateWith({ operator: '!=' }),
+ ),
+ );
+
+ expect(glyph()).not.toBeInTheDocument();
+});
+
+test('a range filter waits on the monotonicity declaration', () => {
+ render(
+ withMapping({
+ ...MONOTONIC_MAPPING,
+ is_monotonic: false,
+ mirrorable_operators: ['==', 'IN'],
+ }),
+ );
+
+ expect(glyph()).not.toBeInTheDocument();
+});
+
+test('an equality filter mirrors under a non-monotonic transform', () => {
+ render(
+ withMapping(
+ {
+ ...MONOTONIC_MAPPING,
+ is_monotonic: false,
+ mirrorable_operators: ['==', 'IN'],
+ },
+ simpleAdhocFilter.duplicateWith({ operator: '==' }),
+ ),
+ );
+
+ expect(glyph()).toBeInTheDocument();
+});
+
+test('a free-form SQL filter on the mapped column carries no glyph', () => {
+ // It lands in `extras.where`, where the backend sees no operator to mirror.
+ render(
+ withMapping(
+ MONOTONIC_MAPPING,
+ new AdhocFilter({
+ expressionType: ExpressionTypes.Sql,
+ sqlExpression: 'value > 10',
+ clause: Clauses.Where,
+ }),
+ ),
+ );
+
+ expect(glyph()).not.toBeInTheDocument();
+});
+
+test('a filter with no comparator yet carries no glyph', () => {
+ render(
+ withMapping(
+ MONOTONIC_MAPPING,
+ simpleAdhocFilter.duplicateWith({ comparator: '' }),
+ ),
+ );
+
+ expect(glyph()).not.toBeInTheDocument();
+});
Review Comment:
Red at head: `1e132aefc9` flipped the `''` case in `PartitionPruningIndicator.test.tsx` but not this sibling, and `isValid()` accepts `''`, so the glyph is right and this test is stale. With the flip below the file is 14/14.
```suggestion
test('an empty-string comparator still carries the glyph', () => {
render(
withMapping(
MONOTONIC_MAPPING,
simpleAdhocFilter.duplicateWith({ comparator: '' }),
),
);
expect(glyph()).toBeInTheDocument();
});
```
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,1278 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` always -- ``T`` is a function
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import re
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLStatement
+from superset.utils import json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: Every entry point enforces it -- the typed column field, the import schema
+#: and the preview request -- because `is_transform_active` parses the stored
+#: value on each Explore load, and an unbounded string would make that parse
+#: the expensive part of rendering a chart.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+def mirrorable_operators(is_monotonic: bool) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ """
+ if is_monotonic:
+ return MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+ return set(MIRRORABLE_ALWAYS)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(self.is_monotonic)
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+ """
+ return VALUE_PLACEHOLDER_RE.sub(_PARSE_STANDIN, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(transform: str, engine: str) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+ """
+ selections = []
+ for index, value in enumerate(values):
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ compiled = clause.compile(
+ dialect=dialect,
+ compile_kwargs={"literal_binds": True},
+ )
+ selections.append(f"{compiled} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ try:
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ database.db_engine_spec.select_without_from_suffix,
+ )
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ row = frame.iloc[0]
+ if len(row) != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ len(row),
+ len(distinct),
+ )
+ return None
+ return [_to_python_scalar(row.iloc[index]) for index in range(len(distinct))]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be mapped onto itself, and the transform cannot carry
+ Jinja or call a non-deterministic function. Tier 2 (``blocking=False``) is
+ everything that merely leaves the mapping inactive.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ effective_mapped_column = partition_mapped_column or main_dttm_col
+ if effective_mapped_column and effective_mapped_column == partition_column:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not contains_value_placeholder(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform must contain the :value placeholder, "
+ "which stands for the filter value being mirrored."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if functions := find_non_deterministic_functions(transform, engine):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform calls %(functions)s, whose result "
+ "depends on when and where it runs. The transform is "
+ "evaluated in a separate session and the result is cached, "
+ "so the emitted predicate would freeze a snapshot of that "
+ "moment.",
+ functions=", ".join(sorted(functions)),
+ ),
+ blocking=True,
+ )
+ ]
+
+ return []
+
+
+@lru_cache(maxsize=LRU_CACHE_MAX_SIZE)
+def is_transform_active(transform: str | None, engine: str) -> bool:
+ """
+ Whether Superset will mirror filters through this transform.
+
+ `validate_transform` with the messages discarded, so the Explore indicator
+ cannot advertise a mapping the save path recorded as inactive. Anything
+ cheaper here would be a second, weaker statement of the same rule, free to
+ drift from the one the save path applies.
+
+ Blocking issues count too. Jinja and non-deterministic transforms are
+ rejected on PUT, but `CreateDatasetCommand` and import do not validate the
+ mapping, so one can still reach the database -- and it would never mirror a
+ filter either.
+
+ Memoized because `partition_filter_mapping_summary` is serialized on every
+ Explore and dashboard load and this parses the transform. The key is
+ everything the answer depends on: `validate_transform` reads no session, no
+ locale and no config beyond `SQL_MAX_PARSE_LENGTH`, which bounds the parser
+ rather than changing a verdict within that bound.
+ """
+ return not validate_transform(transform, engine)
+
+
+def preview_partition_mapping( # pylint: disable=too-many-return-statements
+ datasource: SqlaTable,
+ *,
+ mapped_column: str,
+ value_transform: str | None,
+ sample_values: list[str],
+ operator: FilterOperator = FilterOperator.EQUALS,
+ is_monotonic: bool = False,
+ partition_column: str | None = None,
+) -> dict[str, Any]:
+ """
+ Evaluate a candidate mapping and describe the predicate it would emit.
+
+ Shares the evaluator -- and therefore the probe cache -- with the query
+ path, so preview and runtime cannot drift and a previewed transform warms
+ the chart path for free. The predicate itself comes from
+ `build_mirrored_predicates`, the same builder the query path uses, so
+ operator shapes cannot drift either: what the panel shows is what a chart
+ would emit.
+
+ Validation runs first and the engine second: a half-typed transform is by
+ definition unparseable, so most of what a text input produces costs zero
+ queries.
+
+ Every part of the mapping is taken from the request rather than the stored
+ dataset. The editor previews while the owner is still editing -- a mapping
+ that has to be saved before it can be checked is not a preview.
+ """
+ partition_column = partition_column or datasource.partition_column
+ if not partition_column:
+ return {
+ "valid": False,
+ "reason": "unconfigured",
+ "error": _("No partition column is set."),
+ }
+
+ column_names = {str(column.column_name) for column in datasource.columns}
+ if mapped_column not in column_names:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _("%(name)s is not a column on this dataset.", name=mapped_column),
+ }
+
+ engine = datasource.database.backend
+ for issue in validate_partition_mapping(
+ column_names=column_names,
+ partition_column=str(partition_column),
+ partition_mapped_column=mapped_column,
+ main_dttm_col=datasource.main_dttm_col,
+ transform=value_transform,
+ engine=engine,
+ ):
+ return {
+ "valid": False,
+ # The parse failure is the one an owner sees constantly, and it is
+ # the only one the mockup gives its own headline to.
+ "reason": (
+ "parse"
+ if issue.field == "partition_value_transform"
+ and not is_parseable(value_transform, engine)
+ else "validation"
+ ),
+ "error": str(issue.message),
+ }
+
+ # The same subquery, function-denylist and RLS policy every other stored
+ # expression goes through. The save path applies it in
+ # `UpdateDatasetCommand._validate_partition_mapping`, but preview evaluates
+ # a candidate transform that has not been saved, so without this the gate
+ # had a door around it: `build_probe_sql` binds only `:value` and splices
+ # the rest of the transform in as SQL text, so a dataset editor without SQL
+ # Lab could submit `(SELECT secret FROM protected_table LIMIT 1) || :value`
+ # and read the answer back out of `emitted_predicate`.
+ #
+ # Imported here rather than at module scope: `connectors.sqla.models`
+ # imports this module, so the dependency only runs one way at import time.
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ try:
+ validate_stored_expression(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ parse_skeleton(cast(str, value_transform)),
+ )
+ except (SupersetSecurityException, QueryClauseValidationException) as ex:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": (
+ ex.error.message
+ if isinstance(ex, SupersetSecurityException)
+ else ex.message
+ ),
+ }
+
+ mapping = PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=mapped_column,
+ value_transform=cast(str, value_transform),
+ is_monotonic=is_monotonic,
+ )
+ sample_input = _render_sample_input(
+ datasource, mapped_column, operator, sample_values
+ )
+
+ if operator not in PREVIEWABLE_OPERATORS:
+ # Checked before `mirrors`, which lets `TEMPORAL_RANGE` through when the
+ # transform is declared monotonic -- and the single sample value would
+ # then reach `handle_comparison_filter`, which has no case for a range
+ # and raises. The request schema rejects it too; this keeps the function
+ # honest for any other caller.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is mirrored as a pair of bounds, which "
+ "a preview of a single value cannot describe.",
+ operator=operator.value,
+ ),
+ }
+
+ if not mapping.mirrors(operator):
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is only mirrored when the transform "
+ "preserves ordering, which this one is not declared to do.",
+ operator=operator.value,
+ ),
+ }
+
+ value: Any = sample_values if operator == FilterOperator.IN else sample_values[0]
+ errors: list[str] = []
+ predicates = build_mirrored_predicates(
+ datasource, mapping, [(operator, value)], errors=errors
+ )
+ if not predicates:
+ return {
+ "valid": False,
+ "reason": "engine",
+ "sample_input": sample_input,
+ "error": (
+ _(
+ "The transform could not be evaluated against the "
+ "database: %(reason)s",
+ reason=errors[0],
+ )
+ if errors
+ else _("The transform could not be evaluated against the database.")
+ ),
+ }
+
+ return {
+ "valid": True,
+ "sample_input": sample_input,
+ "emitted_predicate": _render_predicate(datasource, predicates[0]),
+ }
+
+
+def _render_sample_input(
+ datasource: SqlaTable,
+ mapped_column: str,
+ operator: FilterOperator,
+ values: list[str],
+) -> str:
+ """
+ The filter being previewed, written the way an owner would read it.
+
+ Display-only -- it is never executed -- but it is still read as SQL, so the
+ column is quoted and the values are rendered by the dialect rather than
+ concatenated raw. A column named ``order date`` would otherwise come out as
+ two bare words.
+ """
+ quoted = datasource.quote_identifier(mapped_column)
+ if operator == FilterOperator.IN:
+ rendered = ", ".join(
+ _render_literal(datasource.database, value) for value in values
+ )
+ return f"{quoted} IN ({rendered})"
+ return (
+ f"{quoted} {operator.value} {_render_literal(datasource.database, values[0])}"
+ )
+
+
+def _render_predicate(datasource: SqlaTable, predicate: ColumnElement[Any]) -> str:
+ """
+ Compile a mirrored predicate to the text a reader would see in View query.
+
+ Every value in it is a probed constant by this point, so ``literal_binds``
+ renders the same literals the chart query carries.
+ """
+ return str(
+ predicate.compile(
+ dialect=_dialect_for(datasource.database),
+ compile_kwargs={"literal_binds": True},
+ )
+ ).replace("\n", " ")
+
+
+def _render_literal(database: Database, value: Any) -> str:
+ """
+ Render a value the way it appears in the generated SQL.
+
+ Compiled by the dialect rather than formatted by hand. `str()` would render
+ a NULL as the Python repr `None` and leave a date unquoted, neither of which
+ is SQL, and hand-rolled quote-doubling would only ever have been right for
+ strings.
+ """
+ return str(
+ sa.literal(value).compile(
+ dialect=_dialect_for(database),
+ compile_kwargs={"literal_binds": True},
+ )
+ )
+
+
+def build_mirrored_predicates(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ requests: list[tuple[FilterOperator, Any]],
+ *,
+ errors: list[str] | None = None,
+) -> list[ColumnElement[Any]]:
+ """
+ Turn collected ``(operator, value)`` mirror requests into predicates.
+
+ ``requests`` is expected to be deduplicated by the caller. Every value is
+ resolved in a single probe round trip -- one per chart query at most -- then
+ emitted as a literal constant, so "View query" shows the reader an ordinary
+ ``WHERE`` clause rather than an inline expression.
+
+ :param errors: optional sink; see `evaluate_transform`.
+ """
+ if not requests:
+ return []
+
+ partition_column = next(
+ (
+ column
+ for column in datasource.columns
+ if column.column_name == mapping.partition_column
+ ),
+ None,
+ )
+ if partition_column is None:
+ return []
+
+ # Flatten every value that needs probing into one list, remembering how many
+ # each request consumed so the results can be handed back out.
+ flat: list[Any] = []
+ spans: list[tuple[FilterOperator, int, int]] = []
+ for operator, value in requests:
+ values = list(value) if operator == FilterOperator.IN else [value]
+ spans.append((operator, len(flat), len(values)))
+ flat.extend(values)
+
+ evaluated = evaluate_transform(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ mapping.value_transform,
+ flat,
+ errors=errors,
+ )
+ if evaluated is None:
+ return []
+
+ if not _bounds_are_ordered(evaluated, spans):
+ return []
+
+ sqla_col = datasource.convert_tbl_column_to_sqla_col(partition_column)
+ db_engine_spec = datasource.db_engine_spec
+
+ predicates: list[ColumnElement[Any]] = []
+ for operator, start, length in spans:
+ chunk = evaluated[start : start + length]
+ if any(value is None for value in chunk):
+ continue
+ if operator == FilterOperator.IN:
+ predicates.append(sqla_col.in_(chunk))
+ else:
+ predicates.append(
+ db_engine_spec.handle_comparison_filter(sqla_col, operator, chunk[0])
+ )
Review Comment:
Strict `>`/`<` is narrower than the filter when T is monotonic but not strict, e.g. `date(:value)`. Real probe on SQLite: `event_time > '2026-01-01 00:00'` became `dt > '2026-01-01'` and dropped 09:30 Jan 1; a time range ending 12:00 dropped that morning. 8 mirroring tests pin the strict ops.
```suggestion
else:
# A monotonic T need only be non-decreasing: x > v gives T(x) >= T(v).
operator = {
FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
}.get(operator, operator)
predicates.append(
db_engine_spec.handle_comparison_filter(sqla_col, operator, chunk[0])
)
```
##########
docs/admin_docs/configuration/partition-filter-mapping.mdx:
##########
@@ -0,0 +1,189 @@
+---
+title: Partition Filter Mapping
+hide_title: true
+sidebar_position: 15
+version: 1
+---
+
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+
+# Partition Filter Mapping
+
+Tables on Hadoop-family engines are often partitioned on a *technical* column — an epoch
+integer, a lowercased region key — that no analyst would ever filter on. Unless a query
+carries a predicate on that column, the engine scans every partition.
+
+Partition filter mapping makes this a dataset setting instead of a per-chart chore. A
+dataset owner names the partition column, the business column whose filters should be
+mirrored onto it, and a value transform. Superset then appends an equivalent predicate on
+the partition column to every query. Chart authors change nothing; queries prune.
+
+:::caution Experimental
+This feature is behind the `PARTITION_FILTER_MAPPING` feature flag and is off by default.
+:::
+
+## Enabling it
+
+```python
+FEATURE_FLAGS = {
+ "PARTITION_FILTER_MAPPING": True,
+}
+```
+
+Configure it as a **static boolean**. `FEATURE_FLAGS` also accepts per-request callables,
+but a flag that resolves differently per user or tenant would let a user with the feature
+off read a cached chart result that was produced from pruned SQL by a user with it on.
+
+## Configuring a mapping
+
+In the dataset editor's **Columns** tab, under *Default Column Settings*, pick a
+**Partition column**. By default the mapping follows the dataset's default datetime column,
+so re-pointing that column moves the mapping with it; set an explicit override if you want it
+pinned to a different column.
+
+Expand the mapped column's row in *Column Settings* and set the **value transform**: a SQL
+expression containing a `:value` placeholder, which stands for the filter value being
+mirrored. The **Transform preserves ordering** checkbox sits directly beneath it.
+
+| Mapped column | Partition column | Transform |
+|---|---|---|
+| `event_time` (`TIMESTAMP`) | `dt_epoch` (`BIGINT`) | `unix_timestamp(:value)` |
+| `country` (`VARCHAR`) | `region_key` (`VARCHAR`) | `lower(:value)` |
+
+A filter of `event_time >= '2026-01-01'` then adds `dt_epoch >= 1767225600` to the query.
+The added predicate is an ordinary `WHERE` clause and shows up in **View query**.
+
+### Transform preserves ordering
+
+Range filters — including the Explore time range, the most important case — are only
+mirrored when you check **Transform preserves ordering**.
+
+Monotonicity is a property of the *transform*, not of the column's data type.
+`unix_timestamp(:value)` preserves ordering. `hour(:value)`,
+`date_format(:value, 'dd')` and `dayofweek(:value)` are all perfectly reasonable
+partition transforms on a `TIMESTAMP` column and none of them do: `hour('2026-01-01 23:00')`
+is greater than `hour('2026-01-02 01:00')` even though the first instant is earlier. Mirroring
+a range through one of those would silently return wrong numbers, so Superset asks you to
+declare it rather than guessing.
+
+When the box is unchecked, `=` and `IN` filters still mirror; ranges do not.
+
+## What is and isn't mirrored
+
+| Filter | Mirrored |
+|---|---|
+| `=`, `IN` | Always |
+| `>`, `>=`, `<`, `<=`, time ranges | Only when the transform preserves ordering |
+| `!=`, `NOT IN`, `LIKE`, `ILIKE`, `IS NULL`, `IS TRUE` | Never |
+
+Negations are never safe. A transform need not be injective: `lower(:value)` with
+`country != 'US'` would mirror to `region_key != 'us'`, which excludes rows whose `country`
+is already lowercase `'us'` — rows the original filter *keeps*.
+
+**Time grains.** A filter that carries a time grain — drill-to-detail, mostly — compares the
+*truncated* column, so the raw bounds it carries do not describe the rows it keeps: a row in
+the final partial bucket satisfies `DATE_TRUNC(...) < until` while `col < until` excludes it.
+Grained *ranges* still mirror, with both bounds widened by one bucket so the mirror stays no
+narrower than the real filter. A `P1D` drill therefore reads three days of partitions rather
+than one, instead of scanning the table. Grained `=` and `IN` filters do not mirror.
+
+Widening is only applied to grains whose bucket width Superset knows, which means the
+built-in ones. A grain you added through `TIME_GRAIN_ADDONS`, or a built-in grain whose SQL
+you replaced through `TIME_GRAIN_ADDON_EXPRESSIONS`, has no width Superset can rely on and
+simply does not mirror.
+
+Known gaps, all of which are out of scope rather than bugs:
+
+- **Filter-value dropdowns do not prune.** Populating a filter's value list runs its own
+ `SELECT DISTINCT`, which never goes through the chart query path. There is no filter to
+ mirror from.
+- **Row-level security predicates do not mirror.** They are stored as raw SQL and appended
+ downstream of the structured filters.
+- **Custom SQL `WHERE` clauses do not mirror**, for the same reason.
+- **Columns with an active advanced data type do not mirror.** Those build their own
+ predicate shape from translated values, so there is no operator/value pair to mirror.
+- Dashboard native filters and cross-filters *do* mirror — they arrive as ordinary filters —
+ they just carry no visual indicator in the filter bar.
Review Comment:
The stated limitation is only in a code comment; this list already covers indicator gaps, so a line here makes it user-visible:
```suggestion
- Dashboard native filters and cross-filters *do* mirror — they arrive as ordinary filters —
they just carry no visual indicator in the filter bar.
- **The Explore glyph is advisory.** A virtual dataset whose SQL consumes a filter through
`get_filters(..., remove_filter=True)` gets neither the filter nor its mirror, yet the
glyph still shows. **View query** is the authority.
```
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,1278 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` always -- ``T`` is a function
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import re
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLStatement
+from superset.utils import json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: Every entry point enforces it -- the typed column field, the import schema
+#: and the preview request -- because `is_transform_active` parses the stored
+#: value on each Explore load, and an unbounded string would make that parse
+#: the expensive part of rendering a chart.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+def mirrorable_operators(is_monotonic: bool) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ """
+ if is_monotonic:
+ return MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+ return set(MIRRORABLE_ALWAYS)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(self.is_monotonic)
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+ """
+ return VALUE_PLACEHOLDER_RE.sub(_PARSE_STANDIN, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(transform: str, engine: str) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
Review Comment:
Import keeps a subquery transform (`drop_unusable_partition_transforms` drops only blocking issues) and this gate skips the stored-expression policy. Run: `(SELECT secret FROM vault LIMIT 1) || :value` put `'TOPSECRET_us'` into chart SQL; the same subquery as a calculated column is rejected.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4179235170
##########
superset/datasets/api.py:
##########
@@ -323,6 +401,17 @@ class DatasetRestApi(SoftDeleteApiMixin, BaseSupersetModelRestApi):
]
show_columns = show_select_columns + [
"columns.type_generic",
+ # Engine-supplied pre-fill for the editor's value transform input.
+ "partition_value_transform_default",
+ # The resolved mapping summary, which is what Explore's pruning
+ # indicator reads. Saving a dataset from Explore reloads this endpoint
+ # and replaces the chart's datasource with the response wholesale -- it
+ # is a replacement, not a merge -- so anything the summary carries and
+ # this payload does not is lost on an unrelated save and the glyphs
+ # vanish until the page is reloaded. Recomputing it client-side from
+ # `columns` is not an option: `data_for_slices` prunes the partition
+ # column on dashboards, which is why the summary is self-contained.
+ "partition_filter_mapping",
Review Comment:
`check-openapi-spec-drift` fails on this line: it publishes a new readOnly `partition_filter_mapping` field, so `docs/static/resources/openapi.json` needs regenerating here (no suggestion: the fix is in the generated file).
##########
tests/unit_tests/connectors/sqla/partition_mapping_test.py:
##########
@@ -0,0 +1,1434 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Unit tests for ``superset.connectors.sqla.partition_mapping``."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from typing import Any, cast
+from importlib import import_module
Review Comment:
`pre-commit` stays red even after the mypy fix: ruff I001 wants `importlib` before `typing`.
```suggestion
from importlib import import_module
from typing import Any, cast
```
##########
tests/unit_tests/connectors/sqla/partition_mapping_test.py:
##########
@@ -0,0 +1,1434 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Unit tests for ``superset.connectors.sqla.partition_mapping``."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from typing import Any, cast
+from importlib import import_module
+from unittest.mock import MagicMock, patch, PropertyMock
+
+import pandas as pd
+import pytest
+from dateutil.relativedelta import relativedelta
+from flask import Flask
+from sqlalchemy.dialects import mysql, postgresql
+
+from superset.connectors.sqla.models import SqlaTable, TableColumn
+from superset.connectors.sqla.partition_mapping import (
+ _probe_cache_key,
+ _render_literal,
+ build_probe_sql,
+ contains_jinja,
+ contains_value_placeholder,
+ equality_mirrors_safely,
+ evaluate_transform,
+ find_non_deterministic_functions,
+ grain_bucket_width,
+ GRAIN_BUCKET_WIDTHS,
+ is_bare_expression,
+ is_parseable,
+ is_transform_active,
+ is_unfinished,
+ MappingValidationIssue,
+ MIRRORABLE_ALWAYS,
+ MIRRORABLE_IF_MONOTONIC,
+ mirrorable_operators,
+ parse_error_detail,
+ resolve_partition_mapping,
+ stored_expression_error,
+ validate_partition_mapping,
+ validate_transform,
+)
+from superset.constants import TimeGrain
+from superset.db_engine_specs.base import BaseEngineSpec
+from superset.db_engine_specs.oracle import OracleEngineSpec
+from superset.models.core import Database
+from superset.utils.core import FilterOperator
+
+
+@pytest.fixture(autouse=True)
+def real_probe_cache(app: Flask) -> Any:
+ """
+ The test app runs a null cache, which would make every cache assertion here
+ vacuously pass. Swap in a real in-memory one for the duration.
+ """
+ from flask_caching import Cache
+
+ from superset.extensions import cache_manager
+
+ cache = Cache(config={"CACHE_TYPE": "SimpleCache", "CACHE_DEFAULT_TIMEOUT": 300})
+ cache.init_app(app)
+ original = cache_manager._cache # noqa: SLF001
+ cache_manager._cache = cache # noqa: SLF001
+ yield
+ cache_manager._cache = original # noqa: SLF001
+
+
+@pytest.fixture(autouse=True)
+def enable_partition_filter_mapping(app: Flask) -> Any:
+ """The feature ships off; every test here exercises it on."""
+ original = app.config["DEFAULT_FEATURE_FLAGS"].get("PARTITION_FILTER_MAPPING")
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = True
+ yield
+ if original is None:
+ del app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"]
+ else:
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = original
+
+
+def _table(**kwargs: Any) -> SqlaTable:
+ database = Database(database_name="test_db", sqlalchemy_uri="sqlite://")
+ defaults: dict[str, Any] = {
+ "table_name": "web_events",
+ "database": database,
+ "main_dttm_col": "event_time",
+ "columns": [
+ TableColumn(column_name="event_time", is_dttm=True, type="TIMESTAMP"),
+ TableColumn(
+ column_name="dt_epoch",
+ type="BIGINT",
+ partition_value_transform=None,
+ ),
+ TableColumn(column_name="country", type="VARCHAR"),
+ TableColumn(column_name="region_key", type="VARCHAR"),
+ ],
+ }
+ defaults.update(kwargs)
+ return SqlaTable(**defaults)
+
+
+def _mapped_table(
+ *,
+ partition_column: str = "dt_epoch",
+ mapped_column: str = "event_time",
+ transform: str | None = "unix_timestamp(:value)",
+ monotonic: bool = True,
+ partition_mapped_column: str | None = None,
+ main_dttm_col: str | None = "event_time",
+) -> SqlaTable:
+ table = _table(main_dttm_col=main_dttm_col)
+ table.partition_column = partition_column
+ table.partition_mapped_column = partition_mapped_column
+ for column in table.columns:
+ if column.column_name == mapped_column:
+ column.partition_value_transform = transform
+ column.partition_transform_is_monotonic = monotonic
+ return table
+
+
+# ---------------------------------------------------------------------------
+# §2 — operator safety matrix
+# ---------------------------------------------------------------------------
+
+
+def test_equality_and_in_are_always_mirrorable() -> None:
+ """``=`` and ``IN`` are safe for any function ``T``."""
+ assert MIRRORABLE_ALWAYS == {FilterOperator.EQUALS, FilterOperator.IN}
+
+
+def test_range_operators_require_a_monotonic_transform() -> None:
+ assert MIRRORABLE_IF_MONOTONIC == {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+ }
+
+
+def test_mirrorable_operators_excludes_ranges_when_not_monotonic() -> None:
+ assert mirrorable_operators(is_monotonic=False) == MIRRORABLE_ALWAYS
+
+
+def test_mirrorable_operators_includes_ranges_when_monotonic() -> None:
+ assert mirrorable_operators(is_monotonic=True) == (
+ MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+ )
+
+
+@pytest.mark.parametrize(
+ "operator",
+ [
+ FilterOperator.NOT_EQUALS,
+ FilterOperator.NOT_IN,
+ FilterOperator.LIKE,
+ FilterOperator.ILIKE,
+ FilterOperator.NOT_LIKE,
+ FilterOperator.NOT_ILIKE,
+ FilterOperator.IS_NULL,
+ FilterOperator.IS_NOT_NULL,
+ FilterOperator.IS_TRUE,
+ FilterOperator.IS_FALSE,
+ ],
+)
+def test_negations_and_pattern_matches_are_never_mirrorable(
+ operator: FilterOperator,
+) -> None:
+ """
+ ``T`` is not injective, so ``col != v`` does **not** imply ``T(col) != T(v)``:
+ mirroring it would drop rows the original filter keeps.
+ """
+ assert operator not in mirrorable_operators(is_monotonic=True)
+
+
+def test_equality_is_dropped_when_the_engine_does_not_compare_byte_exactly() -> None:
+ """
+ "Safe for any function ``T``" reasons about value equality: ``T`` is a
+ function, so ``col = v`` gives ``T(col) = T(v)``. The engine reasons about
+ *SQL* equality, and the two part company under a case-insensitive
+ collation -- a stored ``'us'`` satisfies a filter for ``'US'`` while the
+ mirror ``hex('US')`` excludes the row, and the chart loses it silently.
+ """
+ assert mirrorable_operators(is_monotonic=False, equality_is_safe=False) == set()
+
+
+def test_ranges_survive_an_unsafe_equality() -> None:
+ """
+ Range mirroring already rests on the owner declaring ``T``
+ order-preserving with respect to the column's own order -- an assertion
+ about the very comparison semantics this gate checks for. Equality has no
+ such declaration behind it, which is why only equality is withdrawn.
+ """
+ assert (
+ mirrorable_operators(is_monotonic=True, equality_is_safe=False)
+ == MIRRORABLE_IF_MONOTONIC
+ )
+
+
+def _column(type_: str) -> TableColumn:
+ database = Database(database_name="t", sqlalchemy_uri="sqlite://")
+ table = SqlaTable(table_name="t", database=database)
+ return TableColumn(column_name="c", type=type_, table=table)
+
+
+@pytest.mark.parametrize(
+ "type_, binary, expected",
+ [
+ ("VARCHAR", True, True),
+ ("VARCHAR", False, False),
+ # Numeric and temporal comparison is exact everywhere.
+ ("BIGINT", False, True),
+ ("TIMESTAMP", False, True),
+ ("DOUBLE", False, True),
+ ],
+)
+def test_equality_mirrors_safely_only_guards_string_columns(
+ app: Flask, type_: str, binary: bool, expected: bool
+) -> None:
+ class _Spec(BaseEngineSpec):
+ binary_string_comparison = binary
+
+ with app.app_context():
+ assert equality_mirrors_safely(_column(type_), _Spec) is expected
+
+
+def test_equality_mirrors_safely_fails_closed_on_an_unresolvable_type(
+ app: Flask,
+) -> None:
+ """
+ The gate exists to stop a silent wrong answer, so a column whose type it
+ cannot read is treated as the risky case rather than waved through.
+ """
+ column = MagicMock()
+ type(column).type_generic = PropertyMock(side_effect=ValueError("no type"))
+
+ with app.app_context():
+ assert equality_mirrors_safely(column, BaseEngineSpec) is False
+
+
+def test_no_mapped_column_leaves_the_matrix_alone(app: Flask) -> None:
+ """Nothing to reason about, and the resolver bails out on it anyway."""
+ with app.app_context():
+ assert equality_mirrors_safely(None, BaseEngineSpec) is True
+
+
+@pytest.mark.parametrize(
+ "module, spec_name",
+ [
+ ("presto", "PrestoEngineSpec"),
+ ("hive", "HiveEngineSpec"),
+ ("trino", "TrinoEngineSpec"),
+ ("impala", "ImpalaEngineSpec"),
+ ("postgres", "PostgresEngineSpec"),
+ ("bigquery", "BigQueryEngineSpec"),
+ ("sqlite", "SqliteEngineSpec"),
+ ],
+)
+def test_the_byte_exact_engines_opt_in(module: str, spec_name: str) -> None:
+ """
+ The engines this feature targets compare text byte-exactly, so the gate
+ must not cost them the second canonical mapping (`lower(:value)` onto a
+ lowercased key).
+ """
+ spec = getattr(import_module(f"superset.db_engine_specs.{module}"), spec_name)
+ assert spec.binary_string_comparison is True
+
+
+@pytest.mark.parametrize("module, spec_name", [("mysql", "MySQLEngineSpec")])
+def test_a_case_insensitive_engine_does_not_opt_in(
+ module: str, spec_name: str
+) -> None:
Review Comment:
`ruff-format` also rewrites this signature onto one line, which is the other modified file in the failing pre-commit run.
```suggestion
def test_a_case_insensitive_engine_does_not_opt_in(module: str, spec_name: str) -> None:
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(explore): indicate when a filter is mirrored onto a partition column [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r3939841258
##########
superset-frontend/src/explore/components/controls/DateFilterControl/DateFilterLabel.tsx:
##########
@@ -406,7 +408,12 @@ export default function DateFilterLabel(props: DateFilterControlProps) {
{...props}
onDescriptionHoverChange={setIsDescriptionHovered}
/>
- {popoverContent}
+ {/* The glyph sits outside the popover trigger so clicking it opens the
+ tooltip rather than the time-range editor. */}
+ <Flex align="center" gap={theme.sizeUnit}>
+ {popoverContent}
+ <PartitionPruningIndicator mapping={props.partitionMapping} />
Review Comment:
Agreed. The standalone control currently receives only the dataset-level mapping, so it cannot distinguish an active time range from `No filter`, nor verify that the selected temporal column is `mapped_column`.
The indicator should be gated before rendering, for example:
```tsx
const hasTimeRange = props.value && props.value !== NO_TIME_RANGE;
const isMappedTemporalColumn =
selectedTemporalColumn === props.partitionMapping?.mapped_column;
<PartitionPruningIndicator
mapping={
hasTimeRange && isMappedTemporalColumn
? props.partitionMapping
: undefined
}
/>
```
`selectedTemporalColumn` should come from the same datasource/control state used to generate the temporal predicate (typically `granularity_sqla` or the effective main datetime column). This ensures the glyph appears only when the query actually contains the mapped time predicate, and remains hidden for `No filter` or another temporal column. The adhoc filter paths already perform the equivalent subject-column check.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(explore): indicate when a filter is mirrored onto a partition column [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #43870:
URL: https://github.com/apache/superset/pull/43870#issuecomment-5548877971
<!-- Bito Reply -->
The flagged issue is correct: the `PartitionPruningIndicator` was being rendered in `OptionControlLabel` without verifying if the filter is actually active or applicable to the current context.
To resolve this, you should ensure the indicator only renders when the `partitionMapping` is valid and active. Since `OptionControlLabel` already receives `partitionMapping` as a prop, you can update the component to check for its existence before rendering the indicator.
### Proposed Fix
Update `superset-frontend/src/explore/components/controls/OptionControls/index.tsx` to conditionally render the indicator:
```tsx
// In OptionControlLabel component
{partitionMapping?.active && (
<PartitionPruningIndicator mapping={partitionMapping} />
)}
```
This ensures the glyph only appears when the mapping is active, preventing misleading indicators for inactive or unrelated filters.
Would you like me to fetch all other comments on this PR to validate and implement fixes for them as well?
**superset-frontend/src/explore/components/controls/OptionControls/index.tsx**
```
<PartitionPruningIndicator mapping={partitionMapping} />
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #43870:
URL: https://github.com/apache/superset/pull/43870#issuecomment-6070765683
### ⚠️ Possible DB migration conflict
@hughhhh the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
To check and, if needed, fix this:
1. Rebase this branch onto the latest `master`.
2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4376078987
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,3889 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Writing the value into the probe
+--------------------------------
+The probe evaluates the transform at a *literal*, because it runs with no bound
+parameters at all -- so every value is written into SQL text by the driver's
+literal renderer and read back by the engine's lexer, and the two do not always
+agree. SQLAlchemy's default renderer doubles apostrophes and leaves backslashes
+alone; Hive honours backslash escapes and not doubling, so ``'O''Brien'`` is
+read there as two adjacent literals and ``'x\\''`` ends four characters into a
+value the filter carries whole. A disagreement is either a mirror built from a
+value nobody filtered on -- dropping rows the filter keeps -- or, where the
+value closes its own quote, an expression of the filterer's choosing running in
+the probe.
+
+Which side is right is not knowable from the driver: it is a per-session server
+setting (``standard_conforming_strings``, ``NO_BACKSLASH_ESCAPES``,
+``spark.sql.parser.escapedStringLiterals``), and SQLAlchemy's own view of it is
+only correct on a dialect that has connected. So escaping is not what makes
+this safe. `literal_round_trips` renders the literal and reads it back in the
+engine's own dialect instead, and a value that does not survive the trip is not
+mirrored -- the usual trade, pruning for correctness. `probe_sql_is_evaluable`
+re-reads the finished statement behind it.
+
+The probe's *answers* make the same trip, in the other direction. The chart
+query is compiled with ``literal_binds``, so a probed partition key is rendered
+into its SQL by the same renderer and read by the same lexer -- and
+``concat(:value, chr(92), 'b')`` turns the unremarkable input ``a`` into the key
+``a\\b``, which Hive reads back as ``a`` followed by a backspace. So
+`_predicates_from_probe` asks `literal_round_trips` about each result too, and
+declines the request rather than emitting a predicate no row can satisfy: the
+mirror is ``AND``-ed onto the query, so a mirror that matches nothing costs the
+chart its rows rather than its pruning.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Mapping, Sequence
+from dataclasses import dataclass
+from datetime import date, datetime, time, timedelta
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: The opening and closing delimiters of each kind of Jinja block. The probe
+#: would render these in a different context at a different time from the chart
+#: query, so a transform holding one is rejected at save time.
+JINJA_BLOCK_DELIMITERS = (("{{", "}}"), ("{%", "%}"), ("{#", "#}"))
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: A PostgreSQL Unicode-escaped identifier, ``U&"..."``.
+#:
+#: The second construct that breaks the premise above, and in the same way:
+#: ``U&"\\0071uery_to_xml"(...)`` parses as an anonymous function whose name is
+#: the *literal* ``\\0071uery_to_xml``, so the function denylist is matching a
+#: name the engine never sees -- PostgreSQL decodes the escape and runs
+#: ``query_to_xml``, handing a dataset owner rows from outside their RLS scope
+#: through the preview's ``emitted_predicate``.
+#:
+#: Normalizing the escapes and re-checking would be the other repair, and is
+#: worse: it means reimplementing one engine's identifier decoding well enough
+#: to be a security boundary. Refusing the construct is exact, and costs
+#: nothing real -- a transform is a scalar function of ``:value``, and there is
+#: no reason to name a function or column through an escape sequence.
+#:
+#: Refused on every engine, like the executable comment, so a transform stored
+#: on SQLite cannot detonate when the dataset is re-pointed at PostgreSQL. The
+#: ``&`` may be separated from the ``U`` by nothing at all, but whitespace or a
+#: comment between the prefix and the string is not accepted by PostgreSQL
+#: either, so the strict form is the whole surface.
+#:
+#: Matched in raw text, so the prefix is refused inside a string literal too.
+#: That is the same trade the executable comment makes and has the same
+#: justification: a gate whose contract is to fire *before* the parse cannot
+#: ask the parse whether the text was quoted. ``concat(:value, 'u&"x"')`` is
+#: refused, which costs an owner nothing anyone writes.
+UNICODE_ESCAPED_IDENTIFIER_RE = re.compile(r'\bU&"', re.IGNORECASE)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate: a transform such as
+#: ``datediff(day, :value, LOCALTIMESTAMP)`` for a relative partition key is
+#: evaluated once and then keeps emitting yesterday's answer, so the chart
+#: silently drops rows after midnight.
+#:
+#: Matched by SQL function name, so every engine's spelling of "now" has to be
+#: named -- the ANSI four were not enough. Listed rather than delegated to the
+#: engine specs because the risk is the same everywhere and a spec that had not
+#: got round to declaring its own would fail open; a name no engine has is
+#: inert, so over-listing costs nothing.
+NON_DETERMINISTIC_FUNCTIONS = {
+ # ANSI, and the engines that spell it this way.
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "LOCALTIME",
+ "LOCALTIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+ # PostgreSQL. `now()` is statement-stable; these two are not even that.
+ "CLOCK_TIMESTAMP",
+ "STATEMENT_TIMESTAMP",
+ "TIMEOFDAY",
+ # MySQL and MariaDB.
+ "CURDATE",
+ "CURTIME",
+ "SYSDATE",
+ "UTC_DATE",
+ "UTC_TIME",
+ "UTC_TIMESTAMP",
+ "UUID_SHORT",
+ # Oracle.
+ "SYSTIMESTAMP",
+ "SYS_GUID",
+ # SQL Server.
+ "GETDATE",
+ "GETUTCDATE",
+ "SYSDATETIME",
+ "SYSUTCDATETIME",
+ "SYSDATETIMEOFFSET",
+ "NEWID",
+ # BigQuery.
+ "CURRENT_DATETIME",
+ "GENERATE_UUID",
+ # Snowflake.
+ "RANDSTR",
+ "UUID_STRING",
+ # ClickHouse.
+ "NOW64",
+ "RANDCANONICAL",
+ "GENERATEUUIDV4",
+ # H2 and Derby, which the test fixtures use.
+ "RANDOM_UUID",
+}
+
+#: The wall-clock names an engine evaluates with no parentheses at all.
+#:
+#: These parse as *column references*, not functions, so the name-based walk
+#: below cannot see them: `datediff(UTC_DATE, :value)` on MySQL and
+#: `:value - SYSDATE` on Oracle both cleared the gate and froze probe time into
+#: a cached mirror.
+#:
+#: A subset of `NON_DETERMINISTIC_FUNCTIONS` rather than the whole of it,
+#: because refusing a bare name costs an owner a column genuinely called that.
+#: Only the names SQL lets you write without ``()`` are listed -- the datetime
+#: keywords -- so `rand`, `uuid` and `newid`, which always need parentheses and
+#: are plausible column names, stay out.
+BARE_WALL_CLOCK_KEYWORDS = frozenset(
+ {
+ "current_date",
+ "current_time",
+ "current_timestamp",
+ "localtime",
+ "localtimestamp",
+ "utc_date",
+ "utc_time",
+ "utc_timestamp",
+ "sysdate",
+ "systimestamp",
+ }
+)
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+class Unmirrorable:
+ """
+ A filter no mirror can stand in for, and why.
+
+ Returned by `ExploreMixin.mirror_probe_request` for a value the engine
+ compares more coarsely than the filter carries, one it cannot render as a
+ literal, one whose rendered literal the engine would not read back as the
+ same value, one in a time frame the transform would discard, or an ``IN``
+ list with a member of any of those kinds. An object rather than `None`,
+ because `None` is a filter value in its own right.
+
+ The reason rides along because the preview has to explain the decline to
+ the owner, and the two declines want different advice: "the engine compares
+ less of this value than you typed, so map a column it compares in full" is
+ sound guidance for a `DATE` column and actively misleading for an
+ offset-bearing bound on a `TIMESTAMP` one, which already is such a column.
+ Carried rather than re-derived so the preview's explanation cannot come
+ apart from the chart path's decision.
+
+ Lives here rather than beside that method so the preview can read it too:
+ `superset.models.helpers` imports this module, so these can only cross the
+ boundary in this direction. Both callers recognise the same instances -- a
+ preview that answered "valid" for a request the chart path declines is the
+ drift this is here to prevent.
+ """
+
+ __slots__ = ("reason",)
+
+ def __init__(self, reason: str) -> None:
+ self.reason = reason
+
+ def __repr__(self) -> str:
+ return f"<Unmirrorable {self.reason}>"
+
+
+#: The ordinary decline: whatever the mirror cannot be built from, with the
+#: engine's own comparison resolution as the reason an owner can act on.
+UNMIRRORABLE = Unmirrorable("resolution")
+
+#: A value carrying a UTC offset, declined whatever the column's resolution.
+#: A transform such as ``CAST(:value AS TIMESTAMP)`` drops the offset, so even
+#: an engine that compares the whole instant would be probed in the wrong
+#: frame -- which is not something mapping a different column fixes.
+UNMIRRORABLE_OFFSET = Unmirrorable("offset")
+
+#: A value the driver and the engine would not spell the same way, declined
+#: whatever the column's resolution and whatever the operator. Nothing about
+#: the column or the transform fixes it -- see `literal_round_trips` -- so the
+#: advice the resolution reason carries would send an owner after the wrong
+#: thing entirely.
+UNMIRRORABLE_ESCAPING = Unmirrorable("escaping")
+
+
+def is_unmirrorable(value: Any) -> bool:
+ """Whether `mirror_probe_request` declined this request."""
+ return isinstance(value, Unmirrorable)
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def _native_generic_type(
+ column: "TableColumn",
+) -> utils.GenericDataType | None:
+ """
+ What the engine spec makes of ``column``'s declared type.
+
+ `TableColumn.type_generic` answers ``TEMPORAL`` for every column carrying
+ ``is_dttm``, which is the right answer for a chart's time axis and the
+ wrong one for a comparison: an epoch ``BIGINT`` is a number to the engine
+ however it is labelled here. Falls back to the flag where the spec has no
+ answer, so a type Superset cannot resolve is no worse off than before.
+ """
+ try:
+ column_spec = column.db_engine_spec.get_column_spec(
+ column.type, db_extra=column.db_extra
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ column_spec = None
+ if column_spec is not None and column_spec.generic_type is not None:
+ return column_spec.generic_type
+ try:
+ return column.type_generic
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+#: A declared type naming an array: PostgreSQL's ``TEXT[]`` / ``INTEGER[][]``
+#: / ``int[3]``, and the ``ARRAY<...>`` / ``ARRAY(...)`` / ``Array(...)``
+#: spellings of Hive, Spark, Trino, BigQuery and ClickHouse.
+#: The bracket body is written so no two runs can match the same blanks:
+#: ``\s*\d*\s*`` backtracks polynomially on a long run of spaces.
+_ARRAY_TYPE_RE = re.compile(r"(?:\[\s*(?:\d+\s*)?\])+\s*$|^\s*ARRAY\b", re.IGNORECASE)
+
+
+def declares_array_type(column_type: str | None) -> bool:
+ """
+ Whether a declared column type is an array, whatever the engine spec says.
+
+ The engine spec only reports ``MULTI_VALUE`` where it has opted into
+ ``supports_multivalue_columns``; PostgreSQL has not, and resolves ``TEXT[]``
+ to ``STRING`` and ``INTEGER[]`` to ``NUMERIC``. So an array partition column
+ there cleared the array refusal, previewed valid, and every equality chart
+ on the mapping failed with ``malformed array literal``. The declared type
+ is what the engine will compare, so it is read directly as well.
+ """
+ return bool(column_type and _ARRAY_TYPE_RE.search(column_type))
+
+
+#: Declared types whose comparison ignores trailing blanks.
+#:
+#: The fixed-width character types, which the SQL standard has compare as
+#: though both sides were padded to the same length -- so ``'US'`` and
+#: ``'US '`` are equal in a ``CHARACTER(3)``, while ``lower()`` of the two is
+#: not. Spelled out rather than matched by prefix because the variable-width
+#: names start with the same letters: ``VARCHAR`` and ``CHARACTER VARYING``
+#: compare the blanks and must not land here.
+PADDED_CHARACTER_TYPES = frozenset(
+ {
+ "CHAR",
+ "NCHAR",
+ # PostgreSQL's own name for ``CHARACTER``, which is what reflection
+ # reports for a ``CHAR(n)`` column there.
+ "BPCHAR",
+ "CHARACTER",
+ "NATIONAL CHAR",
+ "NATIONAL CHARACTER",
+ }
+)
+
+
+def _is_padded_character_type(column: TableColumn) -> bool:
+ """
+ Whether ``column``'s declared type compares without its trailing blanks.
+
+ Read off the declared type rather than the engine spec's resolved one: the
+ specs map ``CHAR`` and ``VARCHAR`` onto the same `sqlalchemy.String`, so
+ the distinction this needs is gone by then. The length suffix is dropped
+ and the name matched against `PADDED_CHARACTER_TYPES`, so an unfamiliar
+ spelling answers ``False`` and the engine-level flag decides as before --
+ this gate adds a decline rather than lifting one. A column with no
+ declared type has nothing to read, and answers the same way.
+ """
+ if not isinstance(column.type, str):
+ return False
+ native = re.sub(r"\s+", " ", column.type.strip().upper())
+ return native.split("(")[0].strip() in PADDED_CHARACTER_TYPES
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ Padding is asked about per column, because it is a property of the *type*
+ rather than of the engine. ``binary_string_comparison`` speaks for an
+ engine's default text comparison, and on PostgreSQL -- which declares it
+ -- a ``CHAR(2)`` still matches a filter for ``'US '`` against a stored
+ ``'US'``, because the standard says a padded character type compares
+ without its trailing blanks. The mirror ``region_key = lower('US ')`` then
+ excludes the row. So a fixed-width character type declines whatever the
+ engine says, and an engine that ignores trailing blanks on its *variable*
+ types says so by not declaring the flag at all (see `RedshiftEngineSpec`).
+
+ The type asked for is the engine spec's reading of the column's declared
+ type, not `TableColumn.type_generic`, which answers ``TEMPORAL`` for
+ anything carrying ``is_dttm``. A ``VARCHAR`` flagged temporal is still text
+ to the engine: on MySQL a filter for ``'2026-01-01T00:00:00'`` matches a
+ stored ``'...t00:00:00'``, while the mirror ``p = hex('...T...')`` excludes
+ it -- and asking the semantic flag skipped the check entirely.
+
+ A type the spec cannot classify declines, which is what the paragraph above
+ promises and what only the exception branch used to do. PostgreSQL's
+ ``citext`` matches no type pattern, so it answered ``None`` -- neither
+ string nor not-string -- and was waved through, which is precisely wrong
+ for a type whose whole purpose is case-insensitive comparison. Declining
+ costs the pruning; admitting it costs rows.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ # Ahead of the generic-type question, which a padded type can lose: the
+ # specs map ``CHARACTER`` onto no generic type at all on some engines, and
+ # a fixed-width character type is a string whether or not Superset can say
+ # so from the name.
+ if _is_padded_character_type(column):
+ return False
+ generic_type = _native_generic_type(column)
+ if generic_type is None:
+ return False
+ if generic_type != utils.GenericDataType.STRING:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_unicode_escaped_identifier(transform: str | None) -> bool:
+ """Whether the transform names something through a ``U&"..."`` escape.
+
+ See `UNICODE_ESCAPED_IDENTIFIER_RE`. Answered on raw text for the same
+ reason as the comment above: the parse reports a name the engine does not
+ use, which is exactly what makes the denylist blind to it.
+ """
+ return (
+ bool(transform)
+ and UNICODE_ESCAPED_IDENTIFIER_RE.search(transform or "") is not None
+ )
+
+
+#: Sequence pseudo-columns, which advance a sequence when they are *read*.
+#:
+#: ``orders_seq.NEXTVAL`` parses as a qualified column reference, not a
+#: function call, so neither `SQLStatement.is_mutating` -- which walks function
+#: names -- nor the function denylist can see it. The probe would then run
+#: ``SELECT orders_seq.NEXTVAL + 1 FROM DUAL`` and advance the sequence, again
+#: on every cache expiry, for a dataset editor holding neither SQL Lab nor a
+#: DML grant. Reading one is a write however the parser classifies it.
+#:
+#: The function spelling (``nextval('s')`` on PostgreSQL) is a different shape
+#: and is caught as a function; this is only about the suffix form.
+SEQUENCE_PSEUDO_COLUMNS = frozenset({"nextval", "currval"})
+
+#: The same thing written as a call.
+#:
+#: Only the suffix form parses as a column; `nextval('s')` on PostgreSQL and
+#: DuckDB, `NEXTVAL(s)`/`SETVAL(s, 1)` on MySQL and MariaDB, and SQL Server's
+#: `NEXT VALUE FOR s` all parse as functions. `SQLStatement.is_mutating` walks
+#: function names on PostgreSQL alone -- deliberately, since the same names are
+#: read-only elsewhere -- so every other engine let these through.
+#:
+#: Matched on the name whatever the engine, because advancing a sequence is a
+#: write wherever it happens and a transform has no reason to call one.
+SEQUENCE_FUNCTIONS = frozenset(
+ {"nextval", "setval", "next_value_for", "nextvalfor", "prevval", "lastval"}
+)
+
+
+def references_sequence(statement: SQLStatement) -> bool:
+ """Whether the statement reads or advances a sequence.
+
+ Both spellings: the pseudo-column suffix, which parses as a column (see
+ `SEQUENCE_PSEUDO_COLUMNS`), and the call, which parses as a function (see
+ `SEQUENCE_FUNCTIONS`).
+
+ Answered on the parse rather than on raw text, because position is what
+ makes it the construct: a column or alias merely *called* ``nextval`` is
+ an ordinary column, and a string literal holding the word is text.
+ """
+ return bool(
+ statement.get_column_names() & SEQUENCE_PSEUDO_COLUMNS
+ or statement.get_disallowed_functions(set(SEQUENCE_FUNCTIONS))
+ )
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """
+ Whether the transform contains a balanced Jinja block.
+
+ A block is an opening delimiter followed, anywhere later, by its closing
+ one -- the same thing ``{{.*?}}`` and its two siblings match under
+ ``re.DOTALL``. Scanned with `str.find` rather than that pattern, because a
+ lazy match retried from every opening delimiter is quadratic in a run of
+ them, and this runs on stored transforms with no length bound of its own:
+ `is_transform_active` reads whatever the column holds. The earliest opening
+ delimiter is the only one worth trying, since any closing delimiter after a
+ later one is also after it.
+ """
+ if not transform:
+ return False
+ for opening, closing in JINJA_BLOCK_DELIMITERS:
+ start = transform.find(opening)
+ if start != -1 and transform.find(closing, start + len(opening)) != -1:
+ return True
+ return False
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+
+ Three spellings have to be looked for, because one name reaches the parse
+ three ways: as a function call, as a zero-argument call a dialect resolves
+ itself, and -- for the datetime keywords -- as a bare word that parses as a
+ column reference.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ # The parenthesis-free spellings, which parse as columns rather than
+ # functions and so are invisible to the walk above. See
+ # `BARE_WALL_CLOCK_KEYWORDS`.
+ found |= {
+ name.upper() for name in BARE_WALL_CLOCK_KEYWORDS & statement.get_column_names()
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ # An array holds no scalar a transform could return, so no mirror onto it
+ # can ever compare. Refused for the mapping rather than only per value, so
+ # the Explore glyph stops promising one: a probe of ``:value`` succeeds and
+ # records a working transform, and only the later type gate declined.
+ if declares_array_type(columns_by_name[partition_column].type):
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error( # noqa: C901
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ And it must be a *read*. Shape is a separate question from effect: a bare
+ scalar expression can still write, so `SQLStatement.is_mutating` is asked
+ too -- the same question SQL Lab and the chart executor ask before letting
+ SQL run. See the gate itself for what that reaches and what it does not.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ # Also ahead of the parse, and for a stronger reason than cost: every gate
+ # below reasons about the parse tree, and this is the one construct that
+ # makes the parse tree describe a different statement from the one the
+ # engine runs. Checked here as well as in `validate_transform` because this
+ # is the door a row written by an earlier release still comes through.
+ if contains_executable_comment(transform):
+ return str(
+ _(
+ "A partition value transform cannot contain a MySQL "
+ "executable comment, which the database executes and every "
+ "validator reads as a comment."
+ )
+ )
+
+ if contains_unicode_escaped_identifier(transform):
+ return str(
+ _(
+ "A partition value transform cannot name anything through a "
+ 'U&"..." escape sequence, which the database decodes and '
+ "every validator reads literally."
+ )
+ )
+
+ # Same door, same reason: the name the denylist below would match is not
+ # the name the engine resolves. See `UNICODE_ESCAPED_IDENTIFIER_RE`.
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The read-only gate, which nothing above implies. The shape gates ask what
+ # the transform *selects*; this asks what evaluating it *does*, and a bare
+ # scalar expression can still write. `nextval(:value)` on PostgreSQL
+ # advances a sequence: one function call, no clause, no sub-query, and not
+ # in the default `DISALLOWED_SQL_FUNCTIONS` either -- so every gate above
+ # passes it and the probe then runs it. `setval` is the same shape, and
+ # `exp.Execute` and the opaque-`exp.Command` forms arrive the same way.
+ #
+ # The large-object writers (`lo_export`, `lowrite`, `lo_from_bytea`, ...)
+ # are caught here too, and the shipped denylist happens to name them as
+ # well -- but that is config an operator can replace, while this is not.
+ #
+ # `is_mutating` is the same question SQL Lab, `get_virtual_table_metadata`
+ # and the chart executor ask before letting SQL run, so a transform is held
+ # to the bar the rest of Superset already sets rather than to one invented
+ # here. Unconditional rather than gated on `Database.allow_dml`: a transform
+ # is a scalar function of `:value` by definition, so there is no legitimate
+ # mutating one, and the probe runs on a cache schedule nobody chose -- a
+ # write would repeat every time the entry expired.
+ #
+ # It bears saying what this does not reach. A user-defined function whose
+ # body writes is a plain call no parser can tell from `lower(:value)`, and
+ # `is_mutating`'s function-name walk is PostgreSQL-only by design, since the
+ # same names are read-only elsewhere. Neither residual is specific to this
+ # feature -- a dataset editor can already have the engine evaluate an
+ # arbitrary expression through a calculated column or a virtual dataset's
+ # SQL -- and closing them means authorizing the preview against the
+ # database, not parsing harder.
+ if statement.is_mutating():
+ return str(
+ _(
+ "A partition value transform cannot change data. It is "
+ "evaluated against the database to check that it mirrors, so "
+ "it has to be a read."
+ )
+ )
+
+ # Not reached by the walk above, which is why it is its own gate: a
+ # sequence pseudo-column is a *column* to the parser and a write to the
+ # engine. See `SEQUENCE_PSEUDO_COLUMNS`.
+ if references_sequence(statement):
+ return str(
+ _(
+ "A partition value transform cannot read a sequence. "
+ "NEXTVAL advances the sequence every time it is evaluated, "
+ "and the transform is evaluated on a cache schedule."
+ )
+ )
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the
+ probe uninspected. Rendering is not what makes that true: a string element
+ is checked by `literal_round_trips` before it is rendered -- the dialect's
+ literal processor and the engine's lexer do not always agree about what a
+ rendered literal says -- and `probe_sql_is_evaluable` re-reads the finished
+ query, which is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def _placeholder_is_bindable(transform: str) -> bool:
+ """
+ Whether SQLAlchemy's ``text()`` can see ``:value`` as a bound parameter.
+
+ `VALUE_PLACEHOLDER_RE` is ``:value\b``, which matches the placeholder in a
+ Postgres cast such as ``:value::bigint``. SQLAlchemy's own bind scan is
+ ``(?<![:\\w$]):([\\w$]+)(?![:\\w$])`` -- note the trailing exclusion -- so a
+ following colon stops it: ``text(":value::bigint")`` reports a parameter
+ named ``valu``, and ``.bindparams(bindparam("value"))`` then raises
+ ``ArgumentError``.
+
+ `_probe` swallows that, so the only symptom was a perfectly valid transform
+ whose mapping silently never pruned, and a preview reporting an engine
+ failure for SQL that was never sent. Every write-side gate passes the
+ transform: it parses, it is a bare expression, and the placeholder *is* in
+ an executable position.
+
+ Answered by attempting the bind itself rather than by pattern-matching
+ ``::`` or reading ``text()``'s private parameter map, so this cannot
+ disagree with what `build_probe_sql` is about to do -- on any dialect, or on
+ a SQLAlchemy whose scan changes.
+ """
+ try:
+ sa.text(transform).bindparams(sa.bindparam("value", value=None))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return False
+ return True
+
+
+def escape_foreign_colons(transform: str) -> str:
+ """
+ ``transform`` with every colon but the ``:value`` placeholder escaped.
+
+ `sqlalchemy.text` reads any ``:word`` as a bind parameter, including one
+ inside a string literal, and an unbound parameter renders as ``NULL``
+ under literal binds rather than raising. So ``:value || \':suffix\'``
+ compiled to ``'us' || 'NULL'``: the mirror asked for a partition value no
+ row holds and the chart dropped rows, with no error for `_probe` to
+ swallow and nothing on screen to say so.
+
+ Escaped rather than refused, because a colon in a literal is ordinary --
+ ``concat(:value, \':\', region)`` builds a composite key -- and the
+ placeholder is the only colon this module means to interpret. `text()`
+ reads ``\\:`` as a literal colon.
+
+ Only the bound path needs this. A `RawProbeValue` or an unbindable
+ placeholder is substituted as text by `parse_skeleton`, which never hands
+ the transform to `text()` at all.
+ """
+ pieces: list[str] = []
+ cursor = 0
+ for match in VALUE_PLACEHOLDER_RE.finditer(transform):
+ pieces.append(transform[cursor : match.start()].replace(":", r"\:"))
+ pieces.append(match.group(0))
+ cursor = match.end()
+ pieces.append(transform[cursor:].replace(":", r"\:"))
+ return "".join(pieces)
+
+
+def literal_round_trips(value: Any, dialect: Dialect | None, engine: str) -> bool:
+ """
+ Whether the engine reads a rendered ``value`` back as that same value.
+
+ The probe runs with no bound parameters, so every value reaches the engine
+ as literal text the driver wrote (see `build_probe_sql`). Whether that text
+ says what the value says is a question about two independent spellings: the
+ driver's escaping, and the engine's lexer. SQLAlchemy's default renderer
+ doubles apostrophes and passes backslashes through; Hive and Spark honour
+ the backslash and not the doubling, so ``'O''Brien'`` is read there as two
+ adjacent literals -- the transform is evaluated at ``OBrien``, and the
+ mirror asks for a partition key that holds none of the rows the filter
+ keeps. The same gap in the other direction lets a value close its own quote
+ and have the rest of it read as SQL.
+
+ Escaping is not the repair. Whether a backslash introduces an escape is a
+ per-session server setting -- ``standard_conforming_strings`` on Postgres,
+ ``NO_BACKSLASH_ESCAPES`` on MySQL, ``escapedStringLiterals`` on Spark -- and
+ nothing in the engine specs exposes it. SQLAlchemy reads it off the server
+ into ``_backslash_escapes`` during ``initialize(connection)``, which the
+ probe's dialect never reaches: `_dialect_for` asks the ``Database`` for a
+ dialect, not for a connection, so Postgres renders ``a\\b`` as
+ ``'a\\\\b'`` and a server with the standard setting reads four
+ characters. An engine-spec flag would have to be defaulted, and either
+ default is wrong for a dozen engines: one leaves the hole open, the other
+ corrupts the probed value.
+
+ So the premise is verified rather than declared, the way
+ `probe_sql_is_evaluable` verifies the finished statement. A value that does
+ not survive the round trip is not mirrored, which costs the query its
+ pruning and nothing else.
+
+ The short-circuit is a proof, not a guess, and it matters for cost: a
+ 200-member ``IN`` list would otherwise parse 200 times on the chart path.
+ If the renderer emitted the value between two quotes and changed nothing in
+ it, and the value carries neither a quote nor a backslash, then no lexer in
+ play can read it as anything but itself. Both exclusions are load-bearing:
+ on Hive ``a\\b`` renders verbatim and reads as ``a`` followed by a
+ backspace.
+
+ :param value: a filter value about to be rendered into the probe
+ :param dialect: the dialect that will render it, as `_dialect_for` reports
+ :param engine: ``database.backend``, whose lexer reads the result
+ :return: whether the two agree about what the literal says
+ """
+ if isinstance(value, RawProbeValue):
+ # Already SQL, with no single value for a parse to be compared against:
+ # its elements are checked before they are rendered, by
+ # `ExploreMixin._array_mirror_probe_value`. A backslash surviving into
+ # the finished text is refused here all the same, as the backstop for a
+ # renderer this module does not own.
+ return "\\" not in value.sql
+ if not isinstance(value, str):
+ # Numbers and instants are not written between delimiters, so there is
+ # no escaping for the two sides to disagree about.
+ return True
+
+ rendered = _compile_literal(sa.literal(value), dialect)
+ if rendered == f"'{value}'" and "'" not in value and "\\" not in value:
+ return True
+
+ try:
+ return (
+ SQLStatement(f"SELECT {rendered}", engine).get_select_literal_value()
+ == value
+ )
+ except SupersetParseError:
+ # A rendered literal the engine's own dialect will not parse is the
+ # strongest form of disagreement there is.
+ return False
+
+
+def value_round_trips(database: Database, value: Any) -> bool:
+ """
+ `literal_round_trips` for a caller holding a database, not a dialect.
+
+ Which renderer and which lexer apply is this module's business, so the two
+ callers outside it -- the chart path's own gate in
+ `ExploreMixin.mirror_probe_request` and the mapping summary Explore reads
+ -- ask in these terms and stay out of it.
+
+ :param database: the database whose driver renders and whose engine reads
+ :param value: a filter value about to be rendered into the probe
+ :return: whether the two agree about what the literal says
+ """
+ return literal_round_trips(value, _dialect_for(database), database.backend)
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text. That is not itself a boundary:
+ the processor's escaping is not always the escaping the engine honours, and
+ a value can close its own quote through the gap. The boundary is
+ `literal_round_trips` on the way in -- which callers must have run, like
+ `stored_expression_error` below -- and `probe_sql_is_evaluable` on the way
+ out.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ bindable = _placeholder_is_bindable(transform)
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ elif bindable:
+ # Every other colon escaped first: `text()` would read one inside a
+ # string literal as a second bind parameter and render it `NULL`.
+ # See `escape_foreign_colons`.
+ clause = sa.text(escape_foreign_colons(transform)).bindparams(
+ sa.bindparam("value", value=value)
+ )
+ rendered = _compile_literal(clause, dialect)
+ else:
+ # `text()` cannot see the placeholder (see
+ # `_placeholder_is_bindable`), so the value is rendered by the
+ # dialect's own literal processor first and substituted as SQL
+ # text. The same two steps in the other order: binding exists to
+ # get the value through that processor, and `_compile_literal`
+ # inlines the result either way, so this is the same string by a
+ # different route -- not a loosening of the "never interpolate a
+ # raw value" rule. `parse_skeleton` substitutes literally, so the
+ # rendered literal arrives here exactly as it was rendered, which
+ # is what makes `literal_round_trips`' verdict on it good for this
+ # branch as much as for the bound one.
+ rendered = parse_skeleton(
+ transform, _compile_literal(sa.literal(value), dialect)
+ )
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Five things have to hold, and all five are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+ * No comment, anywhere. A value that closes its own quote has to hide the
+ text `build_probe_sql` appended after it, and a comment is the only way
+ to do that and still balance the quotes -- so this is what makes the
+ alias check above sufficient rather than merely necessary. Read off the
+ parse rather than the text, so a comment *inside* a literal is data and
+ costs no pruning, and so the question is asked in the engine's own
+ dialect. A transform has no legitimate reason to carry one either; see
+ `EXECUTABLE_COMMENT_RE`.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ # Before the parse, because this gate's whole contract is that what the
+ # parse describes is what the engine will run, and an executable comment is
+ # precisely the text where that stops being true. The transform is already
+ # refused for carrying one; this covers the compiled statement, so no later
+ # change to how values are rendered can reintroduce it behind the gates
+ # below.
+ if contains_executable_comment(sql) or contains_unicode_escaped_identifier(sql):
+ return False
+
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if not isinstance(statement, SQLStatement):
+ # A dialect whose statements this gate cannot take apart -- KQL -- gets
+ # no probe rather than an unchecked one. It never had one: the clause
+ # inspection below is implemented for SQL statements only, and the
+ # alternative to declining here is an `AttributeError` that `_probe`
+ # swallows into the same outcome, less legibly.
+ return False
+ if statement.has_comment():
+ return False
+ if statement.has_subquery():
+ return False
+ if statement.get_clause_names() - {"from"}:
+ return False
+ if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+ """
+ The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+ Parsed rather than string-compared so that the comparison in
+ `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+ not parse answers ``None``, which no statement carrying a FROM can match --
+ the probe then declines, which is the right way for an unreadable engine
+ constant to fail.
+ """
+ if not from_suffix.strip():
+ return None
+ try:
+ return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+ except SupersetParseError:
+ return None
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+ text_answers: list[tuple[int, Any]] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ :param text_answers: optional sink. When given, every date or timestamp in
+ ``values`` is also asked as the text a simple filter would bind, in the
+ same round trip, and ``(index, answer)`` is appended for each -- see
+ `_declined_for_reading_by_type` for why. A transform that refuses text
+ is asked again with ``values`` alone, so a refusal never costs pruning.
+ """
+ if not values:
+ return None
+
+ if text_answers is not None:
+ indexes = [
+ index
+ for index, value in enumerate(values)
+ if isinstance(value, date) and not is_unmirrorable(value)
+ ]
+ if indexes:
+ combined = evaluate_transform(
Review Comment:
On Oracle, `CAST(:value AS DATE)` and `TRUNC(:value, 'HH')` evaluate a typed bound but fail on its text form (ORA-01861, ORA-01722), so every time-range chart reruns this failing probe (failures are not cached) and stores `evaluable=false`, hiding the glyph while queries still prune.
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,3889 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Writing the value into the probe
+--------------------------------
+The probe evaluates the transform at a *literal*, because it runs with no bound
+parameters at all -- so every value is written into SQL text by the driver's
+literal renderer and read back by the engine's lexer, and the two do not always
+agree. SQLAlchemy's default renderer doubles apostrophes and leaves backslashes
+alone; Hive honours backslash escapes and not doubling, so ``'O''Brien'`` is
+read there as two adjacent literals and ``'x\\''`` ends four characters into a
+value the filter carries whole. A disagreement is either a mirror built from a
+value nobody filtered on -- dropping rows the filter keeps -- or, where the
+value closes its own quote, an expression of the filterer's choosing running in
+the probe.
+
+Which side is right is not knowable from the driver: it is a per-session server
+setting (``standard_conforming_strings``, ``NO_BACKSLASH_ESCAPES``,
+``spark.sql.parser.escapedStringLiterals``), and SQLAlchemy's own view of it is
+only correct on a dialect that has connected. So escaping is not what makes
+this safe. `literal_round_trips` renders the literal and reads it back in the
+engine's own dialect instead, and a value that does not survive the trip is not
+mirrored -- the usual trade, pruning for correctness. `probe_sql_is_evaluable`
+re-reads the finished statement behind it.
+
+The probe's *answers* make the same trip, in the other direction. The chart
+query is compiled with ``literal_binds``, so a probed partition key is rendered
+into its SQL by the same renderer and read by the same lexer -- and
+``concat(:value, chr(92), 'b')`` turns the unremarkable input ``a`` into the key
+``a\\b``, which Hive reads back as ``a`` followed by a backspace. So
+`_predicates_from_probe` asks `literal_round_trips` about each result too, and
+declines the request rather than emitting a predicate no row can satisfy: the
+mirror is ``AND``-ed onto the query, so a mirror that matches nothing costs the
+chart its rows rather than its pruning.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Mapping, Sequence
+from dataclasses import dataclass
+from datetime import date, datetime, time, timedelta
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: The opening and closing delimiters of each kind of Jinja block. The probe
+#: would render these in a different context at a different time from the chart
+#: query, so a transform holding one is rejected at save time.
+JINJA_BLOCK_DELIMITERS = (("{{", "}}"), ("{%", "%}"), ("{#", "#}"))
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: A PostgreSQL Unicode-escaped identifier, ``U&"..."``.
+#:
+#: The second construct that breaks the premise above, and in the same way:
+#: ``U&"\\0071uery_to_xml"(...)`` parses as an anonymous function whose name is
+#: the *literal* ``\\0071uery_to_xml``, so the function denylist is matching a
+#: name the engine never sees -- PostgreSQL decodes the escape and runs
+#: ``query_to_xml``, handing a dataset owner rows from outside their RLS scope
+#: through the preview's ``emitted_predicate``.
+#:
+#: Normalizing the escapes and re-checking would be the other repair, and is
+#: worse: it means reimplementing one engine's identifier decoding well enough
+#: to be a security boundary. Refusing the construct is exact, and costs
+#: nothing real -- a transform is a scalar function of ``:value``, and there is
+#: no reason to name a function or column through an escape sequence.
+#:
+#: Refused on every engine, like the executable comment, so a transform stored
+#: on SQLite cannot detonate when the dataset is re-pointed at PostgreSQL. The
+#: ``&`` may be separated from the ``U`` by nothing at all, but whitespace or a
+#: comment between the prefix and the string is not accepted by PostgreSQL
+#: either, so the strict form is the whole surface.
+#:
+#: Matched in raw text, so the prefix is refused inside a string literal too.
+#: That is the same trade the executable comment makes and has the same
+#: justification: a gate whose contract is to fire *before* the parse cannot
+#: ask the parse whether the text was quoted. ``concat(:value, 'u&"x"')`` is
+#: refused, which costs an owner nothing anyone writes.
+UNICODE_ESCAPED_IDENTIFIER_RE = re.compile(r'\bU&"', re.IGNORECASE)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate: a transform such as
+#: ``datediff(day, :value, LOCALTIMESTAMP)`` for a relative partition key is
+#: evaluated once and then keeps emitting yesterday's answer, so the chart
+#: silently drops rows after midnight.
+#:
+#: Matched by SQL function name, so every engine's spelling of "now" has to be
+#: named -- the ANSI four were not enough. Listed rather than delegated to the
+#: engine specs because the risk is the same everywhere and a spec that had not
+#: got round to declaring its own would fail open; a name no engine has is
+#: inert, so over-listing costs nothing.
+NON_DETERMINISTIC_FUNCTIONS = {
+ # ANSI, and the engines that spell it this way.
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "LOCALTIME",
+ "LOCALTIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+ # PostgreSQL. `now()` is statement-stable; these two are not even that.
+ "CLOCK_TIMESTAMP",
+ "STATEMENT_TIMESTAMP",
+ "TIMEOFDAY",
+ # MySQL and MariaDB.
+ "CURDATE",
+ "CURTIME",
+ "SYSDATE",
+ "UTC_DATE",
+ "UTC_TIME",
+ "UTC_TIMESTAMP",
+ "UUID_SHORT",
+ # Oracle.
+ "SYSTIMESTAMP",
+ "SYS_GUID",
+ # SQL Server.
+ "GETDATE",
+ "GETUTCDATE",
+ "SYSDATETIME",
+ "SYSUTCDATETIME",
+ "SYSDATETIMEOFFSET",
+ "NEWID",
+ # BigQuery.
+ "CURRENT_DATETIME",
+ "GENERATE_UUID",
+ # Snowflake.
+ "RANDSTR",
+ "UUID_STRING",
+ # ClickHouse.
+ "NOW64",
+ "RANDCANONICAL",
+ "GENERATEUUIDV4",
+ # H2 and Derby, which the test fixtures use.
+ "RANDOM_UUID",
+}
+
+#: The wall-clock names an engine evaluates with no parentheses at all.
+#:
+#: These parse as *column references*, not functions, so the name-based walk
+#: below cannot see them: `datediff(UTC_DATE, :value)` on MySQL and
+#: `:value - SYSDATE` on Oracle both cleared the gate and froze probe time into
+#: a cached mirror.
+#:
+#: A subset of `NON_DETERMINISTIC_FUNCTIONS` rather than the whole of it,
+#: because refusing a bare name costs an owner a column genuinely called that.
+#: Only the names SQL lets you write without ``()`` are listed -- the datetime
+#: keywords -- so `rand`, `uuid` and `newid`, which always need parentheses and
+#: are plausible column names, stay out.
+BARE_WALL_CLOCK_KEYWORDS = frozenset(
+ {
+ "current_date",
+ "current_time",
+ "current_timestamp",
+ "localtime",
+ "localtimestamp",
+ "utc_date",
+ "utc_time",
+ "utc_timestamp",
+ "sysdate",
+ "systimestamp",
+ }
+)
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+class Unmirrorable:
+ """
+ A filter no mirror can stand in for, and why.
+
+ Returned by `ExploreMixin.mirror_probe_request` for a value the engine
+ compares more coarsely than the filter carries, one it cannot render as a
+ literal, one whose rendered literal the engine would not read back as the
+ same value, one in a time frame the transform would discard, or an ``IN``
+ list with a member of any of those kinds. An object rather than `None`,
+ because `None` is a filter value in its own right.
+
+ The reason rides along because the preview has to explain the decline to
+ the owner, and the two declines want different advice: "the engine compares
+ less of this value than you typed, so map a column it compares in full" is
+ sound guidance for a `DATE` column and actively misleading for an
+ offset-bearing bound on a `TIMESTAMP` one, which already is such a column.
+ Carried rather than re-derived so the preview's explanation cannot come
+ apart from the chart path's decision.
+
+ Lives here rather than beside that method so the preview can read it too:
+ `superset.models.helpers` imports this module, so these can only cross the
+ boundary in this direction. Both callers recognise the same instances -- a
+ preview that answered "valid" for a request the chart path declines is the
+ drift this is here to prevent.
+ """
+
+ __slots__ = ("reason",)
+
+ def __init__(self, reason: str) -> None:
+ self.reason = reason
+
+ def __repr__(self) -> str:
+ return f"<Unmirrorable {self.reason}>"
+
+
+#: The ordinary decline: whatever the mirror cannot be built from, with the
+#: engine's own comparison resolution as the reason an owner can act on.
+UNMIRRORABLE = Unmirrorable("resolution")
+
+#: A value carrying a UTC offset, declined whatever the column's resolution.
+#: A transform such as ``CAST(:value AS TIMESTAMP)`` drops the offset, so even
+#: an engine that compares the whole instant would be probed in the wrong
+#: frame -- which is not something mapping a different column fixes.
+UNMIRRORABLE_OFFSET = Unmirrorable("offset")
+
+#: A value the driver and the engine would not spell the same way, declined
+#: whatever the column's resolution and whatever the operator. Nothing about
+#: the column or the transform fixes it -- see `literal_round_trips` -- so the
+#: advice the resolution reason carries would send an owner after the wrong
+#: thing entirely.
+UNMIRRORABLE_ESCAPING = Unmirrorable("escaping")
+
+
+def is_unmirrorable(value: Any) -> bool:
+ """Whether `mirror_probe_request` declined this request."""
+ return isinstance(value, Unmirrorable)
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def _native_generic_type(
+ column: "TableColumn",
+) -> utils.GenericDataType | None:
+ """
+ What the engine spec makes of ``column``'s declared type.
+
+ `TableColumn.type_generic` answers ``TEMPORAL`` for every column carrying
+ ``is_dttm``, which is the right answer for a chart's time axis and the
+ wrong one for a comparison: an epoch ``BIGINT`` is a number to the engine
+ however it is labelled here. Falls back to the flag where the spec has no
+ answer, so a type Superset cannot resolve is no worse off than before.
+ """
+ try:
+ column_spec = column.db_engine_spec.get_column_spec(
+ column.type, db_extra=column.db_extra
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ column_spec = None
+ if column_spec is not None and column_spec.generic_type is not None:
+ return column_spec.generic_type
+ try:
+ return column.type_generic
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+#: A declared type naming an array: PostgreSQL's ``TEXT[]`` / ``INTEGER[][]``
+#: / ``int[3]``, and the ``ARRAY<...>`` / ``ARRAY(...)`` / ``Array(...)``
+#: spellings of Hive, Spark, Trino, BigQuery and ClickHouse.
+#: The bracket body is written so no two runs can match the same blanks:
+#: ``\s*\d*\s*`` backtracks polynomially on a long run of spaces.
+_ARRAY_TYPE_RE = re.compile(r"(?:\[\s*(?:\d+\s*)?\])+\s*$|^\s*ARRAY\b", re.IGNORECASE)
+
+
+def declares_array_type(column_type: str | None) -> bool:
+ """
+ Whether a declared column type is an array, whatever the engine spec says.
+
+ The engine spec only reports ``MULTI_VALUE`` where it has opted into
+ ``supports_multivalue_columns``; PostgreSQL has not, and resolves ``TEXT[]``
+ to ``STRING`` and ``INTEGER[]`` to ``NUMERIC``. So an array partition column
+ there cleared the array refusal, previewed valid, and every equality chart
+ on the mapping failed with ``malformed array literal``. The declared type
+ is what the engine will compare, so it is read directly as well.
+ """
+ return bool(column_type and _ARRAY_TYPE_RE.search(column_type))
+
+
+#: Declared types whose comparison ignores trailing blanks.
+#:
+#: The fixed-width character types, which the SQL standard has compare as
+#: though both sides were padded to the same length -- so ``'US'`` and
+#: ``'US '`` are equal in a ``CHARACTER(3)``, while ``lower()`` of the two is
+#: not. Spelled out rather than matched by prefix because the variable-width
+#: names start with the same letters: ``VARCHAR`` and ``CHARACTER VARYING``
+#: compare the blanks and must not land here.
+PADDED_CHARACTER_TYPES = frozenset(
+ {
+ "CHAR",
+ "NCHAR",
+ # PostgreSQL's own name for ``CHARACTER``, which is what reflection
+ # reports for a ``CHAR(n)`` column there.
+ "BPCHAR",
+ "CHARACTER",
+ "NATIONAL CHAR",
+ "NATIONAL CHARACTER",
+ }
+)
+
+
+def _is_padded_character_type(column: TableColumn) -> bool:
+ """
+ Whether ``column``'s declared type compares without its trailing blanks.
+
+ Read off the declared type rather than the engine spec's resolved one: the
+ specs map ``CHAR`` and ``VARCHAR`` onto the same `sqlalchemy.String`, so
+ the distinction this needs is gone by then. The length suffix is dropped
+ and the name matched against `PADDED_CHARACTER_TYPES`, so an unfamiliar
+ spelling answers ``False`` and the engine-level flag decides as before --
+ this gate adds a decline rather than lifting one. A column with no
+ declared type has nothing to read, and answers the same way.
+ """
+ if not isinstance(column.type, str):
+ return False
+ native = re.sub(r"\s+", " ", column.type.strip().upper())
+ return native.split("(")[0].strip() in PADDED_CHARACTER_TYPES
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ Padding is asked about per column, because it is a property of the *type*
+ rather than of the engine. ``binary_string_comparison`` speaks for an
+ engine's default text comparison, and on PostgreSQL -- which declares it
+ -- a ``CHAR(2)`` still matches a filter for ``'US '`` against a stored
+ ``'US'``, because the standard says a padded character type compares
+ without its trailing blanks. The mirror ``region_key = lower('US ')`` then
+ excludes the row. So a fixed-width character type declines whatever the
+ engine says, and an engine that ignores trailing blanks on its *variable*
+ types says so by not declaring the flag at all (see `RedshiftEngineSpec`).
+
+ The type asked for is the engine spec's reading of the column's declared
+ type, not `TableColumn.type_generic`, which answers ``TEMPORAL`` for
+ anything carrying ``is_dttm``. A ``VARCHAR`` flagged temporal is still text
+ to the engine: on MySQL a filter for ``'2026-01-01T00:00:00'`` matches a
+ stored ``'...t00:00:00'``, while the mirror ``p = hex('...T...')`` excludes
+ it -- and asking the semantic flag skipped the check entirely.
+
+ A type the spec cannot classify declines, which is what the paragraph above
+ promises and what only the exception branch used to do. PostgreSQL's
+ ``citext`` matches no type pattern, so it answered ``None`` -- neither
+ string nor not-string -- and was waved through, which is precisely wrong
+ for a type whose whole purpose is case-insensitive comparison. Declining
+ costs the pruning; admitting it costs rows.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ # Ahead of the generic-type question, which a padded type can lose: the
+ # specs map ``CHARACTER`` onto no generic type at all on some engines, and
+ # a fixed-width character type is a string whether or not Superset can say
+ # so from the name.
+ if _is_padded_character_type(column):
+ return False
+ generic_type = _native_generic_type(column)
+ if generic_type is None:
+ return False
+ if generic_type != utils.GenericDataType.STRING:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_unicode_escaped_identifier(transform: str | None) -> bool:
+ """Whether the transform names something through a ``U&"..."`` escape.
+
+ See `UNICODE_ESCAPED_IDENTIFIER_RE`. Answered on raw text for the same
+ reason as the comment above: the parse reports a name the engine does not
+ use, which is exactly what makes the denylist blind to it.
+ """
+ return (
+ bool(transform)
+ and UNICODE_ESCAPED_IDENTIFIER_RE.search(transform or "") is not None
+ )
+
+
+#: Sequence pseudo-columns, which advance a sequence when they are *read*.
+#:
+#: ``orders_seq.NEXTVAL`` parses as a qualified column reference, not a
+#: function call, so neither `SQLStatement.is_mutating` -- which walks function
+#: names -- nor the function denylist can see it. The probe would then run
+#: ``SELECT orders_seq.NEXTVAL + 1 FROM DUAL`` and advance the sequence, again
+#: on every cache expiry, for a dataset editor holding neither SQL Lab nor a
+#: DML grant. Reading one is a write however the parser classifies it.
+#:
+#: The function spelling (``nextval('s')`` on PostgreSQL) is a different shape
+#: and is caught as a function; this is only about the suffix form.
+SEQUENCE_PSEUDO_COLUMNS = frozenset({"nextval", "currval"})
+
+#: The same thing written as a call.
+#:
+#: Only the suffix form parses as a column; `nextval('s')` on PostgreSQL and
+#: DuckDB, `NEXTVAL(s)`/`SETVAL(s, 1)` on MySQL and MariaDB, and SQL Server's
+#: `NEXT VALUE FOR s` all parse as functions. `SQLStatement.is_mutating` walks
+#: function names on PostgreSQL alone -- deliberately, since the same names are
+#: read-only elsewhere -- so every other engine let these through.
+#:
+#: Matched on the name whatever the engine, because advancing a sequence is a
+#: write wherever it happens and a transform has no reason to call one.
+SEQUENCE_FUNCTIONS = frozenset(
+ {"nextval", "setval", "next_value_for", "nextvalfor", "prevval", "lastval"}
+)
+
+
+def references_sequence(statement: SQLStatement) -> bool:
+ """Whether the statement reads or advances a sequence.
+
+ Both spellings: the pseudo-column suffix, which parses as a column (see
+ `SEQUENCE_PSEUDO_COLUMNS`), and the call, which parses as a function (see
+ `SEQUENCE_FUNCTIONS`).
+
+ Answered on the parse rather than on raw text, because position is what
+ makes it the construct: a column or alias merely *called* ``nextval`` is
+ an ordinary column, and a string literal holding the word is text.
+ """
+ return bool(
+ statement.get_column_names() & SEQUENCE_PSEUDO_COLUMNS
+ or statement.get_disallowed_functions(set(SEQUENCE_FUNCTIONS))
+ )
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """
+ Whether the transform contains a balanced Jinja block.
+
+ A block is an opening delimiter followed, anywhere later, by its closing
+ one -- the same thing ``{{.*?}}`` and its two siblings match under
+ ``re.DOTALL``. Scanned with `str.find` rather than that pattern, because a
+ lazy match retried from every opening delimiter is quadratic in a run of
+ them, and this runs on stored transforms with no length bound of its own:
+ `is_transform_active` reads whatever the column holds. The earliest opening
+ delimiter is the only one worth trying, since any closing delimiter after a
+ later one is also after it.
+ """
+ if not transform:
+ return False
+ for opening, closing in JINJA_BLOCK_DELIMITERS:
+ start = transform.find(opening)
+ if start != -1 and transform.find(closing, start + len(opening)) != -1:
+ return True
+ return False
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+
+ Three spellings have to be looked for, because one name reaches the parse
+ three ways: as a function call, as a zero-argument call a dialect resolves
+ itself, and -- for the datetime keywords -- as a bare word that parses as a
+ column reference.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ # The parenthesis-free spellings, which parse as columns rather than
+ # functions and so are invisible to the walk above. See
+ # `BARE_WALL_CLOCK_KEYWORDS`.
+ found |= {
+ name.upper() for name in BARE_WALL_CLOCK_KEYWORDS & statement.get_column_names()
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ # An array holds no scalar a transform could return, so no mirror onto it
+ # can ever compare. Refused for the mapping rather than only per value, so
+ # the Explore glyph stops promising one: a probe of ``:value`` succeeds and
+ # records a working transform, and only the later type gate declined.
+ if declares_array_type(columns_by_name[partition_column].type):
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error( # noqa: C901
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ And it must be a *read*. Shape is a separate question from effect: a bare
+ scalar expression can still write, so `SQLStatement.is_mutating` is asked
+ too -- the same question SQL Lab and the chart executor ask before letting
+ SQL run. See the gate itself for what that reaches and what it does not.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ # Also ahead of the parse, and for a stronger reason than cost: every gate
+ # below reasons about the parse tree, and this is the one construct that
+ # makes the parse tree describe a different statement from the one the
+ # engine runs. Checked here as well as in `validate_transform` because this
+ # is the door a row written by an earlier release still comes through.
+ if contains_executable_comment(transform):
+ return str(
+ _(
+ "A partition value transform cannot contain a MySQL "
+ "executable comment, which the database executes and every "
+ "validator reads as a comment."
+ )
+ )
+
+ if contains_unicode_escaped_identifier(transform):
+ return str(
+ _(
+ "A partition value transform cannot name anything through a "
+ 'U&"..." escape sequence, which the database decodes and '
+ "every validator reads literally."
+ )
+ )
+
+ # Same door, same reason: the name the denylist below would match is not
+ # the name the engine resolves. See `UNICODE_ESCAPED_IDENTIFIER_RE`.
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The read-only gate, which nothing above implies. The shape gates ask what
+ # the transform *selects*; this asks what evaluating it *does*, and a bare
+ # scalar expression can still write. `nextval(:value)` on PostgreSQL
+ # advances a sequence: one function call, no clause, no sub-query, and not
+ # in the default `DISALLOWED_SQL_FUNCTIONS` either -- so every gate above
+ # passes it and the probe then runs it. `setval` is the same shape, and
+ # `exp.Execute` and the opaque-`exp.Command` forms arrive the same way.
+ #
+ # The large-object writers (`lo_export`, `lowrite`, `lo_from_bytea`, ...)
+ # are caught here too, and the shipped denylist happens to name them as
+ # well -- but that is config an operator can replace, while this is not.
+ #
+ # `is_mutating` is the same question SQL Lab, `get_virtual_table_metadata`
+ # and the chart executor ask before letting SQL run, so a transform is held
+ # to the bar the rest of Superset already sets rather than to one invented
+ # here. Unconditional rather than gated on `Database.allow_dml`: a transform
+ # is a scalar function of `:value` by definition, so there is no legitimate
+ # mutating one, and the probe runs on a cache schedule nobody chose -- a
+ # write would repeat every time the entry expired.
+ #
+ # It bears saying what this does not reach. A user-defined function whose
+ # body writes is a plain call no parser can tell from `lower(:value)`, and
+ # `is_mutating`'s function-name walk is PostgreSQL-only by design, since the
+ # same names are read-only elsewhere. Neither residual is specific to this
+ # feature -- a dataset editor can already have the engine evaluate an
+ # arbitrary expression through a calculated column or a virtual dataset's
+ # SQL -- and closing them means authorizing the preview against the
+ # database, not parsing harder.
+ if statement.is_mutating():
+ return str(
+ _(
+ "A partition value transform cannot change data. It is "
+ "evaluated against the database to check that it mirrors, so "
+ "it has to be a read."
+ )
+ )
+
+ # Not reached by the walk above, which is why it is its own gate: a
+ # sequence pseudo-column is a *column* to the parser and a write to the
+ # engine. See `SEQUENCE_PSEUDO_COLUMNS`.
+ if references_sequence(statement):
+ return str(
+ _(
+ "A partition value transform cannot read a sequence. "
+ "NEXTVAL advances the sequence every time it is evaluated, "
+ "and the transform is evaluated on a cache schedule."
+ )
+ )
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the
+ probe uninspected. Rendering is not what makes that true: a string element
+ is checked by `literal_round_trips` before it is rendered -- the dialect's
+ literal processor and the engine's lexer do not always agree about what a
+ rendered literal says -- and `probe_sql_is_evaluable` re-reads the finished
+ query, which is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def _placeholder_is_bindable(transform: str) -> bool:
+ """
+ Whether SQLAlchemy's ``text()`` can see ``:value`` as a bound parameter.
+
+ `VALUE_PLACEHOLDER_RE` is ``:value\b``, which matches the placeholder in a
+ Postgres cast such as ``:value::bigint``. SQLAlchemy's own bind scan is
+ ``(?<![:\\w$]):([\\w$]+)(?![:\\w$])`` -- note the trailing exclusion -- so a
+ following colon stops it: ``text(":value::bigint")`` reports a parameter
+ named ``valu``, and ``.bindparams(bindparam("value"))`` then raises
+ ``ArgumentError``.
+
+ `_probe` swallows that, so the only symptom was a perfectly valid transform
+ whose mapping silently never pruned, and a preview reporting an engine
+ failure for SQL that was never sent. Every write-side gate passes the
+ transform: it parses, it is a bare expression, and the placeholder *is* in
+ an executable position.
+
+ Answered by attempting the bind itself rather than by pattern-matching
+ ``::`` or reading ``text()``'s private parameter map, so this cannot
+ disagree with what `build_probe_sql` is about to do -- on any dialect, or on
+ a SQLAlchemy whose scan changes.
+ """
+ try:
+ sa.text(transform).bindparams(sa.bindparam("value", value=None))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return False
+ return True
+
+
+def escape_foreign_colons(transform: str) -> str:
+ """
+ ``transform`` with every colon but the ``:value`` placeholder escaped.
+
+ `sqlalchemy.text` reads any ``:word`` as a bind parameter, including one
+ inside a string literal, and an unbound parameter renders as ``NULL``
+ under literal binds rather than raising. So ``:value || \':suffix\'``
+ compiled to ``'us' || 'NULL'``: the mirror asked for a partition value no
+ row holds and the chart dropped rows, with no error for `_probe` to
+ swallow and nothing on screen to say so.
+
+ Escaped rather than refused, because a colon in a literal is ordinary --
+ ``concat(:value, \':\', region)`` builds a composite key -- and the
+ placeholder is the only colon this module means to interpret. `text()`
+ reads ``\\:`` as a literal colon.
+
+ Only the bound path needs this. A `RawProbeValue` or an unbindable
+ placeholder is substituted as text by `parse_skeleton`, which never hands
+ the transform to `text()` at all.
+ """
+ pieces: list[str] = []
+ cursor = 0
+ for match in VALUE_PLACEHOLDER_RE.finditer(transform):
+ pieces.append(transform[cursor : match.start()].replace(":", r"\:"))
+ pieces.append(match.group(0))
+ cursor = match.end()
+ pieces.append(transform[cursor:].replace(":", r"\:"))
+ return "".join(pieces)
+
+
+def literal_round_trips(value: Any, dialect: Dialect | None, engine: str) -> bool:
+ """
+ Whether the engine reads a rendered ``value`` back as that same value.
+
+ The probe runs with no bound parameters, so every value reaches the engine
+ as literal text the driver wrote (see `build_probe_sql`). Whether that text
+ says what the value says is a question about two independent spellings: the
+ driver's escaping, and the engine's lexer. SQLAlchemy's default renderer
+ doubles apostrophes and passes backslashes through; Hive and Spark honour
+ the backslash and not the doubling, so ``'O''Brien'`` is read there as two
+ adjacent literals -- the transform is evaluated at ``OBrien``, and the
+ mirror asks for a partition key that holds none of the rows the filter
+ keeps. The same gap in the other direction lets a value close its own quote
+ and have the rest of it read as SQL.
+
+ Escaping is not the repair. Whether a backslash introduces an escape is a
+ per-session server setting -- ``standard_conforming_strings`` on Postgres,
+ ``NO_BACKSLASH_ESCAPES`` on MySQL, ``escapedStringLiterals`` on Spark -- and
+ nothing in the engine specs exposes it. SQLAlchemy reads it off the server
+ into ``_backslash_escapes`` during ``initialize(connection)``, which the
+ probe's dialect never reaches: `_dialect_for` asks the ``Database`` for a
+ dialect, not for a connection, so Postgres renders ``a\\b`` as
+ ``'a\\\\b'`` and a server with the standard setting reads four
+ characters. An engine-spec flag would have to be defaulted, and either
+ default is wrong for a dozen engines: one leaves the hole open, the other
+ corrupts the probed value.
+
+ So the premise is verified rather than declared, the way
+ `probe_sql_is_evaluable` verifies the finished statement. A value that does
+ not survive the round trip is not mirrored, which costs the query its
+ pruning and nothing else.
+
+ The short-circuit is a proof, not a guess, and it matters for cost: a
+ 200-member ``IN`` list would otherwise parse 200 times on the chart path.
+ If the renderer emitted the value between two quotes and changed nothing in
+ it, and the value carries neither a quote nor a backslash, then no lexer in
+ play can read it as anything but itself. Both exclusions are load-bearing:
+ on Hive ``a\\b`` renders verbatim and reads as ``a`` followed by a
+ backspace.
+
+ :param value: a filter value about to be rendered into the probe
+ :param dialect: the dialect that will render it, as `_dialect_for` reports
+ :param engine: ``database.backend``, whose lexer reads the result
+ :return: whether the two agree about what the literal says
+ """
+ if isinstance(value, RawProbeValue):
+ # Already SQL, with no single value for a parse to be compared against:
+ # its elements are checked before they are rendered, by
+ # `ExploreMixin._array_mirror_probe_value`. A backslash surviving into
+ # the finished text is refused here all the same, as the backstop for a
+ # renderer this module does not own.
+ return "\\" not in value.sql
+ if not isinstance(value, str):
+ # Numbers and instants are not written between delimiters, so there is
+ # no escaping for the two sides to disagree about.
+ return True
+
+ rendered = _compile_literal(sa.literal(value), dialect)
+ if rendered == f"'{value}'" and "'" not in value and "\\" not in value:
+ return True
+
+ try:
+ return (
+ SQLStatement(f"SELECT {rendered}", engine).get_select_literal_value()
+ == value
+ )
+ except SupersetParseError:
+ # A rendered literal the engine's own dialect will not parse is the
+ # strongest form of disagreement there is.
+ return False
+
+
+def value_round_trips(database: Database, value: Any) -> bool:
+ """
+ `literal_round_trips` for a caller holding a database, not a dialect.
+
+ Which renderer and which lexer apply is this module's business, so the two
+ callers outside it -- the chart path's own gate in
+ `ExploreMixin.mirror_probe_request` and the mapping summary Explore reads
+ -- ask in these terms and stay out of it.
+
+ :param database: the database whose driver renders and whose engine reads
+ :param value: a filter value about to be rendered into the probe
+ :return: whether the two agree about what the literal says
+ """
+ return literal_round_trips(value, _dialect_for(database), database.backend)
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text. That is not itself a boundary:
+ the processor's escaping is not always the escaping the engine honours, and
+ a value can close its own quote through the gap. The boundary is
+ `literal_round_trips` on the way in -- which callers must have run, like
+ `stored_expression_error` below -- and `probe_sql_is_evaluable` on the way
+ out.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ bindable = _placeholder_is_bindable(transform)
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ elif bindable:
+ # Every other colon escaped first: `text()` would read one inside a
+ # string literal as a second bind parameter and render it `NULL`.
+ # See `escape_foreign_colons`.
+ clause = sa.text(escape_foreign_colons(transform)).bindparams(
+ sa.bindparam("value", value=value)
+ )
+ rendered = _compile_literal(clause, dialect)
+ else:
+ # `text()` cannot see the placeholder (see
+ # `_placeholder_is_bindable`), so the value is rendered by the
+ # dialect's own literal processor first and substituted as SQL
+ # text. The same two steps in the other order: binding exists to
+ # get the value through that processor, and `_compile_literal`
+ # inlines the result either way, so this is the same string by a
+ # different route -- not a loosening of the "never interpolate a
+ # raw value" rule. `parse_skeleton` substitutes literally, so the
+ # rendered literal arrives here exactly as it was rendered, which
+ # is what makes `literal_round_trips`' verdict on it good for this
+ # branch as much as for the bound one.
+ rendered = parse_skeleton(
+ transform, _compile_literal(sa.literal(value), dialect)
+ )
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Five things have to hold, and all five are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+ * No comment, anywhere. A value that closes its own quote has to hide the
+ text `build_probe_sql` appended after it, and a comment is the only way
+ to do that and still balance the quotes -- so this is what makes the
+ alias check above sufficient rather than merely necessary. Read off the
+ parse rather than the text, so a comment *inside* a literal is data and
+ costs no pruning, and so the question is asked in the engine's own
+ dialect. A transform has no legitimate reason to carry one either; see
+ `EXECUTABLE_COMMENT_RE`.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ # Before the parse, because this gate's whole contract is that what the
+ # parse describes is what the engine will run, and an executable comment is
+ # precisely the text where that stops being true. The transform is already
+ # refused for carrying one; this covers the compiled statement, so no later
+ # change to how values are rendered can reintroduce it behind the gates
+ # below.
+ if contains_executable_comment(sql) or contains_unicode_escaped_identifier(sql):
+ return False
+
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if not isinstance(statement, SQLStatement):
+ # A dialect whose statements this gate cannot take apart -- KQL -- gets
+ # no probe rather than an unchecked one. It never had one: the clause
+ # inspection below is implemented for SQL statements only, and the
+ # alternative to declining here is an `AttributeError` that `_probe`
+ # swallows into the same outcome, less legibly.
+ return False
+ if statement.has_comment():
+ return False
+ if statement.has_subquery():
+ return False
+ if statement.get_clause_names() - {"from"}:
+ return False
+ if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+ """
+ The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+ Parsed rather than string-compared so that the comparison in
+ `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+ not parse answers ``None``, which no statement carrying a FROM can match --
+ the probe then declines, which is the right way for an unreadable engine
+ constant to fail.
+ """
+ if not from_suffix.strip():
+ return None
+ try:
+ return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+ except SupersetParseError:
+ return None
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+ text_answers: list[tuple[int, Any]] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ :param text_answers: optional sink. When given, every date or timestamp in
+ ``values`` is also asked as the text a simple filter would bind, in the
+ same round trip, and ``(index, answer)`` is appended for each -- see
+ `_declined_for_reading_by_type` for why. A transform that refuses text
+ is asked again with ``values`` alone, so a refusal never costs pruning.
+ """
+ if not values:
+ return None
+
+ if text_answers is not None:
+ indexes = [
+ index
+ for index, value in enumerate(values)
+ if isinstance(value, date) and not is_unmirrorable(value)
+ ]
+ if indexes:
+ combined = evaluate_transform(
+ database,
+ catalog,
+ schema,
+ transform,
+ values + [_as_filter_text(values[index]) for index in indexes],
+ )
+ if combined is not None:
+ text_answers.extend(zip(indexes, combined[len(values) :], strict=False))
+ return combined[: len(values)]
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ # The value side of the premise `probe_sql_is_evaluable` checks on the
+ # finished statement: a value the driver and the engine would spell
+ # differently is not probed at all -- see `literal_round_trips`.
+ #
+ # `ExploreMixin.mirror_probe_request` declines one earlier, with a reason
+ # the preview can explain, and that is the gate an owner sees. This is the
+ # one that cannot be walked around. `_collect_partition_mirror_range`
+ # appends its bounds into the sink without passing through that method at
+ # all, and both paths can hand back a value the gate never saw: on a column
+ # carrying a `python_date_format`, what is probed is
+ # `strftime(that format)` -- text no mapping gate has ever read.
+ #
+ # Above `_run_probe` on purpose. This is a property of one input, not of
+ # the transform, and a verdict recorded here would withdraw the mirror for
+ # every later value of a transform the engine evaluates perfectly well.
+ dialect = _dialect_for(database)
+ if not all(
+ literal_round_trips(value, dialect, database.backend) for value in distinct
+ ):
+ logger.warning(
+ "A filter value is not written the same way by the driver and the "
+ "database, so the partition transform is not probed at it; this "
+ "query will not prune"
+ )
+ return None
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+
+ The verdict is about the *transform*: whether the engine evaluated it at
+ all. A ``NULL`` among the results is not that -- it is this input's answer,
+ and `NULLIF(:value, 0)` returning ``NULL`` for ``n = 0`` says nothing about
+ the same transform on ``n = 2``. Counting it withdrew the promise for the
+ whole transform, and nothing restored it: a *failed* probe is deliberately
+ not cached, so the next chart re-probes and re-records, but a ``NULL`` is a
+ successful probe and *is* cached -- so the false verdict outlived every
+ later hit, and the editor reported a working mapping as not mirroring
+ while the query went on pruning. The per-input skip still happens where it
+ belongs, in the caller's own ``NULL`` guard.
+
+ A probe where *every* input answers ``NULL`` is different only when it is
+ all the evidence there is. ``trunc(..., 'HH')`` on Hive returns ``NULL`` for
+ any input, and recording that as a working transform left Explore's glyph
+ promising a partition predicate no query carried. So an all-``NULL`` probe
+ records ``False`` -- but never over a stored ``True``, which some other
+ input earned and the ``NULLIF`` case above must keep. A later probe that
+ answers anything restores ``True`` the ordinary way: a fresh input misses
+ the probe cache, so it re-records.
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ if values is None:
+ mirrors = False
+ elif any(value is not None for value in values):
+ mirrors = True
+ elif known_mirror_verdict(database, catalog, schema, transform) is not True:
+ mirrors = False
+ else:
+ return values
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=mirrors,
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ from_suffix = database.db_engine_spec.select_without_from_suffix
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ from_suffix,
+ )
+ if not probe_sql_is_evaluable(
+ sql, database.backend, len(distinct), from_suffix
+ ):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _execution_identity(database: Database) -> str | None:
+ """
+ Who the warehouse will run the probe as, when that can vary by caller.
+
+ `_probe_cache_key` keys on the `Database` record, which is the *connection*
+ -- not the identity it is opened under. Two hooks make that identity a
+ function of the Superset user instead:
+
+ * ``impersonate_user`` on the database, which hands the effective username
+ to `db_engine_spec.impersonate_user`;
+ * ``DB_CONNECTION_MUTATOR``, which receives the effective username and may
+ return an entirely different account's URL.
+
+ Under either one, a cached probe result computed under user A's grants was
+ served to user B, and the preview echoed it back in ``emitted_predicate``.
+ A transform wrapping a read-capable function the denylist does not name --
+ Oracle's ``DBMS_XMLGEN.GETXML`` is the worked example -- then leaks across
+ users who were never allowed the same rows.
+
+ Returns ``None`` when neither hook is configured, which is the common case
+ and deliberately leaves the key as it was: the cache exists to keep a
+ synchronous warehouse round trip off the chart-query path, and keying every
+ deployment on the username would cost every deployment the hit rate to fix
+ the two that need it.
+
+ The *Superset* username rather than the resolved warehouse account, because
+ it is the input both hooks branch on, and reading it needs no URL parse and
+ puts no credential in the key.
+ """
+ if not (database.impersonate_user or app.config["DB_CONNECTION_MUTATOR"]):
+ return None
+ return get_username()
+
+
+#: Bumped whenever what the probe cache or the verdict cache *means* changes,
+#: so entries written under the old meaning are never read under the new one.
+#: v2: an all-``NULL`` probe stopped recording a working transform. A ``True``
+#: stored before that is indistinguishable from one another input earned, so
+#: it would have kept Explore's glyph lit for up to a cache timeout -- and the
+#: cached probe results behind it would have kept any query from re-probing
+#: and writing a fresh one.
+PROBE_CACHE_VERSION = "v2"
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{PROBE_CACHE_VERSION}:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _mirror_verdict_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str:
+ """
+ `_probe_cache_key` without the values.
+
+ Whether a transform can be evaluated at all is a property of the transform
+ and the connection, not of the filter that happened to be probing it, so
+ one chart's answer settles the question for the next one.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ # Whether a transform *can* be evaluated is a property of the
+ # transform and the connection -- but under impersonation the
+ # connection is per-user, and a function one account may call can
+ # be refused to another. See `_execution_identity`.
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_verdict:{PROBE_CACHE_VERSION}:{digest}"
+
+
+def record_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ *,
+ mirrors: bool,
+) -> None:
+ """
+ Remember whether this transform produced a mirror, for the UI to read.
+
+ Advisory only. Nothing in the query path consults it: a probe that failed
+ once is retried on the next chart exactly as it is today, because declining
+ to prune for a whole cache timeout over one transient engine blip is the
+ trade `evaluate_transform` deliberately refuses -- see the comment where it
+ declines to cache a failure.
+
+ What this is for is the *claim*. `is_transform_active` parses the transform
+ and no more, so a transform the database rejects -- a misspelled function
+ is the common case -- is "active", and the editor's banner and Explore's
+ pruning glyph promise a speed-up that never happens. A promise is exactly
+ the thing that may be withheld on one bad answer and restored on a good
+ one, which is why this is a separate entry from the probe's own results
+ rather than a relaxation of that rule.
+
+ Written by `_run_probe`, so the preview endpoint -- which shares the
+ evaluator -- settles the question before the owner has even saved.
+ """
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(
+ _mirror_verdict_cache_key(database, catalog, schema, transform),
+ mirrors,
+ timeout=timeout,
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform verdict", exc_info=True)
+
+
+def known_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> bool | None:
+ """
+ The last verdict `record_mirror_verdict` stored, or `None` if there is none.
+
+ `None` is the honest answer on a cold cache and is deliberately not `False`:
+ reporting a working mapping as broken until something probes it would
+ trade one wrong claim for another. The alternative -- probing from the
+ read side -- would put a warehouse round trip on every Explore and
+ dashboard load, and a failing transform is not cached at all, so it would
+ be a round trip every single time.
+ """
+ try:
+ verdict = cache_manager.cache.get(
+ _mirror_verdict_cache_key(database, catalog, schema, transform)
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return verdict if isinstance(verdict, bool) else None
+
+
+def _compile_literal(element: Any, dialect: Dialect | None) -> str:
+ """
+ Compile with inline literals, undoing the paramstyle's percent doubling.
+
+ Both ``TextClause`` and literal compilation run the dialect's
+ ``post_process_text``, which doubles every ``%`` whenever the identifier
+ preparer asks it to -- true for MySQL and Postgres and for every spec
+ inheriting their paramstyle. That doubling exists so a later DBAPI
+ parameter-interpolation pass can undo it, and the probe has no such pass:
+ it executes with no bound parameters at all. So a transform of
+ ``date_format(:value, '%Y%m%d')`` reaches the warehouse asking for the
+ literal string ``%%Y%%m%%d``, the probe returns that instead of a date, and
+ the mirrored predicate drops every row the filter keeps.
+
+ The same normalization ``Database.compile_sqla_query`` applies for the same
+ reason. ``_double_percents`` is private and not guaranteed on a third-party
+ dialect, hence the ``getattr`` default.
+ """
+ compiled = str(
+ element.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
+ )
+ if dialect is not None and getattr(
+ dialect.identifier_preparer, "_double_percents", False
+ ):
+ compiled = compiled.replace("%%", "%")
+ return compiled
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be *asked* to stand in for itself, and the transform
+ cannot carry Jinja or call a non-deterministic function. Tier 2
+ (``blocking=False``) is everything that merely leaves the mapping inactive
+ -- including a self-mapping nobody asked for, where the partition column
+ merely happens to be the default datetime column.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column == partition_column:
+ # Asked for explicitly, so report it as the mistake it is.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+ elif not partition_mapped_column and main_dttm_col == partition_column:
+ # Resolved onto itself only because the default datetime column happens
+ # to be the partition column -- a state metadata sync could produce
+ # without anyone asking for it. The mapping is inert either way, since
+ # `resolve_partition_mapping` bails out on it, so this reports and lets
+ # the write through: blocking here means a dataset already in the state
+ # can never be saved again, not even to change its description, and
+ # there is no field whose edit would clear the error first.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "%(name)s is both the partition column and the default "
+ "datetime column, so the mapping points at itself and "
+ "stays inactive. Set a mapped column override, or change "
+ "the default datetime column.",
+ name=partition_column,
+ ),
+ blocking=False,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def drop_unmapped_value_transforms(
+ columns: list[dict[str, Any]] | None,
+ *,
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ names_by_id: dict[int, str] | None = None,
+ stored_by_name: dict[str, tuple[str | None, bool]] | None = None,
+) -> list[str]:
+ """
+ Null the value transform on every *incoming* column the mapping cannot mirror.
+
+ The write-side twin of `DatasetDAO.clear_unmapped_partition_transforms`,
+ which answers for the model. A mapping has exactly one mirrored column, so
+ at most one column may carry a transform. One parked on any other column is
+ invisible -- no row but the mapped one renders a transform -- and yet it is
+ stored, and it goes live the moment the mapped column resolves back to it.
+ Clearing an override is enough to do that: a null
+ ``partition_mapped_column`` means "follow ``main_dttm_col``".
+
+ Ungated on the feature flag, unlike its model-level twin, and the difference
+ is what each one discards. That one drops stored configuration, so with the
+ flag off it would be pure loss. This one drops only a value the request in
+ hand is asking to write where the invariant says none may live -- and the
+ flag-off window is precisely when such a value gets parked for later, since
+ the editor hides these fields and the model-level pass declines to run.
+
+ Three writers reach the columns with no effective model-level pass between
+ them, which is why this exists at all: the deprecated
+ ``POST /datasource/save/``, which writes straight through
+ `update_from_object` and so never had one; and a
+ ``PUT /api/v1/dataset/<pk>`` or a dataset import made while the flag is
+ off, where the pass runs on both sides of the write and declines on both.
+
+ Mutates the payload in place, because every caller hands its own request
+ dict straight on to the code that writes it. Returns the names it cleared,
+ so the caller can say so in a log: this is a silent correction to a payload
+ whose author may have meant it.
+
+ A column whose payload mentions neither field is left alone. "Incoming" is
+ the whole scope -- a transform already in storage on a column this request
+ says nothing about is the model-level pass's business, under its own flag.
+
+ The mapped column resolves the way every other reader resolves it,
+ ``partition_mapped_column or main_dttm_col``, and resolves to nothing
+ without a partition column -- in which case no column may hold a transform
+ either.
+
+ :param names_by_id: how to read the name off a payload entry that gives
+ only an ``id``. `DatasetDAO._upsert_columns` identifies an existing
+ column by its primary key and lets ``column_name`` be omitted -- the
+ column keeps the name it has -- so without this an ordinary PUT looked
+ like a payload of nameless columns, none of which matched the mapped
+ one, and every transform in it was dropped. Callers whose writer keys
+ on the name instead (`update_from_object`, the importer) pass nothing.
+ An entry this cannot name is left alone rather than guessed at.
+ :param stored_by_name: ``(transform, is_monotonic)`` as currently stored,
+ per column name, so an *echo* can be told from an introduction. A
+ GET-then-PUT client sends back every column exactly as it received it,
+ so changing the default datetime column away from the mapped one made
+ the payload's unchanged copy of its transform look like a value being
+ parked -- and nulling it destroyed configuration the owner never
+ touched, unrecoverably, with the flag off and the editor's own fields
+ hidden. An unchanged value is the model-level pass's business under its
+ own flag, which is the same line this function's docstring already
+ draws for a column the payload omits. Callers that cannot see storage
+ pass nothing and keep the stricter behaviour.
+ """
+ mapped_column = (
+ (partition_mapped_column or main_dttm_col) if partition_column else None
+ )
+ cleared: list[str] = []
+ for column in columns or []:
+ name = column.get("column_name")
+ if name is None and names_by_id is not None:
+ column_id = column.get("id")
+ if column_id is not None:
+ name = names_by_id.get(column_id)
+ if name is None or name == mapped_column:
+ continue
+ transform = column.get("partition_value_transform")
+ is_monotonic = column.get("partition_transform_is_monotonic")
+ if not transform and not is_monotonic:
+ continue
+ if stored_by_name is not None and name in stored_by_name:
+ stored_transform, stored_monotonic = stored_by_name[name]
+ # A key the entry does not carry is unchanged, not `False`:
+ # `_upsert_columns` writes only the keys present, so echoing the
+ # transform without the declaration is a valid partial update. Read
+ # as a change, it failed the exemption and wrote both fields back
+ # as null -- the loss the exemption exists to prevent.
+ monotonic_echoes = "partition_transform_is_monotonic" not in column or bool(
+ is_monotonic
+ ) == bool(stored_monotonic)
+ transform_echoes = (
+ "partition_value_transform" not in column
+ or transform == stored_transform
+ )
+ if transform_echoes and monotonic_echoes:
+ # An echo, not an introduction. See `stored_by_name`.
+ continue
+ column["partition_value_transform"] = None
+ column["partition_transform_is_monotonic"] = False
+ cleared.append(name)
+ return cleared
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if contains_executable_comment(transform):
+ # Blocking, and checked on raw text next to the Jinja gate because no
+ # parse reports it: sqlglot reads `/*!50000 ... */` as comment data
+ # while MySQL and MariaDB execute it, so every shape gate downstream
+ # inspects a statement the engine will not run. See
+ # `EXECUTABLE_COMMENT_RE`.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform cannot contain a MySQL executable "
+ "comment (/*! ... */ or /*M! ... */). Those are comments "
+ "to every validator and statement text to the database, "
+ "so what would run is not what was checked."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if contains_unicode_escaped_identifier(transform):
+ # Beside the comment gate, for the same reason and on raw text: the
+ # parse reports the escape sequence verbatim as the function's name,
+ # so the function denylist compares against a name PostgreSQL never
+ # uses -- it decodes `U&"\0071uery_to_xml"` and runs `query_to_xml`.
+ # See `UNICODE_ESCAPED_IDENTIFIER_RE`.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ 'A value transform cannot name anything through a U&"..." '
+ "escape sequence. The database decodes it and every "
+ "validator reads it literally, so what would run is not "
+ "what was checked."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_bare_expression(transform, engine):
+ # Blocking, and deliberately placed in `validate_transform` rather than
+ # only at the probe: one issue here closes the PUT, the importer, the
+ # query-time gate through `is_transform_active`, the Explore indicator's
+ # active verdict and the preview endpoint, all of which already consult
+ # this function.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform must be a single SQL expression. It "
+ "cannot carry a FROM, WHERE, GROUP BY or any other clause, "
+ "and it cannot contain a sub-query."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not contains_value_placeholder(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform must contain the :value placeholder, "
+ "which stands for the filter value being mirrored."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not placeholder_is_executable(transform, engine):
+ # Blocking, and for the same reason the shape gate above is: this is
+ # the function the PUT, the importer, `is_transform_active`, the
+ # Explore indicator and the preview all consult, so one issue here
+ # closes every door at once. A placeholder inside a string literal is
+ # a sub-query the engine will run once a filter value closes the quote;
+ # one inside a comment silently eats the probe's own alias.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The :value placeholder must appear where the engine will "
+ "evaluate it. It cannot sit inside a string literal or a "
+ "comment."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if functions := find_non_deterministic_functions(transform, engine):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform calls %(functions)s, whose result "
+ "depends on when and where it runs. The transform is "
+ "evaluated in a separate session and the result is cached, "
+ "so the emitted predicate would freeze a snapshot of that "
+ "moment.",
+ functions=", ".join(sorted(functions)),
+ ),
+ blocking=True,
+ )
+ ]
+
+ return []
+
+
+@lru_cache(maxsize=LRU_CACHE_MAX_SIZE)
+def is_transform_active(transform: str | None, engine: str) -> bool:
+ """
+ Whether Superset will mirror filters through this transform.
+
+ `validate_transform` with the messages discarded, so the Explore indicator
+ cannot advertise a mapping the save path recorded as inactive. Anything
+ cheaper here would be a second, weaker statement of the same rule, free to
+ drift from the one the save path applies.
+
+ Blocking issues count too. Jinja and non-deterministic transforms are
+ rejected on PUT, but `CreateDatasetCommand` and import do not validate the
+ mapping, so one can still reach the database -- and it would never mirror a
+ filter either.
+
+ Memoized because `partition_filter_mapping_summary` is serialized on every
+ Explore and dashboard load and this parses the transform. The key is
+ everything the answer depends on: `validate_transform` reads no session, no
+ locale and no config beyond `SQL_MAX_PARSE_LENGTH`, which bounds the parser
+ rather than changing a verdict within that bound.
+ """
+ return not validate_transform(transform, engine)
+
+
+def preview_partition_mapping( # pylint: disable=too-many-return-statements
+ datasource: SqlaTable,
+ *,
+ mapped_column: str,
+ value_transform: str | None,
+ sample_values: list[str],
+ operator: FilterOperator = FilterOperator.EQUALS,
+ is_monotonic: bool = False,
+ partition_column: str | None = None,
+) -> dict[str, Any]:
+ """
+ Evaluate a candidate mapping and describe the predicate it would emit.
+
+ Shares the evaluator -- and therefore the probe cache -- with the query
+ path, so preview and runtime cannot drift and a previewed transform warms
+ the chart path for free. The predicate itself comes from
+ `build_mirrored_predicates`, the same builder the query path uses, so
+ operator shapes cannot drift either: what the panel shows is what a chart
+ would emit.
+
+ Validation runs first and the engine second: a half-typed transform is by
+ definition unparseable, so most of what a text input produces costs zero
+ queries.
+
+ Every part of the mapping is taken from the request rather than the stored
+ dataset. The editor previews while the owner is still editing -- a mapping
+ that has to be saved before it can be checked is not a preview.
+ """
+ partition_column = partition_column or datasource.partition_column
+ if not partition_column:
+ return {
+ "valid": False,
+ "reason": "unconfigured",
+ "error": _("No partition column is set."),
+ }
+
+ columns_by_name = {str(column.column_name): column for column in datasource.columns}
+ if mapped_column not in columns_by_name:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _("%(name)s is not a column on this dataset.", name=mapped_column),
+ }
+
+ # The bail-out `resolve_partition_mapping` makes at query time, and that
+ # `partition_filter_mapping_summary` repeats for the Explore indicator.
+ # Without it here, preview reports a valid emitted predicate for a mapping
+ # no chart will ever mirror -- the one answer a preview panel must not give.
+ if has_active_advanced_data_type(columns_by_name[mapped_column]):
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _(
+ "%(name)s has an advanced data type, so its filters are "
+ "translated into their own predicate shape and cannot be "
+ "mirrored onto the partition column.",
+ name=mapped_column,
+ ),
+ }
+
+ engine = datasource.database.backend
+ for issue in validate_partition_mapping(
+ column_names=set(columns_by_name),
+ partition_column=str(partition_column),
+ partition_mapped_column=mapped_column,
+ main_dttm_col=datasource.main_dttm_col,
+ transform=value_transform,
+ engine=engine,
+ ):
+ return {
+ "valid": False,
+ # The parse failure is the one an owner sees constantly, and it is
+ # the only one the mockup gives its own headline to.
+ "reason": (
+ "parse"
+ if issue.field == "partition_value_transform"
+ and not is_parseable(value_transform, engine)
+ else "validation"
+ ),
+ "error": str(issue.message),
+ }
+
+ # The policy every other stored expression goes through. The save path
+ # applies it in `UpdateDatasetCommand._validate_partition_mapping`, but
+ # preview evaluates a candidate transform that has not been saved, so
+ # without this the gate had a door around it. See
+ # `stored_expression_error` for what is being kept out and why.
+ if reason := stored_expression_error(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ cast(str, value_transform),
+ ):
+ return {"valid": False, "reason": "validation", "error": reason}
+
+ mapping = PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=mapped_column,
+ value_transform=cast(str, value_transform),
+ is_monotonic=is_monotonic,
+ equality_is_safe=equality_mirrors_safely(
+ columns_by_name[mapped_column], datasource.database.db_engine_spec
+ ),
+ )
+ sample_input = _render_sample_input(
+ datasource, mapped_column, operator, sample_values
+ )
+
+ if operator not in PREVIEWABLE_OPERATORS:
+ # Checked before `mirrors`, which lets `TEMPORAL_RANGE` through when the
+ # transform is declared monotonic -- and the single sample value would
+ # then reach `handle_comparison_filter`, which has no case for a range
+ # and raises. The request schema rejects it too; this keeps the function
+ # honest for any other caller.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is mirrored as a pair of bounds, which "
+ "a preview of a single value cannot describe.",
+ operator=operator.value,
+ ),
+ }
+
+ if operator in MIRRORABLE_ALWAYS and not mapping.equality_is_safe:
+ # Withdrawn by `equality_mirrors_safely`, which no declaration about
+ # ordering can change -- so naming monotonicity here would send the
+ # owner to a checkbox that leaves the answer as it is.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter on this text column is not mirrored: "
+ "the database may treat strings that differ in case or "
+ "trailing spaces as equal, and the mirrored predicate could "
+ "then drop rows the filter keeps.",
+ operator=operator.value,
+ ),
+ }
+
+ if not mapping.mirrors(operator):
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is only mirrored when the transform "
+ "preserves ordering, which this one is not declared to do.",
+ operator=operator.value,
+ ),
+ }
+
+ return _preview_probe(
+ datasource,
+ mapping,
+ columns_by_name[mapped_column],
+ operator,
+ sample_values,
+ sample_input,
+ )
+
+
+def _preview_probe(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ mapped_col: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+ sample_input: str,
+) -> dict[str, Any]:
+ """
+ The half of a preview that needs the warehouse.
+
+ Split out from `preview_partition_mapping` so that the gates which answer
+ from the stored mapping alone stay readable as the single run of guard
+ clauses they are. Everything here has either run a query or decided not to.
+
+ A chart hands the transform a temporal value in two shapes. A simple filter
+ binds the text the author typed; a time range binds a `datetime`, which the
+ dialect writes as a typed literal (``TO_DATE(...)`` on Oracle). A
+ transform can read the two differently -- ``TO_DATE(:value, fmt)`` parses
+ the text, but converts the typed value back to text through the session's
+ ``NLS_DATE_FORMAT`` first and lands in year 0012 -- and previewing only the
+ text said valid for a mapping whose every time range came back empty. So a
+ temporal sample is previewed as the time range sends it. Comparing it with
+ the text shape is `build_mirrored_predicates`' job rather than this
+ function's, so the chart path runs the same check -- see
+ `_declined_for_reading_by_type`.
+ """
+ probe_input = _probe_input(datasource, mapped_col, operator, sample_values)
+ range_input = _as_range_bound(mapped_col, operator, probe_input)
+ return _preview_probe_value(
+ datasource,
+ mapping,
+ mapped_col,
+ operator,
+ datasource.mirror_probe_request(
+ operator,
+ range_input if range_input is not None else probe_input,
+ mapped_col,
+ ),
+ sample_input,
+ )
+
+
+def _as_range_bound(
+ column: "TableColumn",
+ operator: FilterOperator,
+ probe_input: Any,
+) -> datetime | None:
+ """
+ The `datetime` a time range would hand the transform for this sample, or
+ `None` where the sample is not a temporal bound a time range could carry.
+ """
+ # Imported here: `superset.models.helpers` imports this module.
+ from superset.models.helpers import ( # pylint: disable=import-outside-toplevel
+ _instant_from_filter_value,
+ )
+
+ if not column.is_dttm or operator == FilterOperator.IN:
+ return None
+ if not isinstance(probe_input, str):
+ return None
+ instant = _instant_from_filter_value(probe_input)
+ if instant is None or instant.tzinfo is not None:
+ return None
+ return instant
+
+
+def _preview_probe_value(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ mapped_col: "TableColumn",
+ operator: FilterOperator,
+ value: Any,
+ sample_input: str,
+) -> dict[str, Any]:
+ """`_preview_probe` for one shape of the probe input."""
+ if is_unmirrorable(value):
+ # The same step the chart path applies, so the preview cannot promise a
+ # mirror the query declines -- and it reports the reason that step
+ # recorded rather than deriving one of its own, which is what let the
+ # offset case be explained as a precision loss it is not.
+ if value.reason == "offset":
+ # The transform is fine and the column may well compare the whole
+ # instant; what cannot be mirrored is the frame. Advising a
+ # different column here would send the owner after a column they
+ # already have.
+ return {
+ "valid": False,
+ "reason": "offset",
+ "sample_input": sample_input,
+ "error": _(
+ "A filter value carrying a UTC offset is not mirrored: a "
+ "transform is evaluated in the database's own time frame, "
+ "so the mirrored predicate could ask for a partition the "
+ "matching rows are not in. Write the bound without an "
+ "offset to mirror this filter.",
+ ),
+ }
+ if value.reason == "escaping":
+ # Nothing about the column, the operator or the transform is wrong
+ # here, so none of the advice the other branches carry applies: the
+ # driver and the database disagree about how to write this value
+ # down. Said in terms of the value, which is the only thing the
+ # owner can change.
+ return {
+ "valid": False,
+ "reason": "escaping",
+ "sample_input": sample_input,
+ "error": _(
+ "A filter value containing a quote or a backslash is not "
+ "mirrored on this database: the driver and the database do "
+ "not agree on how to write it into a query, so the "
+ "transform would be evaluated at a value the filter does "
+ "not compare. Filters whose values carry neither still "
+ "mirror.",
+ ),
+ }
+ # The transform is fine and the engine evaluates it, the filter just
+ # carries more of the value than the engine compares on this column --
+ # which is the column's type talking, not a broken expression.
+ return {
+ "valid": False,
+ "reason": "resolution",
+ "sample_input": sample_input,
+ "error": _(
+ "This engine compares less of a %(operator)s value on "
+ "%(column)s than the filter carries, so there is no mirror a "
+ "predicate on the partition column could stand in for. Map a "
+ "column the engine compares in full to mirror this operator.",
+ operator=operator.value,
+ column=mapped_col.column_name,
+ ),
+ }
+ errors: list[str] = []
+ type_errors: list[str] = []
+ escaping_errors: list[str] = []
+ shape_errors: list[str] = []
+ try:
+ predicates = build_mirrored_predicates(
+ datasource,
+ mapping,
+ [(operator, value)],
+ errors=errors,
+ type_errors=type_errors,
+ escaping_errors=escaping_errors,
+ shape_errors=shape_errors,
+ )
+ except Exception: # pylint: disable=broad-except
+ # The chart path fails open on the same call; the preview reports it
+ # as a mapping that will not mirror rather than as a server error.
+ logger.warning("Could not preview the partition mapping", exc_info=True)
+ return {
+ "valid": False,
+ "reason": "engine",
+ "sample_input": sample_input,
+ "error": _("The transform could not be evaluated against the database."),
+ }
+ if shape_errors:
+ return {
+ "valid": False,
+ "reason": "shape",
+ "sample_input": sample_input,
+ "error": shape_errors[0],
+ }
+ if type_errors:
+ # Its own reason, because "the database would not evaluate this" and
+ # "it evaluated and answered with the wrong kind of thing" are
+ # different problems with different fixes, and the owner is the only
+ # one who can tell which transform they meant to write.
+ return {
+ "valid": False,
+ "reason": "type",
+ "sample_input": sample_input,
+ "error": type_errors[0],
+ }
+ if escaping_errors:
+ # Its own reason, and distinct from the `escaping` one above: that is
+ # about the value the chart author typed, this is about what the
+ # transform made of it. Falling through to `engine` below told the owner
+ # the database would not evaluate the transform, when it evaluated it
+ # perfectly and answered with a key that cannot be asked for here.
+ return {
+ "valid": False,
+ "reason": "transform_escaping",
+ "sample_input": sample_input,
+ "error": escaping_errors[0],
+ }
+ if not predicates:
+ return {
+ "valid": False,
+ "reason": "engine",
+ "sample_input": sample_input,
+ "error": (
+ _(
+ "The transform could not be evaluated against the "
+ "database: %(reason)s",
+ reason=errors[0],
+ )
+ if errors
+ else _("The transform could not be evaluated against the database.")
+ ),
+ }
+
+ return {
+ "valid": True,
+ "sample_input": sample_input,
+ "emitted_predicate": _render_predicate(datasource, predicates[0]),
+ }
+
+
+def _probe_input(
+ datasource: SqlaTable,
+ column: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+) -> Any:
+ """
+ The sample values as the query path would bind them.
+
+ The request carries samples as strings, and the probe is keyed on exactly
+ what it is handed, so passing them through raw asks the engine a different
+ question from the one a chart asks. A sample of ``2025`` on a numeric
+ column has to arrive as the integer the chart compares: under a transform
+ of ``typeof(:value)`` the raw string previewed ``'text'`` where the chart
+ emitted ``'integer'``. And because `_probe_cache_key` keys on each value's
+ ``repr``, the two also missed each other's cache entirely -- so the "a
+ previewed transform warms the chart path for free" claim in
+ `preview_partition_mapping`'s docstring did not actually hold.
+
+ Coerced by `filter_values_handler`, the same function the query path uses,
+ rather than by a second implementation of the same rules. Everything the
+ query path then does to the coerced value -- rendering an expression as a
+ literal, widening a bound, declining a comparison the engine resolves too
+ coarsely -- is `ExploreMixin.mirror_probe_request`'s, and the caller hands
+ this result straight to it.
+
+ Ranges are not previewable (see `PREVIEWABLE_OPERATORS`), so the bound
+ conversion `_collect_partition_mirror_range` applies -- a ``datetime`` into
+ the column's stored representation -- has no counterpart here.
+
+ An array column is the exception to `filter_values_handler`: its predicate
+ is built from the raw value, parsed into elements and rendered as the
+ engine's own array literal, so the chart path probes that literal
+ (`ExploreMixin._array_mirror_probe_value`) and this does too. Passing the
+ handled text instead previewed ``length('[1, 2]')`` for a filter whose
+ query probes ``length(array(1, 2))``.
+
+ Answers with a value, or `None` where an engine spec claims array columns
+ without an array literal -- which `mirror_probe_request` then declines, as
+ the chart path declines it. It may also answer with an `Unmirrorable` the
+ array branch raised itself, which `mirror_probe_request` passes through;
+ otherwise the decline is that method's to make, and the caller hands this
+ straight to it.
+ """
+ is_list = operator == FilterOperator.IN
+ column_spec = datasource.db_engine_spec.get_column_spec(native_type=column.type)
+ if (
+ column_spec
+ and column_spec.generic_type == utils.GenericDataType.MULTI_VALUE
+ and operator in MIRRORABLE_ALWAYS
+ ):
+ # `=` and `IN` are the previewable operators the array branch builds a
+ # literal for; a bound on an array column binds the handled value on
+ # the chart path too, so it falls through to the same here.
+ return datasource._array_mirror_probe_value( # noqa: SLF001
+ sample_values if is_list else sample_values[0],
+ operator,
+ datasource.db_engine_spec.get_array_element_type(column.type),
+ datasource.db_engine_spec,
+ )
+ handled = datasource.filter_values_handler(
+ # `list[str]` is not a `list[FilterValue]` to mypy, invariantly, even
+ # though every `str` is a `FilterValue`.
+ values=cast(FilterValues, sample_values if is_list else sample_values[0]),
+ operator=operator,
+ target_generic_type=(
+ column_spec.generic_type if column_spec else utils.GenericDataType.STRING
+ ),
+ target_native_type=column.type,
+ is_list_target=is_list,
+ db_engine_spec=datasource.db_engine_spec,
+ db_extra=datasource.db_extra,
+ )
+ # No `ColumnElement` conversion here: an epoch-milliseconds sample comes back
+ # as engine SQL rather than a value, and `mirror_probe_request` renders it --
+ # the same step, on the same values, as for a chart filter.
+ return handled
+
+
+def _render_sample_input(
+ datasource: SqlaTable,
+ mapped_column: str,
+ operator: FilterOperator,
+ values: list[str],
+) -> str:
+ """
+ The filter being previewed, written the way an owner would read it.
+
+ Display-only -- it is never executed -- but it is still read as SQL, so the
+ column is quoted and the values are rendered by the dialect rather than
+ concatenated raw. A column named ``order date`` would otherwise come out as
+ two bare words.
+ """
+ quoted = datasource.quote_identifier(mapped_column)
+ if operator == FilterOperator.IN:
+ rendered = ", ".join(
+ _render_literal(datasource.database, value) for value in values
+ )
+ return f"{quoted} IN ({rendered})"
+ return (
+ f"{quoted} {operator.value} {_render_literal(datasource.database, values[0])}"
+ )
+
+
+def _render_predicate(datasource: SqlaTable, predicate: ColumnElement[Any]) -> str:
+ """
+ Compile a mirrored predicate to the text a reader would see in View query.
+
+ Every value in it is a probed constant by this point, so ``literal_binds``
+ renders the same literals the chart query carries.
+ """
+ return _compile_literal(predicate, _dialect_for(datasource.database)).replace(
+ "\n", " "
+ )
+
+
+def _render_literal(database: Database, value: Any) -> str:
+ """
+ Render a value the way it appears in the generated SQL.
+
+ Compiled by the dialect rather than formatted by hand. `str()` would render
+ a NULL as the Python repr `None` and leave a date unquoted, neither of which
+ is SQL, and hand-rolled quote-doubling would only ever have been right for
+ strings.
+ """
+ return _compile_literal(sa.literal(value), _dialect_for(database))
+
+
+def _as_filter_text(value: date) -> str:
+ """``value`` as the text a simple filter on a temporal column carries."""
+ if isinstance(value, datetime):
+ return value.isoformat(
+ sep=" ", timespec="seconds" if not value.microsecond else "auto"
+ )
+ return value.isoformat()
+
+
+def _declined_for_reading_by_type(
+ evaluated: list[Any],
+ text_answers: list[tuple[int, Any]],
+ shape_errors: list[str] | None,
+) -> bool:
+ """
+ Whether a temporal value's text form answered differently from the value.
+
+ A chart hands a temporal value to the transform in two shapes. A time
+ range binds a `datetime`, which the dialect writes as a typed literal
+ (``TO_DATE(...)`` on Oracle); a simple filter binds the text the author
+ typed. A transform can read the two differently: Oracle's
+ ``TO_DATE(:value, fmt)`` parses the text, but turns the typed value back
+ into text through ``NLS_DATE_FORMAT`` first, so every time range asked for
+ a partition in year 0012 and came back empty -- or, under an ISO
+ ``NLS_DATE_FORMAT``, short by whatever the format drops. Nothing about the
+ typed answer alone looks wrong, so `evaluate_transform` asks the same
+ instant as text in the same round trip (``text_answers``), and a mapping
+ whose two answers differ cannot be right for both and is not mirrored.
+
+ The text goes straight to the evaluator rather than through the mirror
+ request path, whose gates decline some text before it reaches the engine
+ -- which is how the preview at a time of day said valid for exactly this
+ transform. Reported to ``shape_errors`` and the log when it declines.
+ """
+ disagreement = next(
+ (
+ (evaluated[index], text_answer)
+ for index, text_answer in text_answers
+ if text_answer is not None and text_answer != evaluated[index]
+ ),
+ None,
+ )
+ if disagreement is None:
+ return False
+ reason = str(
+ _(
+ "The transform gives a different partition value for a "
+ "timestamp (%(typed)s) than for the same instant written as "
+ "text (%(text)s). A time range and a filter typed as text both "
+ "reach it, so it cannot be right for both; filters on this "
+ "mapping will not be mirrored. Write the transform so it reads "
+ ":value the same way in either form.",
+ typed=disagreement[0],
+ text=disagreement[1],
+ )
+ )
+ logger.warning("Partition transform reads :value by type: %s", reason)
+ if shape_errors is not None:
+ shape_errors.append(reason)
+ return True
+
+
+def build_mirrored_predicates(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ requests: list[tuple[FilterOperator, Any]],
+ *,
+ errors: list[str] | None = None,
+ type_errors: list[str] | None = None,
+ escaping_errors: list[str] | None = None,
+ shape_errors: list[str] | None = None,
+) -> list[ColumnElement[Any]]:
+ """
+ Turn collected ``(operator, value)`` mirror requests into predicates.
+
+ ``requests`` is expected to be deduplicated by the caller. Every value is
+ resolved in a single probe round trip -- one per chart query at most -- then
+ emitted as a literal constant, so "View query" shows the reader an ordinary
+ ``WHERE`` clause rather than an inline expression.
+
+ A strict bound is emitted non-strictly; see `mirror_operator`. That happens
+ here, at the one point where a ``FilterOperator`` becomes SQL, rather than
+ at the collection sites in `ExploreMixin`: the preview endpoint calls this
+ directly, so this is what keeps the predicate the editor shows an owner and
+ the predicate the chart carries from disagreeing.
+
+ :param errors: optional sink; see `evaluate_transform`.
+ :param type_errors: optional sink for a probe result the partition column
+ cannot hold -- see `probed_value_type_error`. Separate from ``errors``
+ because the two say different things to an owner: that one is "the
+ database would not evaluate this", and this one is "it evaluated, and
+ answered with the wrong kind of thing".
+ :param escaping_errors: optional sink for a probe result the driver and the
+ engine would spell differently -- see `_predicates_from_probe`. Its own
+ sink for the same reason: "it evaluated, and answered with something
+ this database cannot be asked about" is a third problem, and the only
+ one of the three whose fix is to stop the transform producing the
+ character.
+ """
+ if not requests:
+ return []
+
+ partition_column = next(
+ (
+ column
+ for column in datasource.columns
+ if column.column_name == mapping.partition_column
+ ),
+ None,
+ )
+ if partition_column is None:
+ return []
+
+ # Flatten every value that needs probing into one list, remembering how many
+ # each request consumed so the results can be handed back out.
+ flat: list[Any] = []
+ spans: list[tuple[FilterOperator, int, int]] = []
+ for operator, value in requests:
+ values = list(value) if operator == FilterOperator.IN else [value]
+ spans.append((operator, len(flat), len(values)))
+ flat.extend(values)
+
+ text_answers: list[tuple[int, Any]] = []
+ evaluated = evaluate_transform(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ mapping.value_transform,
+ flat,
+ errors=errors,
+ text_answers=text_answers,
+ )
+ if evaluated is None:
+ return []
+
+ if not _bounds_are_ordered(evaluated, spans):
+ return []
+
+ if _declined_for_reading_by_type(evaluated, text_answers, shape_errors):
Review Comment:
When this declines (Oracle `TO_DATE(:value, fmt)` puts the typed bound in year 0012), the stored verdict stays `evaluable=true`, so the time-range glyph keeps promising pruning that no time-range query gets.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "hughhhh (via GitHub)" <gi...@apache.org>.
hughhhh commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4362308007
##########
superset/db_engine_specs/base.py:
##########
@@ -580,6 +580,47 @@ def normalize_custom_sql_metric(cls, expression: str) -> str:
allows_joins = True
allows_subqueries = True
allows_alias_in_select = True
+ # Appended to a ``SELECT`` that has no ``FROM`` -- evaluating expressions
+ # and nothing else. Most engines accept a bare ``SELECT 1``; Oracle, DB2
+ # and Db2 for i require a one-row table to select it from.
+ select_without_from_suffix: str = ""
+ # Whether ``=`` on a text column compares byte-exactly by default: no case
+ # folding, no trailing-space padding, no accent insensitivity.
+ #
+ # Partition filter mapping needs this. It mirrors ``col = v`` onto
+ # ``partition_col = T(v)`` on the strength of ``col = v`` implying
+ # ``T(col) = T(v)``, which holds for value equality and not for SQL
+ # equality: under a case-insensitive collation a stored ``'us'`` satisfies
+ # a filter for ``'US'``, while the mirror ``hex('US')`` excludes the row,
+ # and the chart silently loses it. False by default, so a spec that has
+ # not said so does not mirror string equality.
+ #
+ # This speaks for the engine's *default* comparison only. A column
+ # declaring its own non-binary collation (``country COLLATE NOCASE``) is
+ # invisible to Superset -- nothing in SQLAlchemy's reflection or the engine
+ # specs exposes it -- so on such a column the assumption remains the
+ # owner's, like ``p = T(mapped_col)`` itself.
+ binary_string_comparison: bool = False
+
+ # Every text form this engine reads as a date or timestamp when one is
+ # compared against a temporal column. `strftime`/`strptime` patterns.
+ #
+ # Partition filter mapping needs this. A bucketing key such as
+ # ``to_char(:value, 'YYYYMMDD')`` is legitimately text, so the mirror
+ # ``part_date = '20260115'`` has to be allowed against a ``DATE`` partition
+ # column -- but only where the engine reads it, because comparing a
+ # temporal column against text is an implicit coercion an engine need not
+ # have. Trino has no VARCHAR-to-DATE comparison and BigQuery coerces only a
+ # canonical ``YYYY-MM-DD`` *literal*, so on those even plain ISO text fails
+ # the whole chart rather than merely losing the pruning -- which is why the
+ # ISO forms are declared here too rather than assumed universal.
+ #
+ # Empty by default, so an engine Superset has not confirmed declines the
+ # mirror and keeps the query working. Declared on concrete specs, not on a
+ # shared base: `PostgresBaseEngineSpec` is inherited by Snowflake, whose
+ # AUTO date input reads an all-digit string as epoch seconds instead.
+ temporal_literal_formats: tuple[str, ...] = ()
Review Comment:
Good catch, thanks. Fixed in [5615540384](https://github.com/apache/superset/pull/43870/commits/5615540384). A probed `date`/`datetime` is now written with the engine's own literal via `convert_dttm` (the same path as the chart's own time bounds), so on Trino this emits `dt >= DATE '2026-01-01'` for ranges, `=` and `IN`. Where the engine has no faithful literal for the column, the mirror is declined and only pruning is lost. Added dialect-level tests and a preview test.
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/DatasourceEditor.tsx:
##########
@@ -1365,19 +1695,76 @@ function DatasourceEditor({
try {
const newCols = await fetchSyncedColumns(datasource, signal);
+ // Everything past the `await` reads the refs rather than the closure;
+ // see their declaration.
+ const liveColumns = currentColumnsRef.current;
+ const liveDatasource = datasourceRef.current;
+
const columnChanges = updateColumns(
- datasource.columns,
+ liveColumns,
Review Comment:
Thanks, reproduced. Fixed in [e8935b2abe](https://github.com/apache/superset/pull/43870/commits/e8935b2abe). The merge still runs against the live rows, but a column that comes back as "added" and exists in `datasource.columns` is restored from its saved row (taking the source's type), so the save updates it instead of re-creating the name. Added a test for delete → sync → save.
##########
superset-frontend/src/explore/components/controls/DateFilterControl/DateFilterLabel.tsx:
##########
@@ -420,7 +422,12 @@ export default function DateFilterLabel(props: DateFilterControlProps) {
{...props}
onDescriptionHoverChange={setIsDescriptionHovered}
/>
- {popoverContent}
+ {/* The glyph sits outside the popover trigger so clicking it opens the
+ tooltip rather than the time-range editor. */}
+ <Flex align="center" gap={theme.sizeUnit}>
Review Comment:
Agreed. Fixed in [f94ce2fe3c](https://github.com/apache/superset/pull/43870/commits/f94ce2fe3c). The `Flex` is now rendered only when `partitionMapping` is set, so the flag-off markup matches master. With a mapping, the trigger also gets `flex: 1; min-width: 0`, so the box fills the row instead of shrinking. Added tests for both cases.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4320971055
##########
UPDATING.md:
##########
@@ -217,6 +217,58 @@ reattached to a reachable container by layout repair.
instead; the response sets `managed_externally: true`. Read-only tools and
certification inspection are unaffected.
+- Refreshing a dataset's columns from its source -- the "Sync columns from
+ source" button, and a `PUT /api/v1/dataset/<id>?override_columns=true` --
+ no longer resets **Is dimension** and **Is filterable** on columns that
+ already exist. Those two flags were set unconditionally on every column the
+ source reported, so a save that synced columns reverted whatever the dataset
+ owner had chosen for them. A newly discovered column still arrives with both
+ enabled. A deployment that relied on a resync to restore those defaults has
+ to set them explicitly.
+
+- `DISALLOWED_SQL_FUNCTIONS` now names the whole PostgreSQL XML family, plus the
+ two full-text search functions that share its blind spot. Seven shapes were
+ missing -- `schema_to_xml`, `schema_to_xmlschema`,
+ `schema_to_xml_and_xmlschema`, `database_to_xml_and_xmlschema`,
+ `table_to_xmlschema`, `ts_rewrite` and `ts_stat` -- which, being scalar calls
+ with no FROM clause and no sub-query, cleared every gate that reasons about
+ table references. `ts_rewrite` and `ts_stat` run their text argument as a
+ query, so the statement they execute is a string with no clause of its own for
+ such a gate to see. The same reasoning adds a new `oracle` entry naming
+ `getxml`, `getxmltype`, `newcontext` and `newcontextfromhierarchy`, the
+ `DBMS_XMLGEN` / `DBMS_XMLQUERY` calls that run a query handed to them as
+ text, and the URI readers that name a table by path string -- `dburitype`,
+ `xdburitype`, `httpuritype` and `geturi`, the last reached through
+ `URIFACTORY.GETURI(...)`. They are listed by bare name because that is what
+ the parser sees for a package-qualified call.
+
+ The denylist is shared with SQL Lab and Charts, so a
+ deployment relying on any of these functions there will now see it refused --
+ including a deployment that never enables `PARTITION_FILTER_MAPPING`, since
+ the denylist is not gated on the feature flag. Override
+ `DISALLOWED_SQL_FUNCTIONS` in `superset_config.py` if that is intended.
+
+- A partition value transform is now refused if it changes data --
+ `nextval(:value)`, a stored-procedure call, a PostgreSQL large-object writer.
+ The transform is evaluated against the engine to check that it mirrors, and
+ that evaluation is cached and repeated, so it has to be a read. The check is
+ the same `is_mutating` gate SQL Lab and chart queries already apply, and it
+ covers transforms already in storage: one stored by an earlier version simply
+ stops mirroring rather than failing a query.
+
+- Only the mapped column may carry a partition value transform, and that is now
+ enforced on every write rather than only inside `UpdateDatasetCommand`. A
+ transform arriving on any other column is dropped -- by the deprecated
+ `POST /datasource/save/`, and by `PUT /api/v1/dataset/<pk>` and dataset import
+ even when `PARTITION_FILTER_MAPPING` is off. An API client that was storing one there
+ will find the field `null` on the next read. The value was never readable:
Review Comment:
With `PARTITION_FILTER_MAPPING` off, an API client doing GET-then-PUT can re-point `partition_mapped_column` while echoing the previous column's stored transform unchanged. `DatasetDAO.update()` deliberately keeps that echo (`stored_by_name`), so the next read returns the transform rather than the `null` promised here; imports have the same exemption. Should this say that only newly introduced or changed unmapped transforms are dropped while the flag is off (and the matching sentence in `partition-filter-mapping.mdx`)?
##########
superset/commands/dataset/importers/v0.py:
##########
@@ -291,7 +319,154 @@ def run(self) -> None:
.one()
)
dataset["database_id"] = database.id
- SqlaTable.import_from_dict(dataset, sync=self.sync)
+ self._prepare_partition_mapping(dataset, database)
+ table = SqlaTable.import_from_dict(dataset, sync=self.sync)
+ if table is not None:
+ imported.append(table)
+
+ self._repair_partition_mappings(imported)
+
+ @classmethod
+ def _default_omitted_monotonic_declarations(cls, config: Any) -> None:
+ """
+ Materialize `partition_transform_is_monotonic` wherever a transform is
+ set, anywhere in a v0 config.
+
+ The v1 importer does this on its own raw config, and for the same
+ reason: an overwrite keeps whatever the bundle omits, including a
+ ``True`` left behind by the transform this bundle is replacing. A
+ non-monotonic transform declared monotonic enables range mirrors that
+ exclude rows the filter keeps -- ``abs(:value)`` inheriting a stored
+ ``True`` turns ``n >= -1`` into ``p >= 1`` and misses ``n = 0``.
+
+ Walked rather than addressed directly because a v0 bundle comes in two
+ shapes: a CLI export nests datasets under ``databases[].tables[]``,
+ while a UI export is a bare list of datasets. Only columns that supply
+ a transform are touched, so a re-import that says nothing about a
+ column stays idempotent.
+ """
+ if isinstance(config, list):
+ for entry in config:
+ cls._default_omitted_monotonic_declarations(entry)
+ return
+ if not isinstance(config, dict):
+ return
+ _default_omitted_monotonic_declarations(config.get("columns") or [])
+ for key in (DATABASES_KEY, "tables"):
+ for child in config.get(key) or []:
+ cls._default_omitted_monotonic_declarations(child)
+
+ @staticmethod
+ def _prepare_partition_mapping(
+ dataset: dict[str, Any], database: Optional[Database]
+ ) -> None:
+ """
+ Run the two repairs that have to happen *before* the bundle is applied.
+
+ `_repair_partition_mappings` below runs after `import_from_dict`, which
+ is too late for either of these.
+
+ Sanitizing the bundle. The v1 importer drops a transform the save path
+ would refuse (`drop_unusable_partition_transforms`) on its way in, and
+ v0 did not -- so a legacy bundle naming ``partition_mapped_column: n``
+ and a transform of ``random() + :value`` on ``n`` imported happily and
+ then failed *every* later save: a description-only
+ ``PUT /api/v1/dataset/<id>`` returns 422 on the stored expression, and
+ the mapping never mirrors anything. Applied to the config rather than
+ the model because that is where the transform still is.
+
+ Disarming the old mapping. `DatasetDAO.clear_unmapped_partition_transforms`
+ reads the mapping as it stands, so the post-import call can only enforce
+ the one-transform invariant against the *new* references. An overwrite
+ that re-points the mapping makes a previously unmapped column the
+ effective one, and a transform parked there -- which nothing in the
+ bundle authored -- is found already mapped by the later call and kept.
+ A dataset mapping ``a -> p`` with a parked ``:value + 100`` on ``b``,
+ overwritten by a bundle setting ``partition_mapped_column: b`` and
+ omitting the columns, would mirror ``b = 5`` as ``p = 105`` and drop the
+ row ``(a=1, b=5, p=1)``. The same pre-change call `DatasetDAO.update`
+ and the v1 importer both make, and for the same reason.
+
+ ``database`` is ``None`` only for a CLI bundle importing a connection
+ that does not exist yet, which by definition has no stored dataset to
+ disarm and no dialect to validate a transform against -- the same case
+ `drop_unusable_partition_transforms` already declines to act on.
+ """
+ if database is None:
+ return
+
+ # Deferred import: `daos.dataset` pulls in `views.base`, which
+ # circularly imports back into the commands package at app init.
+ from superset.daos.dataset import DatasetDAO # noqa: PLC0415
+
+ drop_unusable_partition_transforms(dataset, database)
+
+ if not (table_name := dataset.get("table_name")):
+ return
+ existing = (
+ db.session.query(SqlaTable)
+ .filter(
+ SqlaTable.table_name == table_name,
+ SqlaTable.schema == dataset.get("schema"),
+ SqlaTable.catalog == dataset["catalog"]
+ if dataset.get("catalog") is not None
+ else True,
+ SqlaTable.database_id == database.id,
+ )
+ .one_or_none()
+ )
+ if existing is not None:
+ DatasetDAO.clear_unmapped_partition_transforms(existing)
+
+ @staticmethod
+ def _repair_partition_mappings(datasets: list[SqlaTable]) -> None:
+ """
+ Keep the partition filter mapping honest across a v0 import.
+
+ The mapping's columns ride in `SqlaTable.export_fields`, so this path
+ carries them -- but it calls `SqlaTable.import_from_dict` directly and
+ goes through neither `DatasetDAO.update` nor the v1 importer, so
+ neither of the mapping's repairs ran. An older bundle imported with
+ ``--sync columns`` that omits the partition column deletes it and keeps
+ `partition_column` naming it: pruning silently stops, and every later
+ edit of that dataset fails the partition-column-not-found validation,
+ including a description-only PUT, which carries no columns payload and
+ so cannot reach the branch that forgives a stored-only dangle.
+
+ The same pair, in the same order, as `RefreshDatasetCommand` and the
+ v1 importer. Run after the import rather than around it because
+ ``import_from_dict`` is what discovers which datasets are involved.
+ """
+ if not datasets:
+ return
+ # Deferred import: `daos.dataset` pulls in `views.base`, which
+ # circularly imports back into the commands package at app init.
+ from superset.daos.dataset import DatasetDAO # noqa: PLC0415
+
+ db.session.flush()
+ for dataset in datasets:
+ DatasetDAO.clear_dangling_partition_mapping(
Review Comment:
`dataset.columns` is still the pre-import collection here: `import_from_dict` removes omitted columns with `session.delete(...)`, and `flush()` doesn't drop them from an already-loaded relationship. With `sync=["columns"]` and a bundle that omits the partition column `p`, `p` still counts as a survivor, so `partition_column` keeps naming a column that no longer exists. Pruning stops and every later PUT (even description-only) fails the column-not-found validation. Should this expire `columns` before reading the surviving names, the way the v1 importer does?
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/DatasourceEditor.tsx:
##########
@@ -1250,6 +1379,178 @@ function DatasourceEditor({
[],
);
+ // Which column's row expand to open, for the "map a different column" links.
+ // Consumed by the Columns tab, which scrolls the row into view and expands it.
+ //
+ // Carries a nonce because the request is an event, not a state: clicking the
+ // same link twice -- after collapsing the row by hand in between -- asks for
+ // the same column name, and a bare string would make the second
+ // `setColumnToReveal` a no-op. React would bail out of the render, nothing
+ // downstream would see a change, and the row would stay shut.
+ const [columnToReveal, setColumnToReveal] = useState<{
+ name: string;
+ nonce: number;
+ } | null>(null);
+
+ // What the mapped column's own preview said, relayed up from its row expand
+ // so the dataset-level banner cannot claim a mirror that panel has already
+ // refused. Reported rather than lifted: the transform the preview judges is
+ // the debounced local one that panel owns. `null` means no verdict yet.
+ const [previewMirrors, setPreviewMirrors] = useState<boolean | null>(null);
+
+ const handlePartitionColumnChange = useCallback(
+ (columnName: string | null) => {
+ const next = {
+ ...datasource,
+ partition_column: columnName,
+ partition_mapped_column: nextMappedColumnOverride(
+ datasource.partition_mapped_column,
+ columnName,
+ ),
+ };
+ setDatasource(prev => ({
+ ...prev,
+ partition_column: next.partition_column,
+ partition_mapped_column: next.partition_mapped_column,
+ }));
+ // Choosing or clearing the partition column moves which column the
+ // mapping mirrors, so the one-transform invariant is enforced on both
+ // sides of it -- the same reason the column sync does, and the same
+ // reason `DatasetDAO.update` runs its own pass twice. Designating a
+ // partition column where there was none makes the default datetime
+ // column the mapped one, and a transform stranded there by an earlier
+ // writer would otherwise arrive live from a single select. Clearing the
+ // partition column leaves no mapped column at all, so no column may hold
+ // a transform -- which is what the server does too.
+ //
+ // A transform on a column that is mapped on both sides is untouched, so
+ // re-pointing the partition column does not cost the owner what they
+ // wrote.
+ setDatabaseColumns(prev =>
+ clearUnmappedTransformsAcrossMove(datasource, next, prev),
+ );
+ setCalculatedColumns(prev =>
+ clearUnmappedTransformsAcrossMove(datasource, next, prev),
+ );
+ // Deliberately nothing else. Designating a partition column must not
+ // touch that column's own `filterable`/`groupby` flags: hiding it from
+ // Explore is a per-column decision the owner makes, not a side effect of
+ // the mapping, and forcing it here silently changed behaviour for a
+ // dataset that already exposes its partition column.
+ //
+ // No feature-flag gate, unlike `handleMainDttmColChange`: the select that
+ // calls this only renders inside `PartitionColumnFields`, which mounts
+ // only when the flag is on.
+ },
+ [datasource],
+ );
+
+ const handleNavigateToColumn = useCallback((columnName: string) => {
Review Comment:
Calculated columns can be the mapped column (the validation tests cover it), but this always switches to the physical Columns tab and filters it by name. For a calculated mapped column that table is empty, so "Customize the value transform" / "Map a different column" land on nothing, and neither the transform editor nor a replacement action appears. Should the handler route to the Calculated columns tab when the column is calculated?
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/PartitionColumnFields.tsx:
##########
@@ -0,0 +1,349 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { useMemo } from 'react';
+import { t } from '@apache-superset/core/translation';
+import { css, useTheme } from '@apache-superset/core/theme';
+import { Alert } from '@apache-superset/core/components';
+import {
+ Button,
+ Flex,
+ Icons,
+ InfoTooltip,
+ Label,
+ Select,
+ Tooltip,
+ Typography,
+} from '@superset-ui/core/components';
+import {
+ mappedColumnIsImplicit,
+ mappingIsActive,
+ partitionMappingErrors,
+ resolveMappedColumn,
+ suggestedMappedColumn,
+} from './utils';
+import type {
+ PartitionMappingColumn,
+ PartitionMappingDatasource,
+ PartitionMappingIssue,
+} from './types';
+
+interface PartitionColumnFieldsProps {
+ datasource: PartitionMappingDatasource;
+ /**
+ * Physical columns: what the partition-column dropdown may offer, and where
+ * a replacement mapped column may be suggested from. A calculated column
+ * belongs in neither -- the engine cannot partition on an expression, and
+ * the mapping picker only renders on a physical column's row.
+ */
+ columns: PartitionMappingColumn[];
+ /**
+ * Every column on the dataset, physical and calculated. What *exists* is a
+ * different question from what may be picked, and validation asks the first:
+ * the backend accepts a calculated column as the mapped-column override, so
+ * checking existence against the physical columns alone reported a column
+ * that is really there as missing -- and blocked Save with no way out, since
+ * the dropdown cannot offer it back.
+ */
+ allColumns: PartitionMappingColumn[];
+ onPartitionColumnChange: (columnName: string | null) => void;
+ /** Open the given column's row expand in the Columns table. */
+ onNavigateToColumn: (columnName: string) => void;
+ /**
+ * Whether the mapped column's own preview says the transform mirrors, or
+ * `null`/undefined when no verdict is in yet. The checks this section can
+ * make are all static -- a transform the database rejects clears every one
+ * of them -- so without the preview's answer the banner claimed a speed-up
+ * the query never delivers.
+ */
+ previewMirrors?: boolean | null;
+}
+
+/**
+ * "Partition column" and the computed "Maps to partition" (wireframes 1a, 1g).
+ *
+ * "Maps to partition" is deliberately read-only. It reflects
+ * `partition_mapped_column ?? main_dttm_col`, and a peer dropdown would let it
+ * drift from the default datetime column silently. The only way to override it
+ * is from the target column's own row, where a transform has to be supplied
+ * alongside.
+ */
+export default function PartitionColumnFields({
+ datasource,
+ columns,
+ allColumns,
+ onPartitionColumnChange,
+ onNavigateToColumn,
+ previewMirrors,
+}: PartitionColumnFieldsProps) {
+ const theme = useTheme();
+
+ const options = useMemo(
+ () =>
+ columns.map(column => ({
+ value: column.column_name,
+ label: column.column_name,
+ customLabel: (
+ <Flex align="center" gap={theme.sizeUnit}>
+ <span>{column.column_name}</span>
+ {column.type && <Label>{column.type}</Label>}
+ </Flex>
+ ),
+ })),
+ [columns, theme.sizeUnit],
+ );
+
+ const mappedColumn = resolveMappedColumn(datasource);
+ const isImplicit = mappedColumnIsImplicit(datasource);
+ const liveTransform =
+ allColumns.find(column => column.column_name === mappedColumn)
+ ?.partition_value_transform ?? null;
+ // The stored refusal, but only while the box still holds the expression it
+ // was about. It is a verdict on one transform, and it outlived it: reopen a
+ // dataset whose stored `no_such_fn(:value)` failed its last probe, replace it
+ // with something that works, watch the row's own preview come back valid --
+ // and the banner still said nothing would mirror, because this read a summary
+ // computed when the editor opened.
+ const storedVerdictApplies =
+ liveTransform === datasource.partition_filter_mapping?.evaluated_transform;
+ // The static checks are necessary, not sufficient: an unparseable expression
+ // or a function the database does not have needs the engine to spot, and the
+ // mapped column's row already asks it. Deferring to that answer where there
+ // is one is what keeps this banner and that panel from contradicting each
+ // other.
+ const isActive =
+ mappingIsActive(datasource, allColumns) &&
+ previewMirrors !== false &&
Review Comment:
The stored verdict still wins when the transform is unchanged: open a dataset whose mapped transform has `evaluable: false` from a transient warehouse failure (so `evaluated_transform` equals the live one) and the row's own preview now succeeds. `previewMirrors` is `true` but `storedVerdictApplies` keeps `isActive` false, so the row shows "Valid" with an emitted predicate while the banner says nothing mirrors. Should a live preview verdict take precedence over the stored one once it exists?
##########
tests/unit_tests/connectors/sqla/partition_mapping_test.py:
##########
@@ -0,0 +1,3632 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Unit tests for ``superset.connectors.sqla.partition_mapping``."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from decimal import Decimal
+from importlib import import_module
+from typing import Any, cast
+from unittest.mock import MagicMock, patch, PropertyMock
+
+import pandas as pd
+import pytest
+from dateutil.relativedelta import relativedelta
+from flask import Flask
+from pytest_mock import MockerFixture
+from sqlalchemy.dialects import mysql, postgresql
+
+from superset.config import DISALLOWED_SQL_FUNCTIONS
+from superset.connectors.sqla.models import SqlaTable, TableColumn
+from superset.connectors.sqla.partition_mapping import (
+ _mirror_verdict_cache_key,
+ _placeholder_is_bindable,
+ _probe_cache_key,
+ _reads_as_temporal,
+ _render_literal,
+ _render_predicate,
+ BARE_WALL_CLOCK_KEYWORDS,
+ build_mirrored_predicates,
+ build_probe_sql,
+ contains_executable_comment,
+ contains_jinja,
+ contains_value_placeholder,
+ drop_unmapped_value_transforms,
+ equality_mirrors_safely,
+ evaluate_transform,
+ find_non_deterministic_functions,
+ grain_bucket_width,
+ GRAIN_BUCKET_WIDTHS,
+ is_bare_expression,
+ is_parseable,
+ is_transform_active,
+ is_unfinished,
+ known_mirror_verdict,
+ literal_round_trips,
+ MappingValidationIssue,
+ mirror_operator,
+ MIRRORABLE_ALWAYS,
+ MIRRORABLE_IF_MONOTONIC,
+ mirrorable_operators,
+ NON_DETERMINISTIC_FUNCTIONS,
+ parse_error_detail,
+ placeholder_is_executable,
+ probe_sql_is_evaluable,
+ probed_value_type_error,
+ RawProbeValue,
+ resolve_partition_mapping,
+ stored_expression_error,
+ validate_partition_mapping,
+ validate_transform,
+)
+from superset.constants import TimeGrain
+from superset.db_engine_specs.base import BaseEngineSpec
+from superset.db_engine_specs.mysql import MySQLEngineSpec
+from superset.db_engine_specs.oracle import OracleEngineSpec
+from superset.db_engine_specs.postgres import PostgresEngineSpec
+from superset.models.core import Database
+from superset.sql.parse import SQLStatement
+from superset.utils.core import FilterOperator, GenericDataType, override_user
+
+
+@pytest.fixture(autouse=True)
+def real_probe_cache(app: Flask) -> Any:
+ """
+ The test app runs a null cache, which would make every cache assertion here
+ vacuously pass. Swap in a real in-memory one for the duration.
+ """
+ from flask_caching import Cache
+
+ from superset.extensions import cache_manager
+
+ cache = Cache(config={"CACHE_TYPE": "SimpleCache", "CACHE_DEFAULT_TIMEOUT": 300})
+ cache.init_app(app)
+ original = cache_manager._cache # noqa: SLF001
+ cache_manager._cache = cache # noqa: SLF001
+ yield
+ cache_manager._cache = original # noqa: SLF001
+
+
+@pytest.fixture(autouse=True)
+def enable_partition_filter_mapping(app: Flask) -> Any:
+ """The feature ships off; every test here exercises it on."""
+ original = app.config["DEFAULT_FEATURE_FLAGS"].get("PARTITION_FILTER_MAPPING")
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = True
+ yield
+ if original is None:
+ del app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"]
+ else:
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = original
+
+
+def _table(**kwargs: Any) -> SqlaTable:
+ database = Database(database_name="test_db", sqlalchemy_uri="sqlite://")
+ defaults: dict[str, Any] = {
+ "table_name": "web_events",
+ "database": database,
+ "main_dttm_col": "event_time",
+ "columns": [
+ TableColumn(column_name="event_time", is_dttm=True, type="TIMESTAMP"),
+ TableColumn(
+ column_name="dt_epoch",
+ type="BIGINT",
+ partition_value_transform=None,
+ ),
+ TableColumn(column_name="country", type="VARCHAR"),
+ TableColumn(column_name="region_key", type="VARCHAR"),
+ ],
+ }
+ defaults.update(kwargs)
+ return SqlaTable(**defaults)
+
+
+def _mapped_table(
+ *,
+ partition_column: str = "dt_epoch",
+ mapped_column: str = "event_time",
+ transform: str | None = "unix_timestamp(:value)",
+ monotonic: bool = True,
+ partition_mapped_column: str | None = None,
+ main_dttm_col: str | None = "event_time",
+) -> SqlaTable:
+ table = _table(main_dttm_col=main_dttm_col)
+ table.partition_column = partition_column
+ table.partition_mapped_column = partition_mapped_column
+ for column in table.columns:
+ if column.column_name == mapped_column:
+ column.partition_value_transform = transform
+ column.partition_transform_is_monotonic = monotonic
+ return table
+
+
+# ---------------------------------------------------------------------------
+# §2 — operator safety matrix
+# ---------------------------------------------------------------------------
+
+
+def test_equality_and_in_are_always_mirrorable() -> None:
+ """``=`` and ``IN`` are safe for any function ``T``."""
+ assert MIRRORABLE_ALWAYS == {FilterOperator.EQUALS, FilterOperator.IN}
+
+
+def test_range_operators_require_a_monotonic_transform() -> None:
+ assert MIRRORABLE_IF_MONOTONIC == {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+ }
+
+
+def test_mirrorable_operators_excludes_ranges_when_not_monotonic() -> None:
+ assert mirrorable_operators(is_monotonic=False) == MIRRORABLE_ALWAYS
+
+
+def test_mirrorable_operators_includes_ranges_when_monotonic() -> None:
+ assert mirrorable_operators(is_monotonic=True) == (
+ MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+ )
+
+
+@pytest.mark.parametrize(
+ "operator",
+ [
+ FilterOperator.NOT_EQUALS,
+ FilterOperator.NOT_IN,
+ FilterOperator.LIKE,
+ FilterOperator.ILIKE,
+ FilterOperator.NOT_LIKE,
+ FilterOperator.NOT_ILIKE,
+ FilterOperator.IS_NULL,
+ FilterOperator.IS_NOT_NULL,
+ FilterOperator.IS_TRUE,
+ FilterOperator.IS_FALSE,
+ ],
+)
+def test_negations_and_pattern_matches_are_never_mirrorable(
+ operator: FilterOperator,
+) -> None:
+ """
+ ``T`` is not injective, so ``col != v`` does **not** imply ``T(col) != T(v)``:
+ mirroring it would drop rows the original filter keeps.
+ """
+ assert operator not in mirrorable_operators(is_monotonic=True)
+
+
+def test_equality_is_dropped_when_the_engine_does_not_compare_byte_exactly() -> None:
+ """
+ "Safe for any function ``T``" reasons about value equality: ``T`` is a
+ function, so ``col = v`` gives ``T(col) = T(v)``. The engine reasons about
+ *SQL* equality, and the two part company under a case-insensitive
+ collation -- a stored ``'us'`` satisfies a filter for ``'US'`` while the
+ mirror ``hex('US')`` excludes the row, and the chart loses it silently.
+ """
+ assert mirrorable_operators(is_monotonic=False, equality_is_safe=False) == set()
+
+
+def test_ranges_survive_an_unsafe_equality() -> None:
+ """
+ Range mirroring already rests on the owner declaring ``T``
+ order-preserving with respect to the column's own order -- an assertion
+ about the very comparison semantics this gate checks for. Equality has no
+ such declaration behind it, which is why only equality is withdrawn.
+ """
+ assert (
+ mirrorable_operators(is_monotonic=True, equality_is_safe=False)
+ == MIRRORABLE_IF_MONOTONIC
+ )
+
+
+@pytest.mark.parametrize(
+ "operator,expected",
+ [
+ (FilterOperator.GREATER_THAN, FilterOperator.GREATER_THAN_OR_EQUALS),
+ (FilterOperator.LESS_THAN, FilterOperator.LESS_THAN_OR_EQUALS),
+ (
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ ),
+ (FilterOperator.LESS_THAN_OR_EQUALS, FilterOperator.LESS_THAN_OR_EQUALS),
+ (FilterOperator.EQUALS, FilterOperator.EQUALS),
+ (FilterOperator.IN, FilterOperator.IN),
+ ],
+)
+def test_a_strict_bound_mirrors_non_strictly(
+ operator: FilterOperator, expected: FilterOperator
+) -> None:
+ """
+ Order-preserving means non-decreasing, not injective, so ``col < v``
+ implies only ``T(col) <= T(v)``. A day-key transform maps a whole day onto
+ one value and a strict mirror drops the boundary bucket. The non-strict
+ cases are already safe and pass through, which is what makes applying this
+ twice harmless.
+ """
+ assert mirror_operator(operator) == expected
+
+
+def test_relaxing_a_bound_stays_inside_the_mirrorable_set() -> None:
+ """
+ The substitution is about strictness, not about which filters mirror. The
+ Explore indicator reads `mirrorable_operators`, so leaving that set alone is
+ what keeps the glyph from promising pruning the SQL does not do -- and it is
+ also what guarantees `handle_comparison_filter` is never handed an operator
+ it has no case for.
+ """
+ assert {
+ mirror_operator(operator) for operator in MIRRORABLE_IF_MONOTONIC
+ } <= MIRRORABLE_IF_MONOTONIC
+
+
+def _column(type_: str) -> TableColumn:
+ database = Database(database_name="t", sqlalchemy_uri="sqlite://")
+ table = SqlaTable(table_name="t", database=database)
+ return TableColumn(column_name="c", type=type_, table=table)
+
+
+@pytest.mark.parametrize(
+ "type_, binary, expected",
+ [
+ ("VARCHAR", True, True),
+ ("VARCHAR", False, False),
+ # Numeric and temporal comparison is exact everywhere.
+ ("BIGINT", False, True),
+ ("TIMESTAMP", False, True),
+ ("DOUBLE", False, True),
+ ],
+)
+def test_equality_mirrors_safely_only_guards_string_columns(
+ app: Flask, type_: str, binary: bool, expected: bool
+) -> None:
+ class _Spec(BaseEngineSpec):
+ binary_string_comparison = binary
+
+ with app.app_context():
+ assert equality_mirrors_safely(_column(type_), _Spec) is expected
+
+
+@pytest.mark.parametrize(
+ "type_, expected",
+ [
+ # The padded types: `'US'` and `'US '` are equal in the column, and
+ # `lower()` of the two is not.
+ ("CHAR(2)", False),
+ ("CHAR", False),
+ ("CHARACTER(2)", False),
+ ("NCHAR(2)", False),
+ # What PostgreSQL reflection reports for a `CHAR(n)` column.
+ ("BPCHAR", False),
+ ("bpchar(2)", False),
+ ("NATIONAL CHARACTER(2)", False),
+ # The variable-width types start with the same letters and must not be
+ # caught by it.
+ ("VARCHAR(2)", True),
+ ("NVARCHAR(2)", True),
+ ("CHARACTER VARYING(2)", True),
+ ("TEXT", True),
+ ],
+)
+def test_a_padded_character_column_declines_equality_on_a_byte_exact_engine(
+ app: Flask, type_: str, expected: bool
+) -> None:
+ """
+ `binary_string_comparison` speaks for the engine's default comparison,
+ which PostgreSQL declares -- and a `CHAR(2)` there still matches a filter
+ for `'US '` against a stored `'US'`, so the mirror `lower('US ')` excludes
+ the row. Padding is a property of the type, so it is asked per column.
+ """
+
+ class _Spec(BaseEngineSpec):
+ binary_string_comparison = True
+
+ with app.app_context():
+ assert equality_mirrors_safely(_column(type_), _Spec) is expected
+
+
+def test_redshift_does_not_opt_in_to_byte_exact_comparison() -> None:
+ """
+ Redshift ignores trailing blanks for `VARCHAR` as well as `CHAR`, so the
+ `True` it inherits from `PostgresBaseEngineSpec` would be wrong.
+ """
+ from superset.db_engine_specs.redshift import RedshiftEngineSpec
+
+ assert RedshiftEngineSpec.binary_string_comparison is False
+
+
+@pytest.mark.parametrize(
+ "type_",
+ [
+ # PostgreSQL's case-insensitive text type matches no type pattern, so
+ # the spec cannot classify it -- and its whole purpose is the
+ # comparison this gate is about.
+ "citext",
+ # A column with no declared type at all.
+ "",
+ "SOME_EXTENSION_TYPE",
+ ],
+)
+def test_equality_mirrors_safely_fails_closed_on_an_unresolvable_type(
+ app: Flask, type_: str
+) -> None:
+ """
+ The gate exists to stop a silent wrong answer, so a column whose type it
+ cannot read is treated as the risky case rather than waved through.
+
+ `type_generic` answers `None` for these -- neither string nor not-string --
+ and the old reading waved them through, which for `citext` admitted exactly
+ the case-insensitive equality the gate is for. Only the exception branch
+ failed closed, though the docstring claimed otherwise.
+ """
+ with app.app_context():
+ assert equality_mirrors_safely(_column(type_), PostgresEngineSpec) is False
+
+
+def test_equality_mirrors_safely_reads_past_the_temporal_flag(app: Flask) -> None:
+ """
+ `TableColumn.type_generic` answers `TEMPORAL` for anything carrying
+ `is_dttm`, so a `VARCHAR` flagged temporal skipped the string check
+ entirely: on MySQL a filter for `'2026-01-01T00:00:00'` matches a stored
+ `'...t00:00:00'` while the mirror `hex('...T...')` excludes it.
+ """
+ with app.app_context():
+ flagged = _column("VARCHAR")
+ flagged.is_dttm = True
+ assert flagged.type_generic == GenericDataType.TEMPORAL
+ # Declines where plain text declines...
+ assert equality_mirrors_safely(flagged, MySQLEngineSpec) is False
+ # ...and is admitted where plain text is admitted.
+ assert equality_mirrors_safely(flagged, PostgresEngineSpec) is True
+
+ # A column that really is temporal is unaffected.
+ real = _column("TIMESTAMP")
+ real.is_dttm = True
+ assert equality_mirrors_safely(real, MySQLEngineSpec) is True
+
+
+def test_no_mapped_column_leaves_the_matrix_alone(app: Flask) -> None:
+ """Nothing to reason about, and the resolver bails out on it anyway."""
+ with app.app_context():
+ assert equality_mirrors_safely(None, BaseEngineSpec) is True
+
+
+@pytest.mark.parametrize(
+ "module, spec_name",
+ [
+ ("presto", "PrestoEngineSpec"),
+ ("hive", "HiveEngineSpec"),
+ ("trino", "TrinoEngineSpec"),
+ ("impala", "ImpalaEngineSpec"),
+ ("postgres", "PostgresEngineSpec"),
+ ("bigquery", "BigQueryEngineSpec"),
+ ("sqlite", "SqliteEngineSpec"),
+ ],
+)
+def test_the_byte_exact_engines_opt_in(module: str, spec_name: str) -> None:
+ """
+ The engines this feature targets compare text byte-exactly, so the gate
+ must not cost them the second canonical mapping (`lower(:value)` onto a
+ lowercased key).
+ """
+ spec = getattr(import_module(f"superset.db_engine_specs.{module}"), spec_name)
+ assert spec.binary_string_comparison is True
+
+
+@pytest.mark.parametrize("module, spec_name", [("mysql", "MySQLEngineSpec")])
+def test_a_case_insensitive_engine_does_not_opt_in(module: str, spec_name: str) -> None:
+ """
+ MySQL's default collation is `utf8mb4_0900_ai_ci`, which is exactly the
+ case the reviewer raised.
+ """
+ spec = getattr(import_module(f"superset.db_engine_specs.{module}"), spec_name)
+ assert spec.binary_string_comparison is False
+
+
+def test_the_base_spec_does_not_opt_in() -> None:
+ """A spec that has not said so does not mirror string equality."""
+ assert BaseEngineSpec.binary_string_comparison is False
+
+
+# ---------------------------------------------------------------------------
+# Time grain bucket widths
+# ---------------------------------------------------------------------------
+
+
+@pytest.mark.parametrize("grain", list(TimeGrain))
+def test_every_builtin_grain_has_a_known_bucket_width(
+ app: Flask, grain: TimeGrain
+) -> None:
+ """
+ The widening is only sound for a grain whose bucket width we know, so a
+ grain added upstream without a width here would silently stop mirroring.
+ This is the test that notices.
+ """
+ with app.app_context():
+ assert grain_bucket_width(grain.value, "sqlite") is not None
+
+
+def test_a_calendar_grain_widens_by_a_calendar_month(app: Flask) -> None:
+ """A month is not thirty days, and the month it lands in decides its width."""
+ with app.app_context():
+ width = grain_bucket_width(TimeGrain.MONTH.value, "sqlite")
+
+ assert width is not None
+ assert datetime(2026, 1, 31) + width == datetime(2026, 2, 28)
+ assert datetime(2026, 2, 1) + width == datetime(2026, 3, 1)
+
+
+def test_a_fractional_grain_has_a_width(app: Flask) -> None:
+ """
+ ``PT0.5H`` and ``P0.25Y`` are why the widths are written out rather than
+ parsed -- and the anchored week grains are intervals ``parse_duration``
+ rejects outright.
+ """
+ with app.app_context():
+ assert grain_bucket_width(TimeGrain.HALF_HOUR.value, "sqlite") == relativedelta(
+ minutes=30
+ )
+ assert grain_bucket_width(
+ TimeGrain.WEEK_ENDING_SATURDAY.value, "sqlite"
+ ) == relativedelta(days=7)
+
+
+def test_an_unknown_grain_has_no_known_width(app: Flask) -> None:
+ with app.app_context():
+ assert grain_bucket_width("P13X", "sqlite") is None
+ assert grain_bucket_width(None, "sqlite") is None
+
+
+def test_an_addon_grain_has_no_known_width(app: Flask) -> None:
+ """An operator-declared grain carries whatever duration string they typed."""
+ with app.app_context():
+ app.config["TIME_GRAIN_ADDONS"] = {"PT2S": "2 second"}
+ try:
+ assert grain_bucket_width("PT2S", "sqlite") is None
+ finally:
+ app.config["TIME_GRAIN_ADDONS"] = {}
+
+
+def test_a_builtin_grain_an_operator_redefined_has_no_known_width(
+ app: Flask,
+) -> None:
+ """
+ ``TIME_GRAIN_ADDON_EXPRESSIONS`` replaces a built-in grain's SQL for one
+ engine, so its duration no longer bounds the displacement *there* -- but it
+ still does on every other engine.
+ """
+ with app.app_context():
+ app.config["TIME_GRAIN_ADDON_EXPRESSIONS"] = {
+ "sqlite": {"P1D": "DATETIME({col}, 'start of year')"}
+ }
+ try:
+ assert grain_bucket_width(TimeGrain.DAY.value, "sqlite") is None
+ assert grain_bucket_width(TimeGrain.DAY.value, "hive") is not None
+ finally:
+ app.config["TIME_GRAIN_ADDON_EXPRESSIONS"] = {}
+
+
+def test_the_width_table_is_keyed_on_grain_durations(app: Flask) -> None:
+ """Keys are the ISO duration a filter carries, not the enum member name."""
+ assert GRAIN_BUCKET_WIDTHS[TimeGrain.DAY] == relativedelta(days=1)
+ assert set(GRAIN_BUCKET_WIDTHS) == {grain.value for grain in TimeGrain}
+
+
+# ---------------------------------------------------------------------------
+# §4.1 — resolving the effective mapping, and the defensive bail-outs
+# ---------------------------------------------------------------------------
+
+
+def test_resolve_returns_the_mapping_when_everything_lines_up(app: Flask) -> None:
+ with app.app_context():
+ mapping = resolve_partition_mapping(_mapped_table())
+
+ assert mapping is not None
+ assert mapping.partition_column == "dt_epoch"
+ assert mapping.mapped_column == "event_time"
+ assert mapping.value_transform == "unix_timestamp(:value)"
+ assert mapping.is_monotonic is True
+
+
+def test_effective_mapped_column_follows_main_dttm_col(app: Flask) -> None:
+ """No explicit override: the mapping follows the default datetime column."""
+ with app.app_context():
+ mapping = resolve_partition_mapping(_mapped_table())
+
+ assert mapping is not None
+ assert mapping.mapped_column == "event_time"
+
+
+def test_explicit_override_wins_over_main_dttm_col(app: Flask) -> None:
+ table = _mapped_table(
+ mapped_column="country",
+ transform="lower(:value)",
+ monotonic=False,
+ partition_mapped_column="country",
+ )
+ table.partition_column = "region_key"
+
+ with app.app_context():
+ mapping = resolve_partition_mapping(table)
+
+ assert mapping is not None
+ assert mapping.mapped_column == "country"
+ assert mapping.partition_column == "region_key"
+ assert mapping.is_monotonic is False
+
+
+def test_resolve_returns_none_when_the_feature_flag_is_off(app: Flask) -> None:
+ table = _mapped_table()
+ with app.app_context():
+ with patch(
+ "superset.connectors.sqla.partition_mapping.feature_flag_manager."
+ "is_feature_enabled",
+ return_value=False,
+ ):
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_without_a_partition_column(app: Flask) -> None:
+ table = _mapped_table()
+ table.partition_column = None
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_partition_column_no_longer_exists(
+ app: Flask,
+) -> None:
+ """A column sync can drop the physical partition column out from under us."""
+ table = _mapped_table()
+ table.partition_column = "dt_epoch_gone"
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_the_mapped_column_no_longer_exists(
+ app: Flask,
+) -> None:
+ table = _mapped_table(main_dttm_col="vanished")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_on_self_mapping(app: Flask) -> None:
+ """
+ ``partition_column == effective mapped column`` mirrors a column onto itself.
+ Save-time validation rejects it, but rows predating that validation exist.
+ """
+ table = _mapped_table(
+ partition_column="event_time",
+ mapped_column="event_time",
+ )
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+@pytest.mark.parametrize("transform", [None, "", " "])
+def test_resolve_returns_none_without_a_transform(
+ app: Flask, transform: str | None
+) -> None:
+ table = _mapped_table(transform=transform)
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_the_transform_lacks_the_placeholder(
+ app: Flask,
+) -> None:
+ table = _mapped_table(transform="unix_timestamp(event_time)")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_for_a_non_deterministic_transform(app: Flask) -> None:
+ """
+ The query-time gate is `is_transform_active`, the same one the Explore
+ indicator reads. Anything narrower would let a transform that reached
+ storage without passing `UpdateDatasetCommand` -- through import, or a
+ hand-written bundle -- mirror a filter with a value frozen at probe time,
+ while the editor reported the mapping as inactive and nothing on screen
+ said otherwise.
+ """
+ table = _mapped_table(transform="unix_timestamp(:value) + rand()")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_for_a_multi_expression_transform(app: Flask) -> None:
+ """A select list is not an expression; the probe cannot align its columns."""
+ table = _mapped_table(transform="lower(:value), 'x'")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_for_an_unparseable_transform(app: Flask) -> None:
+ table = _mapped_table(transform="unix_timestamp(:value")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_the_mapped_column_has_an_advanced_data_type(
+ app: Flask,
+) -> None:
+ """
+ ``translate_filter`` builds its own predicate shape from *translated* values,
+ so the ``(operator, value)`` pair the operator matrix reasons about does not
+ exist. Mirroring anyway would silently apply the wrong values (§4.1).
+ """
+ table = _mapped_table()
+ for column in table.columns:
+ if column.column_name == "event_time":
+ column.advanced_data_type = "port"
+
+ with app.app_context():
+ with patch.dict(app.config["ADVANCED_DATA_TYPES"], {"port": MagicMock()}):
+ with patch(
+ "superset.connectors.sqla.partition_mapping.feature_flag_manager."
+ "is_feature_enabled",
+ side_effect=lambda flag: (
+ flag in {"PARTITION_FILTER_MAPPING", "ENABLE_ADVANCED_DATA_TYPES"}
+ ),
+ ):
+ assert resolve_partition_mapping(table) is None
+
+
+def test_advanced_data_type_does_not_block_when_the_flag_is_off(app: Flask) -> None:
+ """An inert ``advanced_data_type`` is not a reason to skip mirroring."""
+ table = _mapped_table()
+ for column in table.columns:
+ if column.column_name == "event_time":
+ column.advanced_data_type = "port"
+
+ with app.app_context():
+ with patch(
+ "superset.connectors.sqla.partition_mapping.feature_flag_manager."
+ "is_feature_enabled",
+ side_effect=lambda flag: flag == "PARTITION_FILTER_MAPPING",
+ ):
+ assert resolve_partition_mapping(table) is not None
+
+
+# ---------------------------------------------------------------------------
+# §5 — transform inspection helpers
+# ---------------------------------------------------------------------------
+
+
+@pytest.mark.parametrize(
+ "transform,expected",
+ [
+ ("unix_timestamp(:value)", True),
+ ("lower(:value)", True),
+ ("CAST(:value AS BIGINT)", True),
+ ("unix_timestamp(event_time)", False),
+ (":values", False),
+ ("", False),
+ (None, False),
+ ],
+)
+def test_contains_value_placeholder(transform: str | None, expected: bool) -> None:
+ assert contains_value_placeholder(transform) is expected
+
+
+@pytest.mark.parametrize(
+ "transform,expected",
+ [
+ ("unix_timestamp(:value)", False),
+ ("{{ current_username() }}", True),
+ ("lower({% if x %}:value{% endif %})", True),
+ ("lower(:value) -- {# comment #}", True),
+ ],
+)
+def test_contains_jinja(transform: str, expected: bool) -> None:
+ assert contains_jinja(transform) is expected
+
+
+def test_contains_jinja_answers_as_the_block_pattern_does() -> None:
+ """
+ The scan has to agree with the lazy, ``DOTALL`` pattern it stands in for
+ on every input, including overlapping and unclosed delimiters, so that no
+ stored transform changes verdict. Every string of up to seven characters
+ over the delimiter characters, a newline and a filler is checked.
+ """
+ import itertools
+ import re
+
+ pattern = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+ for length in range(8):
+ for chars in itertools.product("{}%#\na", repeat=length):
+ text = "".join(chars)
+ assert contains_jinja(text) is (pattern.search(text) is not None), text
+
+
+@pytest.mark.parametrize("opening", ["{{", "{%", "{#"])
+def test_contains_jinja_is_linear_in_a_run_of_opening_delimiters(
+ opening: str,
+) -> None:
+ """
+ A run of opening delimiters with no closing one made the lazy pattern retry
+ from every position, which is quadratic. Stored transforms are not
+ length-bounded here, so a long run has to stay cheap.
+ """
+ import time
+
+ started = time.monotonic()
+ assert contains_jinja(opening * 200_000) is False
+ assert time.monotonic() - started < 1
+
+
+@pytest.mark.parametrize(
+ ("transform", "expected"),
+ [
+ ("lower(:value)", False),
+ ("lower(:value) /* an ordinary comment */", False),
+ ("lower(:value) -- a line comment", False),
+ (":value /*!50000 + 1 */", True),
+ (":value /*M!50000 + 1 */", True),
+ (":value /*! + 1 */", True),
+ ("", False),
+ (None, False),
+ ],
+)
+def test_contains_executable_comment(transform: str | None, expected: bool) -> None:
+ assert contains_executable_comment(transform) is expected
+
+
+@pytest.mark.parametrize(
+ "transform",
+ [
+ "unix_timestamp(:value)",
+ "lower(:value)",
+ "CAST(:value AS BIGINT)",
+ "date_format(:value, 'yyyyMMdd')",
+ ],
+)
+def test_pure_transforms_report_no_non_deterministic_functions(
+ transform: str,
+) -> None:
+ assert find_non_deterministic_functions(transform, "hive") == set()
+
+
+@pytest.mark.parametrize(
+ "transform,expected_name",
+ [
+ ("date_diff(:value, now())", "NOW"),
+ ("CAST(:value AS BIGINT) + rand()", "RAND"),
+ ("CAST(:value AS DATE) - current_date", "CURRENT_DATE"),
+ ],
+)
+def test_non_deterministic_functions_are_reported(
+ transform: str, expected_name: str
+) -> None:
+ """
+ The probe runs at a different moment and in a different session from the
+ chart query, and its result is cached, so anything time- or
+ randomness-dependent freezes a snapshot of probe time into the predicate.
+ """
+ assert expected_name in find_non_deterministic_functions(transform, "hive")
+
+
+@pytest.mark.parametrize(
+ ("engine", "transform", "expected_name"),
+ [
+ # `now()` is statement-stable on PostgreSQL; these two are not even
+ # that, and the ANSI four did not name them.
+ ("postgresql", "age(clock_timestamp(), :value)", "CLOCK_TIMESTAMP"),
+ ("postgresql", "age(statement_timestamp(), :value)", "STATEMENT_TIMESTAMP"),
+ # Every engine spells "now" its own way, and the gate matches by name.
+ ("mysql", "datediff(sysdate(), :value)", "SYSDATE"),
+ ("mysql", "datediff(curdate(), :value)", "CURDATE"),
+ ("oracle", "datediff(day, :value, LOCALTIMESTAMP)", "LOCALTIMESTAMP"),
+ ("oracle", "SYSTIMESTAMP - :value", "SYSTIMESTAMP"),
+ ("mssql", "DATEDIFF(day, :value, GETDATE())", "GETDATE"),
+ ("mssql", "DATEDIFF(day, :value, SYSUTCDATETIME())", "SYSUTCDATETIME"),
+ ("clickhouse", "now64() - :value", "NOW64"),
+ ("bigquery", "DATE_DIFF(CURRENT_DATETIME(), :value, DAY)", "CURRENT_DATETIME"),
+ ],
+)
+def test_every_engine_s_spelling_of_now_is_reported(
+ engine: str, transform: str, expected_name: str
+) -> None:
+ """
+ The list is matched by SQL function name, so a spelling it does not carry
+ passes the gate. A relative partition key such as
+ `datediff(day, :value, LOCALTIMESTAMP)` is then probed once, cached, and
+ keeps emitting yesterday's partition value after midnight -- so the chart
+ silently drops rows.
+ """
+ assert expected_name in find_non_deterministic_functions(transform, engine)
+
+
+@pytest.mark.parametrize(
+ ("engine", "transform", "expected_name"),
+ [
+ # MySQL takes these with no parentheses at all...
+ ("mysql", "datediff(UTC_DATE, :value)", "UTC_DATE"),
+ ("mysql", "datediff(utc_timestamp, :value)", "UTC_TIMESTAMP"),
+ ("mysql", "datediff(CURRENT_DATE, :value)", "CURRENT_DATE"),
+ # ...as do Oracle and PostgreSQL for their own spellings.
+ # sqlglot normalizes Oracle's bare `SYSDATE` to `CURRENT_TIMESTAMP`,
+ # so it is caught as a function under that name -- which is a pass:
+ # what matters is that the gate reports it, not what it is called.
+ ("oracle", ":value - SYSDATE", "CURRENT_TIMESTAMP"),
+ ("oracle", ":value - SYSTIMESTAMP", "SYSTIMESTAMP"),
+ ("postgresql", "age(LOCALTIMESTAMP, :value)", "LOCALTIMESTAMP"),
+ ],
+)
+def test_a_bare_wall_clock_keyword_is_reported(
+ engine: str, transform: str, expected_name: str
+) -> None:
+ """
+ Written without parentheses these parse as *column references*, so the
+ function-name walk could not see them and probe time was frozen into a
+ cached mirror.
+ """
+ assert expected_name in find_non_deterministic_functions(transform, engine)
+
+
+def test_the_bare_list_stays_to_names_that_need_no_parentheses() -> None:
+ """
+ Refusing a bare name costs an owner a column genuinely called that, so the
+ list is only the datetime keywords SQL lets you write without `()`.
+ `rand`, `uuid` and `newid` always need them, and are plausible column
+ names.
+ """
+ assert BARE_WALL_CLOCK_KEYWORDS <= {
+ name.lower() for name in NON_DETERMINISTIC_FUNCTIONS
+ }
+ assert not BARE_WALL_CLOCK_KEYWORDS & {"rand", "random", "uuid", "newid"}
+ # A column by one of those names is still an ordinary column.
+ assert find_non_deterministic_functions("lower(:value) || uuid", "postgresql") == (
+ set()
+ )
+
+
+@pytest.mark.parametrize(
+ ("engine", "transform"),
+ [
+ # The canonical transforms, which must not be swept up by the names
+ # added above.
+ ("hive", "unix_timestamp(:value)"),
+ ("postgresql", "to_char(:value, 'YYYYMMDD')"),
+ ("postgresql", "extract(epoch from :value)"),
+ ("mysql", "date_format(:value, '%Y%m%d')"),
+ ("oracle", "trunc(:value)"),
+ ("mssql", "CONVERT(date, :value)"),
+ ],
+)
+def test_the_canonical_transforms_are_still_pure(engine: str, transform: str) -> None:
+ """The list grew; this is the half that says it did not grow into the
+ transforms this feature exists for."""
+ assert find_non_deterministic_functions(transform, engine) == set()
+
+
+def test_niladic_unix_timestamp_is_rejected_but_the_unary_form_is_not() -> None:
+ """
+ On Hive/Impala ``unix_timestamp()`` means "now" while ``unix_timestamp(x)``
+ -- the canonical temporal transform -- is pure. The distinction is the whole
+ reason this check inspects arity rather than just the name.
+ """
+ assert find_non_deterministic_functions("unix_timestamp(:value)", "hive") == set()
+ assert find_non_deterministic_functions(
+ "unix_timestamp(:value) - unix_timestamp()", "hive"
+ )
+
+
+# ---------------------------------------------------------------------------
+# §4.2 — probe evaluation
+# ---------------------------------------------------------------------------
+
+
+def _user(username: str) -> Any:
+ """A stand-in for `override_user`, which only needs `.username` here."""
+ user = MagicMock()
+ user.username = username
+ user.is_anonymous = False
+ return user
+
+
+def _database_returning(values: list[Any]) -> Database:
+ """A real ``Database`` (so the dialect is real) with only ``get_df`` stubbed."""
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ return_value=pd.DataFrame(
+ [values], columns=[f"v{i}" for i in range(len(values))]
+ )
+ )
+ return database
+
+
+def _database_returning_frame(frame: pd.DataFrame) -> Database:
+ """
+ ``_database_returning`` for a probe result whose column dtypes matter.
+
+ The flat-list sibling builds its frame from one Python list, so pandas
+ infers a single dtype and the row-versus-cell distinction cannot be seen.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ return_value=frame
+ )
+ return database
+
+
+def _probe(database: Database) -> MagicMock:
+ """
+ The stubbed ``get_df``, typed for call assertions.
+
+ ``Database.get_df`` is a real method, so mypy reads its declared signature
+ rather than the mock that replaced it and rejects ``.call_args`` and
+ friends.
+ """
+ return cast(MagicMock, database.get_df)
+
+
+def test_evaluate_transform_returns_one_value_per_input(app: Flask) -> None:
+ database = _database_returning([1767225600, 1769904000])
+
+ with app.app_context():
+ result = evaluate_transform(
+ database,
+ None,
+ "default",
+ "unix_timestamp(:value)",
+ ["2026-01-01 00:00:00", "2026-02-01 00:00:00"],
+ )
+
+ assert result == [1767225600, 1769904000]
+ _probe(database).assert_called_once()
+
+
+def test_evaluate_transform_binds_values_rather_than_interpolating(
+ app: Flask,
+) -> None:
+ """
+ Filter values are attacker-controlled (a Gamma user picks them), so they must
+ be bound and escaped, never pasted into the probe SQL.
+ """
+ database = _database_returning(["o''brien"])
+
+ with app.app_context():
+ evaluate_transform(database, None, None, "lower(:value)", ["O'Brien"])
+
+ sql = _probe(database).call_args.kwargs["sql"]
+ assert "O'Brien" not in sql
+ assert "O''Brien" in sql
+
+
+@pytest.mark.parametrize(
+ ("transform", "expected"),
+ [
+ ("lower(:value)", True),
+ ("CAST(:value AS BIGINT)", True),
+ ("date_format(:value, '%Y%m%d')", True),
+ # The cast shorthand: a trailing colon stops SQLAlchemy's bind scan.
+ (":value::bigint", False),
+ ("(:value::date)::text", False),
+ ],
+)
+def test_a_postgres_cast_shorthand_is_not_bindable(
+ transform: str, expected: bool
+) -> None:
+ """
+ `VALUE_PLACEHOLDER_RE` is `:value\b`, which matches inside `:value::bigint`.
+ SQLAlchemy's own scan ends with `(?![:\\w$])`, so the following colon stops
+ it: `text(":value::bigint")` reports a parameter named `valu`, and asking it
+ to bind `value` raises.
+
+ Pinned because the two regexes disagreeing is the whole bug: every
+ write-side gate accepted the transform and the probe then died on an
+ `ArgumentError` that `_probe` swallows.
+ """
+ assert _placeholder_is_bindable(transform) is expected
+
+
+def test_a_cast_shorthand_transform_still_probes(app: Flask) -> None:
+ """
+ The transform is valid SQL, passes every gate, and used to prune nothing:
+ `build_probe_sql` raised, `_probe` swallowed it, and the only symptom was a
+ mapping that silently never mirrored -- with the preview reporting an engine
+ failure for SQL that was never sent.
+ """
+ database = _database_returning([20260115])
+
+ with app.app_context():
+ result = evaluate_transform(
+ database, None, None, ":value::bigint", ["20260115"]
+ )
+
+ assert result == [20260115]
+ assert _probe(database).call_count == 1
+ assert "::bigint" in _probe(database).call_args.kwargs["sql"]
+
+
+def test_a_cast_shorthand_value_is_still_escaped_by_the_dialect(
+ app: Flask,
+) -> None:
+ """
+ The fallback substitutes where the bind path binds, so it has to earn the
+ same guarantee its sibling above pins: the value is rendered by the
+ dialect's literal processor, not pasted in.
+
+ Binding was only ever the vehicle for reaching that processor --
+ `_compile_literal` inlines the result either way -- so this renders first
+ and substitutes second. Same string, different order.
+
+ Rendering is necessary and not sufficient: whether the engine reads the
+ rendered text back as this value is a separate question, and the one
+ `literal_round_trips` answers. SQLite's engine honours the doubling its
+ driver emits, which is why this value is probed here at all.
+ """
+ database = _database_returning(["x"])
+
+ with app.app_context():
+ evaluate_transform(database, None, None, ":value::text", ["O'Brien"])
+
+ sql = _probe(database).call_args.kwargs["sql"]
+ assert "O'Brien" not in sql
+ assert "O''Brien" in sql
+
+
+def test_evaluate_transform_dedupes_repeated_values(app: Flask) -> None:
+ """Three inputs, two distinct: the probe evaluates the transform twice."""
+ database = _database_returning(["us", "us"])
+
+ with app.app_context():
+ result = evaluate_transform(
+ database, None, None, "lower(:value)", ["US", "US", "us"]
+ )
+
+ assert result == ["us", "us", "us"]
+ sql = _probe(database).call_args.kwargs["sql"]
+ assert sql.count("lower") == 2
+
+
+def test_evaluate_transform_fails_open_on_a_short_result_row(app: Flask) -> None:
+ """A row narrower than the probe asked for means the results cannot be
+ aligned back to their inputs; pruning is skipped rather than guessed at."""
+ database = _database_returning(["us"])
+
+ with app.app_context():
+ assert (
+ evaluate_transform(database, None, None, "lower(:value)", ["US", "CA"])
+ is None
+ )
+
+
+def test_evaluate_transform_fails_open_on_a_wide_result_row(app: Flask) -> None:
+ """
+ Too many columns is the dangerous direction. A transform whose select list
+ holds two expressions returns 2N columns for N inputs, and reading the first
+ N interleaves the expressions instead of taking one per value -- a predicate
+ built from the wrong values rather than one that is merely short. A frame of
+ `('us', 'x', 'ca', 'x')` read as the first two columns would have yielded
+ `('us', 'x')` and dropped every CA row.
+
+ The transform is a perfectly ordinary `lower(:value)` and the width comes
+ from the stubbed frame, which is the only way to reach the guard: a
+ transform that really does carry two expressions -- `lower(:value), 'x'` --
+ is refused by `stored_expression_error` for not being a single expression,
+ so `get_df` is never called and `None` comes back for an unrelated reason.
+ Asserting the probe *ran* is what separates the two, and it is what makes
+ relaxing the guard from `!=` to `<` fail here rather than pass: four columns
+ for two inputs is not fewer than two.
+ """
+ database = _database_returning(["us", "x", "ca", "x"])
+
+ with app.app_context():
+ assert (
+ evaluate_transform(database, None, None, "lower(:value)", ["US", "CA"])
+ is None
+ )
+
+ assert _probe(database).call_count == 1
+
+
+def test_the_probe_select_carries_the_engine_s_from_clause(app: Flask) -> None:
+ """
+ A `SELECT` with no `FROM` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from. Without this every probe on those engines
+ raises, which `evaluate_transform` swallows -- so the only symptom is a
+ correctly configured mapping that silently never prunes.
+ """
+ assert build_probe_sql("lower(:value)", ["US"]) == "SELECT lower('US') AS v0"
+ assert build_probe_sql("lower(:value)", ["US"], None, " FROM DUAL").endswith(
+ " FROM DUAL"
+ )
+ assert OracleEngineSpec.select_without_from_suffix == " FROM DUAL"
+ assert BaseEngineSpec.select_without_from_suffix == ""
+
+
+@pytest.mark.parametrize(
+ ("module", "spec_name", "suffix"),
+ [
+ ("oracle", "OracleEngineSpec", " FROM DUAL"),
+ ("db2", "Db2EngineSpec", " FROM SYSIBM.SYSDUMMY1"),
+ ],
+)
+def test_the_probe_reads_the_from_suffix_off_the_engine_spec(
+ app: Flask, mocker: MockerFixture, module: str, spec_name: str, suffix: str
+) -> None:
+ """
+ The sibling above hands `build_probe_sql` a suffix directly, so it never
+ exercises the step that reads `select_without_from_suffix` off the engine
+ spec and forwards it. Drop that forwarding and the sibling stays green
+ while Oracle and Db2 stop pruning entirely -- a bare `SELECT ...` raises
+ there, `evaluate_transform` swallows it, and the only symptom is a
+ correctly configured mapping that silently never prunes.
+
+ So this drives the real entry point and asserts on the SQL the engine is
+ handed, plus that the result is accepted.
+ """
+ spec = getattr(import_module(f"superset.db_engine_specs.{module}"), spec_name)
+ database = _database_returning(["us"])
+ mocker.patch.object(
+ type(database), "db_engine_spec", PropertyMock(return_value=spec)
+ )
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, "lower(:value)", ["US"]) == [
+ "us"
+ ]
+
+ sql = _probe(database).call_args.kwargs["sql"]
+ assert sql.endswith(suffix)
+ # And the gate that re-parses the compiled probe accepts that shape, rather
+ # than the suffix being appended only to be refused downstream.
+ assert probe_sql_is_evaluable(sql, spec.engine, 1, suffix) is True
+
+
+@pytest.mark.parametrize(
+ ("transform", "expected"),
+ [
+ (":value || ':suffix'", "SELECT 'us' || ':suffix' AS v0"),
+ ("concat(:value, ':x')", "SELECT concat('us', ':x') AS v0"),
+ ("replace(:value, ':a', ':b')", "SELECT replace('us', ':a', ':b') AS v0"),
+ # The separator shape, which is the ordinary reason to write one.
+ ("concat(:value, ':', 'x')", "SELECT concat('us', ':', 'x') AS v0"),
+ # A time format carries two.
+ (
+ "to_char(:value, 'HH24:MI:SS')",
+ "SELECT to_char('us', 'HH24:MI:SS') AS v0",
+ ),
+ # And the placeholder itself still binds.
+ ("lower(:value)", "SELECT lower('us') AS v0"),
+ ],
+)
+def test_a_colon_in_a_literal_is_not_read_as_a_bind(
+ transform: str, expected: str
+) -> None:
+ """
+ `text()` reads any `:word` as a bind parameter, including inside a string
+ literal, and an unbound one renders as `NULL` under literal binds rather
+ than raising. So `:value || ':suffix'` compiled to `'us' || 'NULL'`: the
+ mirror asked for a partition value no row holds and the chart dropped
+ rows, with no error for `_probe` to swallow.
+ """
+ assert build_probe_sql(transform, ["us"]) == expected
+
+
+def test_a_colon_literal_survives_the_unbindable_path_too() -> None:
+ """
+ The other branch substitutes textually through `parse_skeleton` and never
+ hands the transform to `text()`, so it was never affected -- pinned so the
+ escaping added for the bound path cannot leak into it as a stray backslash.
+ """
+ assert build_probe_sql(":value::bigint", [7]) == "SELECT 7::bigint AS v0"
+
+
+@pytest.mark.parametrize("dialect", [mysql.dialect(), postgresql.dialect()])
+def test_the_probe_select_does_not_double_percent_signs(dialect: Any) -> None:
+ """
+ `TextClause` compilation runs the dialect's `post_process_text`, which
+ doubles every `%` on any paramstyle whose DBAPI later interpolates
+ parameters -- MySQL and Postgres, and every spec inheriting from them. The
+ probe has no such interpolation pass: it executes with no bound parameters
+ at all. Left doubled, `date_format(:value, '%Y%m%d')` asks the warehouse
+ for the literal string `%%Y%%m%%d`, so the probe returns that instead of a
+ date and the mirrored predicate drops every row the filter keeps.
+ """
+ sql = build_probe_sql("date_format(:value, '%Y%m%d')", ["2026-01-15"], dialect)
+
+ assert "'%Y%m%d'" in sql
+ assert "%%" not in sql
+
+
+def test_the_probe_select_is_unchanged_on_a_dialect_that_does_not_double() -> None:
+ """
+ Pins the no-dialect path, which is also the blind spot: the default dialect
+ does not double percent signs, so no assertion made through it can see the
+ bug the two cases above cover.
+ """
+ assert (
+ build_probe_sql("date_format(:value, '%Y%m%d')", ["2026-01-15"])
+ == "SELECT date_format('2026-01-15', '%Y%m%d') AS v0"
+ )
+
+
+def test_a_raw_probe_value_is_substituted_literally() -> None:
+ r"""
+ `RawProbeValue.sql` is rendered from a filter value, so it reaches
+ `parse_skeleton` as the *replacement* for `:value`. Read as a replacement
+ template, a backslash in it is an escape: `array('a\nb')` -- which is how a
+ dialect renders the two characters `\` and `n` -- would become a real
+ newline, so the engine is asked about a different array than the predicate
+ compares and the mirror can exclude rows the filter keeps.
+ """
+ sql = build_probe_sql("toYYYYMM(:value)", [RawProbeValue(r"array('a\nb')")])
+
+ assert sql == r"SELECT toYYYYMM(array('a\nb')) AS v0"
+
+
+def test_a_raw_probe_value_does_not_re_inject_the_placeholder() -> None:
+ r"""
+ `\g<0>` in a replacement template expands to the whole match, which would
+ put `:value` back into the probe -- an unbound parameter the engine refuses.
+ """
+ sql = build_probe_sql("toYYYYMM(:value)", [RawProbeValue(r"'a\g<0>b'")])
+
+ assert sql == r"SELECT toYYYYMM('a\g<0>b') AS v0"
+ assert ":value" not in sql
+
+
+def test_a_raw_probe_value_with_a_group_reference_does_not_raise() -> None:
+ r"""
+ `\1` is an invalid group reference for this pattern, so as a replacement
+ template it raised `re.PatternError` rather than probing anything.
+ """
+ sql = build_probe_sql("toYYYYMM(:value)", [RawProbeValue(r"'a\1b'")])
+
+ assert sql == r"SELECT toYYYYMM('a\1b') AS v0"
+
+
+def test_a_probed_literal_keeps_its_percent_sign(app: Flask) -> None:
+ """
+ The preview panel renders probed values through the same dialect, so a
+ value that merely contains a `%` would be shown doubled.
+ """
+ database = Database(database_name="pct_db", sqlalchemy_uri="postgresql://h/d")
+
+ with app.app_context():
+ assert _render_literal(database, "100%") == "'100%'"
+
+
+def test_the_probe_reads_each_cell_without_row_wide_dtype_coercion(
+ app: Flask,
+) -> None:
+ """
+ A row is a Series, so it carries one dtype across every probe column: a row
+ mixing an exact int64 with a float unifies to float64 and an integer
+ partition key above 2^53 comes back rounded. The mirror then asks for a key
+ the warehouse does not hold, and the row the filter matched is dropped.
+ """
+ database = _database_returning_frame(
+ pd.DataFrame({"v0": [9007199254740993], "v1": [1.5]})
+ )
+
+ with app.app_context():
+ probed = evaluate_transform(
+ database, None, None, "CAST(:value AS NUMERIC)", ["9007199254740993", "1.5"]
+ )
+
+ assert probed == [9007199254740993, 1.5]
+
+
+def test_evaluate_transform_pins_catalog_and_schema(app: Flask) -> None:
+ """
+ The probe runs in a different session from the chart query; pinning the
+ catalog and schema keeps session settings as close as the pool allows.
+ """
+ database = _database_returning([1])
+
+ with app.app_context():
+ evaluate_transform(database, "prod", "analytics", "lower(:value)", ["x"])
+
+ kwargs = _probe(database).call_args.kwargs
+ assert kwargs["catalog"] == "prod"
+ assert kwargs["schema"] == "analytics"
+
+
+def test_evaluate_transform_fails_open_when_the_probe_raises(app: Flask) -> None:
+ """A wedged engine must not break the chart — it just stops pruning."""
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ side_effect=RuntimeError("connection reset")
+ )
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, "lower(:value)", ["x"]) is None
+
+
+def test_evaluate_transform_fails_open_on_an_empty_result(app: Flask) -> None:
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ return_value=pd.DataFrame()
+ )
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, "lower(:value)", ["x"]) is None
+
+
+def test_evaluate_transform_returns_none_for_no_values(app: Flask) -> None:
+ database = _database_returning([])
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, "lower(:value)", []) is None
+
+ _probe(database).assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "transform",
+ [
+ "(SELECT password FROM ab_user LIMIT 1) || :value",
+ "lower(:value) UNION ALL SELECT password FROM ab_user",
+ "lower(:value); DROP TABLE ab_user",
+ "password || :value FROM ab_user",
+ "lower(:value) FROM ab_user WHERE 1 = 1",
+ ],
+ ids=[
+ "subquery",
+ "set-operation",
+ "multi-statement",
+ "bare-from",
+ "from-and-where",
+ ],
+)
+def test_a_transform_that_is_not_a_storable_expression_never_runs(
+ app: Flask, transform: str
+) -> None:
+ """
+ The probe is where a transform stops being text and becomes SQL.
+
+ `build_probe_sql` binds `:value` and splices the rest in verbatim, so a
+ transform that was never a single harmless expression is arbitrary SQL
+ against the dataset's database -- read back out of the emitted predicate
+ by anyone who can open "View query". The write-side gates refuse these,
+ but they can only speak for rows written after they existed, so the last
+ word belongs here.
+ """
+ database = _database_returning(["irrelevant"])
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, transform, ["us"]) is None
+
+ _probe(database).assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "transform, unfinished",
+ [
+ ("unix_timestamp(:value", True),
+ ("unix_timestamp(:value))", True),
+ ("unix_timestamp(:value) +", True),
+ ("unix_timestamp(:value)", False),
+ ("unix_timestamp(:value); DROP TABLE ab_user", False),
+ ("unix_timestamp(:value) UNION ALL SELECT password FROM ab_user", False),
+ ("password || :value FROM ab_user", False),
+ ],
+)
+def test_is_unfinished_separates_not_sql_yet_from_the_wrong_sql(
+ transform: str, unfinished: bool
+) -> None:
+ """
+ The two deserve opposite treatment -- a half-typed transform is stored and
+ parked inactive, the wrong SQL is refused -- and neither `is_parseable` nor
+ parsing as a single statement tells them apart, because the multi-statement
+ form fails both exactly as unfinished text does. Parsing as a script does.
+ """
+ assert is_unfinished(transform, "hive") is unfinished
+
+
+def test_a_transform_smuggling_its_own_from_clause_is_refused(app: Flask) -> None:
+ """
+ The hole this gate was added for.
+
+ `is_parseable` counts only the projection, so `password || :value FROM
+ ab_user` reads as a single select expression and passed every write-side
+ gate -- including with `ALLOW_ADHOC_SUBQUERY` off, since a top-level FROM
+ is not a sub-query. `build_probe_sql` then emitted `SELECT password || 'us'
+ AS v0 FROM ab_user`, where its own alias is read as a table alias on the
+ FROM clause the transform brought with it: valid SQL, one row, and the
+ secret handed back through the predicate the preview panel renders.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ transform = "password || :value FROM ab_user"
+
+ assert is_parseable(transform, "sqlite") is True
+ assert is_bare_expression(transform, "sqlite") is False
+
+ with app.app_context():
+ reason = stored_expression_error(database, None, None, transform)
+ assert reason is not None
+
+ blocking = _blocking(validate_transform(transform, "sqlite"))
+ assert len(blocking) == 1
+ assert "single SQL expression" in str(blocking[0].message)
+ assert is_transform_active(transform, "sqlite") is False
+
+
+def test_a_subquery_transform_is_refused_even_with_adhoc_subquery_enabled(
+ app: Flask,
+) -> None:
+ """
+ `validate_adhoc_subquery` admits a sub-query under `ALLOW_ADHOC_SUBQUERY`
+ and returns RLS-rewritten SQL -- which this path has no way to propagate,
+ because `build_probe_sql` splices the original transform text. So the probe
+ ran a sub-query with no row-level-security predicates at all and reported
+ the hidden row in `emitted_predicate`. A transform is a scalar function of
+ `:value`, so refusing the sub-query outright is both correct and what makes
+ the missing RLS rewrite moot.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ transform = "(SELECT secret FROM vault LIMIT 1) || :value"
+
+ with app.app_context():
+ app.config["DEFAULT_FEATURE_FLAGS"]["ALLOW_ADHOC_SUBQUERY"] = True
+ try:
+ reason = stored_expression_error(database, None, None, transform)
+ finally:
+ del app.config["DEFAULT_FEATURE_FLAGS"]["ALLOW_ADHOC_SUBQUERY"]
+
+ assert reason is not None
+ assert "sub-query" in reason
+
+
+@pytest.mark.parametrize(
+ "comment",
+ ["/*!50000 + (SELECT secret FROM vault LIMIT 1) */", "/*M!50000 + 1 */"],
+)
+def test_an_executable_comment_is_refused_by_every_gate(
+ app: Flask, comment: str
+) -> None:
+ """
+ The one construct that made the shape gates describe a statement the engine
+ would not run.
+
+ sqlglot reads a MySQL executable comment as comment data: the pinned parse
+ below reports no sub-query and no clause, so `stored_expression_error` and
+ `probe_sql_is_evaluable` both passed it, while MySQL and MariaDB execute
+ what is inside. An owner with dataset write and no SQL Lab could put one in
+ a transform, call the preview and read a table back out of
+ `emitted_predicate`, with no RLS on the hidden query.
+
+ Refused on every engine, not only the two that honour it -- hence SQLite
+ here. There is no legitimate transform carrying one, and a per-engine gate
+ would store on Postgres what detonates after the dataset is re-pointed.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ transform = f"(:value {comment})"
+
+ # The premise: no parse-tree gate can see it.
+ statement = SQLStatement(f"SELECT (1 {comment}) AS v0", "mysql")
+ assert statement.has_subquery() is False
+ assert statement.get_clause_names() == set()
+
+ with app.app_context():
+ assert stored_expression_error(database, None, None, transform) is not None
+
+ blocking = [
+ issue for issue in validate_transform(transform, "mysql") if issue.blocking
+ ]
+ assert len(blocking) == 1
+ assert "executable comment" in str(blocking[0].message)
+
+
+def test_an_executable_comment_stops_the_probe_before_the_engine(app: Flask) -> None:
+ """
+ The gate above is the save path. This is the row an earlier release stored:
+ `_probe` consults `stored_expression_error` on every call, so a transform
+ already in the metadata database never reaches `get_df`.
+ """
+ database = _database_returning(["x"])
+ transform = "(:value /*!50000 + (SELECT secret FROM vault LIMIT 1) */)"
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, transform, ["US"]) is None
+
+ assert _probe(database).call_count == 0
+
+
+def test_a_unicode_escaped_identifier_is_refused_by_every_gate(app: Flask) -> None:
+ """
+ The second construct that made the gates reason about a name the engine
+ does not use. sqlglot reports `U&"\\0071uery_to_xml"` as an anonymous
+ function literally called `\\0071uery_to_xml`, so the function denylist --
+ which matches on the reported name -- never sees `query_to_xml`, while
+ PostgreSQL decodes the escape and runs it. An owner with dataset write and
+ no SQL Lab could read rows outside their RLS scope back out of
+ `emitted_predicate`.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="postgresql://u@h/d")
+ transform = "CAST(U&\"\\0071uery_to_xml\"(:value, false, true, '') AS TEXT)"
+
+ # The premise: the denylist is matching the wrong name.
+ statement = SQLStatement(
+ "SELECT CAST(U&\"\\0071uery_to_xml\"('x', false, true, '') AS TEXT) AS v0",
+ "postgresql",
+ )
+ assert statement.get_disallowed_functions({"query_to_xml"}) == set()
+
+ with app.app_context():
+ assert stored_expression_error(database, None, None, transform) is not None
+
+ blocking = [
+ issue for issue in validate_transform(transform, "postgresql") if issue.blocking
+ ]
+ assert len(blocking) == 1
+ assert "escape sequence" in str(blocking[0].message)
+
+
+def test_a_unicode_escaped_identifier_stops_the_probe_before_the_engine(
+ app: Flask,
+) -> None:
+ """The row an earlier release stored, as for the executable comment."""
+ database = _database_returning(["x"])
+ transform = "U&\"\\0071uery_to_xml\"(:value, false, true, '') || ''"
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, transform, ["US"]) is None
+
+ assert _probe(database).call_count == 0
+
+
+def test_an_ordinary_quoted_identifier_is_still_allowed(app: Flask) -> None:
+ """
+ Only the escape prefix is refused. A plainly quoted identifier names what
+ it says, so the denylist sees the real name and rejecting it would cost an
+ owner a transform that works.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="postgresql://u@h/d")
+
+ with app.app_context():
+ assert (
+ stored_expression_error(database, None, None, 'lower("Mixed Case")') is None
+ )
+
+
+def test_the_escape_gate_reads_raw_text_and_says_so(app: Flask) -> None:
+ """
+ The prefix is refused wherever it appears, including inside a string
+ literal -- the same trade the executable-comment gate makes, and for the
+ same reason: a gate whose whole job is to fire before the parse cannot ask
+ the parse whether the text is quoted. `concat(:value, 'u&"x"')` is refused,
+ which costs an owner nothing anyone writes.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="postgresql://u@h/d")
+
+ with app.app_context():
+ assert (
+ stored_expression_error(database, None, None, "concat(:value, 'u&\"x\"')")
+ is not None
+ )
+
+
+def test_a_plain_comment_is_still_allowed_through_the_shape_gates(
+ app: Flask,
+) -> None:
+ """
+ Only the executable form is refused. An ordinary comment is inert on every
+ engine, so rejecting it would cost an owner a transform that works -- and
+ the placeholder gate already covers the case that matters, a `:value` the
+ comment swallows.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+
+ with app.app_context():
+ assert (
+ stored_expression_error(database, None, None, "lower(:value) /* ok */")
+ is None
+ )
+
+
+def test_a_transform_calling_a_disallowed_function_is_refused(app: Flask) -> None:
+ """
+ The probe executes the transform, so the operator's function denylist has
+ to apply to it for the same reason it applies in SQL Lab.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ transform = "version() || :value"
+
+ with app.app_context():
+ original = app.config["DISALLOWED_SQL_FUNCTIONS"]
+ try:
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = {"sqlite": {"version"}}
+ reason = stored_expression_error(database, None, None, transform)
+ assert reason is not None
+ assert "version" in reason
+
+ # Named, rather than echoing the operator's whole denylist back.
+ assert "current_user" not in reason
+
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = {}
+ assert stored_expression_error(database, None, None, transform) is None
+ finally:
+ # Restored: `app.config` is shared, and leaving it emptied silently
+ # disabled this gate for every test that ran afterwards.
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = original
+
+
+@pytest.mark.parametrize(
+ "function",
+ [
+ "database_to_xml",
+ "database_to_xmlschema",
+ "database_to_xml_and_xmlschema",
+ "schema_to_xml",
+ "schema_to_xmlschema",
+ "schema_to_xml_and_xmlschema",
+ "table_to_xml",
+ "table_to_xmlschema",
+ "table_to_xml_and_xmlschema",
+ "query_to_xml",
+ "query_to_xmlschema",
+ "query_to_xml_and_xmlschema",
+ ],
+)
+def test_the_whole_postgres_xml_family_is_denied_by_default(function: str) -> None:
+ """
+ These read tables with no FROM clause and no sub-query, so every gate that
+ reasons about table references is blind to them -- the denylist is the only
+ thing that can refuse them, and it has to name each shape. `schema_to_xml`
+ and three siblings were missing, so a bare scalar call cleared
+ `stored_expression_error` entirely and returned connection-user-readable
+ schema contents through preview.
+
+ Asserted against the shipped default rather than through the gate, because
+ the gap was an incomplete enumeration rather than broken wiring -- and
+ because `app.config` is ambient here, which the behavioural test below
+ handles by setting the denylist itself.
+ """
+ assert function in DISALLOWED_SQL_FUNCTIONS["postgresql"]
+
+
+def test_a_denied_read_capable_function_is_refused_despite_having_no_from(
+ app: Flask,
+) -> None:
+ """
+ The wiring half: a bare scalar call passes the length, single-statement,
+ bare-expression, sub-query and placeholder gates, so the denylist is what
+ has to stop it.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="postgresql://u@h/d")
+ transform = "schema_to_xml('public', true, false, '') || :value"
+
+ with app.app_context():
+ original = app.config["DISALLOWED_SQL_FUNCTIONS"]
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = {"postgresql": {"schema_to_xml"}}
+ try:
+ reason = stored_expression_error(database, None, None, transform)
+ finally:
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = original
+
+ assert reason is not None
+ assert "schema_to_xml" in reason
+
+
+@pytest.mark.parametrize("function", ["ts_rewrite", "ts_stat"])
+def test_the_postgres_full_text_query_functions_are_denied_by_default(
+ function: str,
+) -> None:
+ """
+ `ts_stat('select ...')` and `ts_rewrite(q, 'select ...')` run their *text*
+ argument as a query. The query is a string, so these have the same blind
+ spot the XML family above does: no FROM clause and no sub-query for a
+ table-reference gate to reason about, which leaves the denylist as the only
+ thing that can refuse them.
+ """
+ assert function in DISALLOWED_SQL_FUNCTIONS["postgresql"]
+
+
+@pytest.mark.parametrize(
+ "function",
+ [
+ "getxml",
+ "getxmltype",
+ "newcontext",
+ "newcontextfromhierarchy",
+ # No function argument to inspect at all: the table is named by the
+ # path string handed to the constructor.
+ "dburitype",
+ # The same reader reached through its factory, and the sibling URI
+ # types. Without a case each, deleting these three from `config.py`
+ # left the suite green and reopened the factory path.
+ "geturi",
+ "xdburitype",
+ "httpuritype",
+ ],
+)
+def test_the_oracle_query_running_xml_functions_are_denied_by_default(
+ function: str,
+) -> None:
+ """
+ `DBMS_XMLGEN.GETXML('select secret from vault')` runs its text argument as
+ a query -- the same blind spot as the PostgreSQL families above, on the
+ engine both reviewers named. Listed bare because the package prefix never
+ reaches the matcher: sqlglot parses the call as an anonymous function named
+ `GETXML`, and `get_disallowed_functions` compares against that name.
+ """
+ assert function in DISALLOWED_SQL_FUNCTIONS["oracle"]
+
+
+def test_a_package_qualified_denied_function_is_refused(app: Flask) -> None:
+ """
+ The wiring half for the bare-name listing above: the denylist entry has to
+ match a call written with its package prefix, which is the only way anyone
+ writes these.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="oracle://u@h/d")
+ transform = "DBMS_XMLGEN.GETXML('select secret from vault') || :value"
+
+ with app.app_context():
+ reason = stored_expression_error(database, None, None, transform)
+
+ assert reason is not None
+ assert "getxml" in reason
+
+
+def test_a_denied_query_running_text_function_is_refused(app: Flask) -> None:
+ """
+ The wiring half, and the only thing that proves the *name* matching works
+ for these two: neither is a function sqlglot models, so each reaches
+ `get_disallowed_functions` through its ANONYMOUS branch rather than as a
+ typed node. A denylist entry that only matched modelled functions would
+ pass the enumeration test above and still let these through.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="postgresql://u@h/d")
+ transform = "ts_stat('select 1') || :value"
+
+ with app.app_context():
+ original = app.config["DISALLOWED_SQL_FUNCTIONS"]
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = {"postgresql": {"ts_stat"}}
+ try:
+ reason = stored_expression_error(database, None, None, transform)
+ finally:
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = original
+
+ assert reason is not None
+ assert "ts_stat" in reason
+
+
+def test_the_function_denylist_is_keyed_on_the_engine_spec_name(
+ app: Flask, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """
+ Every other denylist gate in the codebase keys on the engine spec's own
+ name, which is also the name the config documentation tells an operator to
+ write, so this one does too -- a spec covering several SQLAlchemy backends
+ through `engine_aliases` reports the one canonical name under which its
+ entry exists.
+
+ Tested through an *aliased* engine, which is the only way to tell the two
+ names apart. On `sqlite://` the backend and the spec name are both
+ `"sqlite"`, so the assertion held whichever one the gate read, and the test
+ did not check what its name promises. `postgres://` is
+ `PostgresEngineSpec.engine_aliases`, so the URL's backend is `postgres`
+ while the spec -- and the config key an operator writes -- is `postgresql`.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="postgres://u@h/d")
+
+ with app.app_context():
+ # The premise, asserted rather than assumed: if this alias ever goes
+ # away, the test below stops discriminating and should say so here.
+ assert database.backend == "postgres"
+ assert database.db_engine_spec.engine == "postgresql"
+
+ # Denied only under the spec's name. Keyed on `database.backend` the
+ # gate would find no entry and let the call through.
+ #
+ # `monkeypatch`, because `app` is module-scoped: assigning to
+ # `app.config` outlived the test and the next one to read the shipped
+ # defaults -- `test_a_package_qualified_denied_function_is_refused` --
+ # then found this stub and failed under any ordering that put it second.
+ monkeypatch.setitem(
+ app.config, "DISALLOWED_SQL_FUNCTIONS", {"postgresql": {"version"}}
+ )
+ reason = stored_expression_error(database, None, None, "version() || :value")
+
+ assert reason is not None
+ assert "version" in reason
+
+
+def test_the_denylist_key_falls_back_when_the_engine_spec_cannot_load(
+ app: Flask, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """
+ Resolving the engine spec loads the SQLAlchemy dialect entrypoint, which
+ imports the driver package. A deployment missing an optional driver that
+ raises on import rather than being absent must not have its dataset
+ imports turned into hard failures by this gate, so the key falls back to
+ the URL's backend -- the same string for every engine without aliases.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+
+ with (
+ app.app_context(),
+ patch.object(
+ type(database),
+ "db_engine_spec",
+ new_callable=lambda: property(
+ lambda self: (_ for _ in ()).throw(ModuleNotFoundError("no driver"))
+ ),
+ ),
+ ):
+ # `monkeypatch` for the same reason as the test above: `app` is
+ # module-scoped, so a plain assignment leaks into every later test.
+ monkeypatch.setitem(
+ app.config, "DISALLOWED_SQL_FUNCTIONS", {"sqlite": {"version"}}
+ )
+ assert (
+ stored_expression_error(database, None, None, "version() || :value")
+ is not None
+ )
+
+
+# ---------------------------------------------------------------------------
+# §5 — save-time validation, in two tiers
+# ---------------------------------------------------------------------------
+
+
+def _issues(**kwargs: Any) -> list[MappingValidationIssue]:
+ defaults: dict[str, Any] = {
+ "column_names": {"event_time", "dt_epoch", "country", "region_key"},
+ "partition_column": "dt_epoch",
+ "partition_mapped_column": None,
+ "main_dttm_col": "event_time",
+ "transform": "unix_timestamp(:value)",
+ "engine": "hive",
+ }
+ defaults.update(kwargs)
+ return validate_partition_mapping(**defaults)
+
+
+def _blocking(issues: list[MappingValidationIssue]) -> list[MappingValidationIssue]:
+ return [issue for issue in issues if issue.blocking]
+
+
+def _warnings(issues: list[MappingValidationIssue]) -> list[MappingValidationIssue]:
+ return [issue for issue in issues if not issue.blocking]
+
+
+def test_a_well_formed_mapping_raises_nothing() -> None:
+ assert _issues() == []
+
+
+def test_no_partition_column_means_nothing_to_validate() -> None:
+ assert _issues(partition_column=None, transform=None) == []
+
+
+# Tier 1 — blocks the save
+
+
+def test_an_unknown_partition_column_blocks_the_save() -> None:
+ issues = _issues(partition_column="nope")
+ assert len(_blocking(issues)) == 1
+ assert issues[0].field == "partition_column"
+
+
+def test_an_unknown_mapped_column_override_blocks_the_save() -> None:
+ issues = _issues(partition_mapped_column="nope")
+ assert len(_blocking(issues)) == 1
+ assert issues[0].field == "partition_mapped_column"
+
+
+def test_an_explicit_self_mapping_blocks_the_save() -> None:
+ issues = _blocking(_issues(partition_mapped_column="dt_epoch"))
+ assert len(issues) == 1
+ assert "itself" in issues[0].message
+
+
+def test_an_implicit_self_mapping_is_reported_without_blocking() -> None:
+ """
+ Still caught -- checking only the explicit override would miss the case an
+ owner actually hits, where `partition_column` names the column that is
+ *already* the default datetime column -- but Tier 2 rather than Tier 1.
+
+ Blocking it made the state unescapable. `fetch_metadata` could choose the
+ partition column as the default datetime column without anyone asking, and
+ once it had, every later write failed validation -- including one that
+ changed nothing but the description, and including the write that would
+ have set the override that fixes it. The mapping is inert either way, since
+ `resolve_partition_mapping` bails out on it, so reporting is the whole job.
+ """
+ issues = _issues(partition_column="event_time", main_dttm_col="event_time")
+
+ assert _blocking(issues) == []
+ reported = [issue for issue in issues if "points at itself" in str(issue.message)]
+ assert len(reported) == 1
+ assert reported[0].field == "partition_mapped_column"
+ # And it names the two ways out, since neither is obvious from the error.
+ assert "override" in str(reported[0].message)
+ assert "default datetime column" in str(reported[0].message)
+
+
+def test_an_explicit_self_mapping_still_blocks_the_save() -> None:
+ """The counterpart: asked for directly, it is the mistake it looks like."""
+ issues = _blocking(
+ _issues(partition_column="event_time", partition_mapped_column="event_time")
+ )
+ assert len(issues) == 1
+ assert "itself" in str(issues[0].message)
+
+
+def test_an_override_clears_the_implicit_self_mapping_report() -> None:
+ """
+ The way out the message names has to actually work: setting an override
+ away from the partition column leaves no self-mapping at all.
+ """
+ issues = _issues(
+ partition_column="event_time",
+ main_dttm_col="event_time",
+ partition_mapped_column="country",
+ )
+
+ assert _blocking(issues) == []
+ assert not [issue for issue in issues if "points at itself" in str(issue.message)]
+
+
+def test_jinja_in_the_transform_blocks_the_save() -> None:
+ """
+ The probe would render the template in a different context at a different
+ time from the chart query, so v1 disallows it outright.
+ """
+ issues = _blocking(_issues(transform="unix_timestamp('{{ ds }}' , :value)"))
+ assert len(issues) == 1
+ assert "Jinja" in issues[0].message
+
+
+@pytest.mark.parametrize(
+ "transform",
+ [
+ "unix_timestamp(:value) - unix_timestamp()",
+ "date_diff(:value, now())",
+ "CAST(:value AS BIGINT) + rand()",
+ ],
+)
+def test_a_non_deterministic_transform_blocks_the_save(transform: str) -> None:
+ issues = _blocking(_issues(transform=transform))
+ assert len(issues) == 1
+ assert issues[0].field == "partition_value_transform"
+
+
+# Tier 2 — saves, but the mapping stays inactive
+
+
+def test_an_unparseable_transform_saves_with_a_warning() -> None:
+ """The PRD is explicit: a bad transform still saves, it just stays inactive."""
+ issues = _issues(transform="unix_timestamp(:value")
+ assert _blocking(issues) == []
+ assert len(_warnings(issues)) == 1
+
+
+def test_a_parse_failure_names_what_the_parser_choked_on() -> None:
+ """
+ "Could not be parsed" tells an owner nothing they can act on. When the
+ parser hands us a position, pass it along.
+ """
+ issues = _issues(transform="unix_timestamp(:value")
+ message = str(_warnings(issues)[0].message)
+ assert "position" in message
+
+
+def test_a_misspelled_function_is_not_a_parse_error() -> None:
+ """
+ sqlglot parses unknown functions happily -- they are anonymous calls, not
+ syntax errors -- so a typo like this reaches the engine and is reported
+ from there instead. Pinning it so the distinction is not lost.
+ """
+ assert parse_error_detail("unix_timestmp(:value)", "postgresql") is None
+
+
+def test_a_transform_without_the_placeholder_saves_with_a_warning() -> None:
+ issues = _issues(transform="unix_timestamp(event_time)")
+ assert _blocking(issues) == []
+ assert len(_warnings(issues)) == 1
+
+
+def test_a_missing_transform_saves_with_a_warning() -> None:
+ issues = _issues(transform=None)
+ assert _blocking(issues) == []
+ assert len(_warnings(issues)) == 1
+
+
+def test_an_unparseable_transform_skips_the_checks_that_need_a_parse() -> None:
+ """
+ The Jinja and non-determinism checks require a successful parse. When there
+ is nothing to inspect, fall through to a warning rather than reporting a
+ blocking error the owner cannot act on.
+ """
+ issues = _issues(transform="now(:value")
+ assert _blocking(issues) == []
+
+
+# ---------------------------------------------------------------------------
+# §4.2 — the probe cache
+# ---------------------------------------------------------------------------
+
+
+def test_a_repeated_probe_is_served_from_cache(app: Flask) -> None:
+ """
+ Day-aligned ranges ("Last month") repeat constantly across charts, so the
+ hit rate is what keeps the added round trip off the hot path.
+ """
+ database = _database_returning([1767225600])
+
+ with app.app_context():
+ first = evaluate_transform(
+ database, None, None, "unix_timestamp(:value)", ["2026-01-01"]
+ )
+ second = evaluate_transform(
+ database, None, None, "unix_timestamp(:value)", ["2026-01-01"]
+ )
+
+ assert first == second == [1767225600]
+ _probe(database).assert_called_once()
+
+
+def test_the_cache_key_includes_the_transform(app: Flask) -> None:
+ """Editing the transform must not serve the old transform's results."""
+ database = _database_returning([1])
+
+ with app.app_context():
+ evaluate_transform(database, None, None, "unix_timestamp(:value)", ["x"])
+ evaluate_transform(database, None, None, "lower(:value)", ["x"])
+
+ assert _probe(database).call_count == 2
+
+
+def test_the_cache_key_includes_the_values(app: Flask) -> None:
+ database = _database_returning([1])
+
+ with app.app_context():
+ evaluate_transform(database, None, None, "lower(:value)", ["x"])
+ evaluate_transform(database, None, None, "lower(:value)", ["y"])
+
+ assert _probe(database).call_count == 2
+
+
+def test_the_cache_key_includes_the_catalog_and_schema(app: Flask) -> None:
+ """
+ The transform is evaluated against a pinned catalog and schema; the same
+ expression can resolve differently under a different one.
+ """
+ database = _database_returning([1])
+
+ with app.app_context():
+ evaluate_transform(database, "prod", "analytics", "lower(:value)", ["x"])
+ evaluate_transform(database, "prod", "staging", "lower(:value)", ["x"])
+
+ assert _probe(database).call_count == 2
+
+
+def test_a_failed_probe_is_not_cached(app: Flask) -> None:
+ """Caching a failure would keep a transient engine blip pruning-free for a day."""
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ side_effect=[
+ RuntimeError("connection reset"),
+ pd.DataFrame([[42]], columns=["v0"]),
+ ]
+ )
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, "lower(:value)", ["x"]) is None
+ assert evaluate_transform(database, None, None, "lower(:value)", ["x"]) == [42]
+
+
+def test_a_null_monotonic_flag_reads_as_not_declared(app: Flask) -> None:
+ """
+ The column is nullable because the legacy datasource editor writes NULL for
+ any field its payload omits. NULL has to fail closed: ranges stop mirroring
+ rather than mirroring through a transform nobody declared order-preserving.
+ """
+ table = _mapped_table()
+ for column in table.columns:
+ if column.column_name == "event_time":
+ column.partition_transform_is_monotonic = None
+
+ with app.app_context():
+ mapping = resolve_partition_mapping(table)
+
+ assert mapping is not None
+ assert mapping.is_monotonic is False
+ assert not mapping.mirrors(FilterOperator.TEMPORAL_RANGE)
+ assert mapping.mirrors(FilterOperator.EQUALS)
+
+
+def test_a_failed_probe_reports_the_engine_error_when_asked(app: Flask) -> None:
+ """
+ The query path swallows probe failures -- losing pruning beats failing a
+ chart. The editor's preview passes a sink so it can tell the owner why,
+ which is the only way a misspelled function ever gets explained.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ side_effect=RuntimeError("function unix_timestmp does not exist")
+ )
+ errors: list[str] = []
+
+ with app.app_context():
+ assert (
+ evaluate_transform(
+ database, None, None, "unix_timestmp(:value)", ["x"], errors=errors
+ )
+ is None
+ )
+
+ assert errors == ["function unix_timestmp does not exist"]
+
+
+def test_a_failed_probe_stays_silent_without_a_sink(app: Flask) -> None:
+ """The hot path passes nothing and must not pay for the message."""
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ side_effect=RuntimeError("connection reset")
+ )
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, "lower(:value)", ["x"]) is None
+
+
+def test_probe_cache_key_tracks_the_connection(app: Flask) -> None:
+ """
+ The probe asks a specific database to evaluate the transform, so the answer
+ belongs to that connection. ``database.id`` survives an edit to the URI or
+ to ``extra`` (a session timezone, say), which would otherwise serve values
+ computed against the old environment for the whole cache timeout -- and a
+ wrong transformed bound prunes away rows the real filter keeps.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.id = 1
+
+ with app.app_context():
+ before = _probe_cache_key(database, None, None, "lower(:value)", ["US"])
+ database.sqlalchemy_uri = "postgresql://host/db"
+ after_uri = _probe_cache_key(database, None, None, "lower(:value)", ["US"])
+ database.extra = '{"engine_params": {"connect_args": {"timezone": "UTC"}}}'
+ after_extra = _probe_cache_key(database, None, None, "lower(:value)", ["US"])
+
+ assert before != after_uri
+ assert after_uri != after_extra
+
+
+def test_the_probe_cache_ignores_the_caller_without_a_per_user_connection(
+ app: Flask,
+) -> None:
+ """
+ The common case keeps its hit rate.
+
+ The cache exists to keep a synchronous warehouse round trip off the
+ chart-query path, so keying it on the username everywhere would cost every
+ deployment the sharing that makes it worth having -- to fix the two hooks
+ that actually make the connection per-user.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.id = 1
+
+ with app.app_context():
+ with override_user(_user("alice")):
+ as_alice = _probe_cache_key(database, None, None, "lower(:value)", ["US"])
+ with override_user(_user("bob")):
+ as_bob = _probe_cache_key(database, None, None, "lower(:value)", ["US"])
+
+ assert as_alice == as_bob
+
+
+def test_an_impersonating_connection_keys_the_probe_cache_per_caller(
+ app: Flask,
+) -> None:
+ """
+ With impersonation the warehouse runs the probe as the Superset user, so the
+ values the transform returns are computed under *that* user's grants.
+ Shared, the cache handed user B what the transform saw as user A, and the
+ preview echoed it in `emitted_predicate` -- a cross-user read for a
+ transform wrapping any read-capable function the denylist does not name.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.id = 1
+ database.impersonate_user = True
+
+ with app.app_context():
+ with override_user(_user("alice")):
+ as_alice = _probe_cache_key(database, None, None, "lower(:value)", ["US"])
+ alice_verdict = _mirror_verdict_cache_key(
+ database, None, None, "lower(:value)"
+ )
+ with override_user(_user("bob")):
+ as_bob = _probe_cache_key(database, None, None, "lower(:value)", ["US"])
+ bob_verdict = _mirror_verdict_cache_key(
+ database, None, None, "lower(:value)"
+ )
+
+ assert as_alice != as_bob
+ # The verdict too: a function one account may call can be refused to
+ # another, so "this transform evaluates" is not a shared answer either.
+ assert alice_verdict != bob_verdict
+
+
+def test_a_connection_mutator_keys_the_probe_cache_per_caller(app: Flask) -> None:
+ """
+ `DB_CONNECTION_MUTATOR` receives the effective username and may return an
+ entirely different account's URL, so it makes the connection per-user even
+ with `impersonate_user` off -- which is why the gate checks both.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.id = 1
+
+ with app.app_context():
+ app.config["DB_CONNECTION_MUTATOR"] = lambda *args: args[:2]
+ try:
+ with override_user(_user("alice")):
+ as_alice = _probe_cache_key(
+ database, None, None, "lower(:value)", ["US"]
+ )
+ with override_user(_user("bob")):
+ as_bob = _probe_cache_key(database, None, None, "lower(:value)", ["US"])
+ finally:
+ app.config["DB_CONNECTION_MUTATOR"] = None
+
+ assert as_alice != as_bob
+
+
+# ---------------------------------------------------------------------------
+# A probe result the partition column cannot hold
+# ---------------------------------------------------------------------------
+
+
+@pytest.mark.parametrize(
+ "value",
+ [
+ # Even plain ISO: comparing a temporal column against text is an
+ # implicit coercion, and Trino has none while BigQuery coerces only a
+ # canonical literal -- so on an engine Superset has not confirmed, this
+ # declines rather than risking the whole chart.
+ "2026-01-01",
+ "2026-01-01 00:00:00",
+ "2026-01-01T10:08:11",
+ # The unseparated forms, same answer.
+ "20260101",
+ "20260706100811",
+ # Ordinary text, which is the whole point.
+ "us",
+ "US",
+ "",
+ "x20260101",
+ "202601",
+ "1767225600",
+ "1767225600000",
+ ],
+)
+def test_an_undeclared_engine_reads_no_text_as_an_instant(value: str) -> None:
+ """
+ `_PROBE_RESULT_TYPES` admits `str` for a temporal partition column so a day
+ key keeps working. It admitted every string, so `lower(:value)` answering
+ `'us'` passed and the chart failed at the database instead.
+
+ An earlier cut admitted extended ISO everywhere and only asked the spec
+ about the unseparated forms. That is the hole: on Trino a monotonic
+ `date_format(CAST(:value AS TIMESTAMP), '%Y-%m-%d')` probes to
+ `'2026-01-15'`, and `part_date >= '2026-01-15'` errors there rather than
+ losing the pruning.
+ """
+ assert _reads_as_temporal(value, BaseEngineSpec) is False
+
+
+@pytest.mark.parametrize(
+ ("value", "expected"),
+ [
+ # PostgreSQL's date/time input reads both spellings, so the day key
+ # this feature exists for mirrors there.
+ ("2026-01-01", True),
+ ("2026-01-01 00:00:00", True),
+ ("2026-01-01T10:08:11", True),
+ ("2026-01-01 10:08:11.123456", True),
+ ("20260101", True),
+ ("20260706100811", True),
+ # Still not a date, declared formats or not. `strptime` accepts
+ # unpadded fields, so a bare epoch parsed happily as `%Y%m%d%H%M%S`
+ # (1767-02-25 06:00) and was emitted as a date literal -- the exact
+ # bad-literal error this gate exists to stop. The round-trip rejects it.
+ ("1767225600", False),
+ ("1767225600000", False),
+ ("202601", False),
+ ("us", False),
+ ],
+)
+def test_an_engine_that_reads_a_day_key_says_so(value: str, expected: bool) -> None:
+ """
+ Which text reads as an instant is the engine's answer, declared in
+ `temporal_literal_formats`.
+ """
+ assert _reads_as_temporal(value, PostgresEngineSpec) is expected
+
+
+@pytest.mark.parametrize(
+ ("module", "spec_name"),
+ [
+ # Inherit `PostgresBaseEngineSpec`, so declaring the formats there
+ # handed them Postgres's date input. Snowflake's AUTO input does not
+ # take `YYYYMMDD` and reads an all-digit string as epoch seconds.
+ ("snowflake", "SnowflakeEngineSpec"),
+ ("vertica", "VerticaEngineSpec"),
+ ("hana", "HanaEngineSpec"),
+ ("netezza", "NetezzaEngineSpec"),
+ ("hologres", "HologresEngineSpec"),
+ # And the engines the reviewer named as failing the query outright.
+ ("trino", "TrinoEngineSpec"),
+ ("bigquery", "BigQueryEngineSpec"),
+ ],
+)
+def test_a_postgres_relative_does_not_inherit_the_day_key(
+ module: str, spec_name: str
+) -> None:
+ """
+ The declaration lives on the concrete `PostgresEngineSpec` and
+ `RedshiftEngineSpec`, not on the base class seven other specs extend.
+ """
+ spec = getattr(import_module(f"superset.db_engine_specs.{module}"), spec_name)
+ assert spec.temporal_literal_formats == ()
+
+
+def test_redshift_shares_the_postgres_day_key() -> None:
+ """Redshift shares PostgreSQL's date/time input, and names it itself."""
+ from superset.db_engine_specs.redshift import RedshiftEngineSpec
+
+ assert RedshiftEngineSpec.temporal_literal_formats == (
+ PostgresEngineSpec.temporal_literal_formats
+ )
+
+
+def test_the_base_spec_claims_no_day_key_format() -> None:
+ """
+ Default closed: an engine that has not said it reads a day key declines
+ the mirror, which costs the pruning rather than the query.
+ """
+ assert BaseEngineSpec.temporal_literal_formats == ()
+
+
+def test_a_type_mismatch_does_not_poison_the_shared_transform_verdict(
+ app: Flask,
+) -> None:
+ """
+ The decline is about *this* dataset's partition column, and
+ `_mirror_verdict_cache_key` holds no partition column -- only database,
+ catalog, schema and transform.
+
+ Recorded there, a dataset-specific outcome answered for every other dataset
+ sharing the transform: `cast(:value as text)` mirroring happily onto a text
+ key in dataset A was reported `evaluable: false`, and its pruning indicator
+ hidden, because an owner previewed the same transform against a numeric key
+ in dataset B. A probe cache hit on A never rewrites the verdict, so A
+ stayed wrong until the entry expired.
+
+ `evaluate_transform` is patched out here, so it records no verdict of its
+ own and anything left in the cache can only have come from the branch under
+ test. `real_probe_cache` is autouse in this module, so `None` is a real
+ reading rather than what a null cache returns for everything.
+ """
+ table = _mapped_table(transform="cast(:value as text)")
+ mapping = resolve_partition_mapping(table)
+ assert mapping is not None
+
+ with app.app_context():
+ with patch(
+ "superset.connectors.sqla.partition_mapping.evaluate_transform",
+ return_value=["2026-01-01 00:00:00"],
+ ):
+ predicates = build_mirrored_predicates(
+ table, mapping, [(FilterOperator.EQUALS, "2026-01-01")]
+ )
+
+ # `dt_epoch` is a BIGINT and the transform answered with text, so the
+ # mirror is declined -- that part is `probed_value_type_error`'s job.
+ assert predicates == []
+ # And nothing was written to the verdict every other dataset reads.
+ # Before this, the branch above recorded `mirrors=False` here.
+ assert (
+ known_mirror_verdict(table.database, None, None, "cast(:value as text)")
+ is None
+ )
+
+
+def _text_mapped_table(backend: str, transform: str) -> SqlaTable:
+ """
+ A text key mirrored from a text column, on ``backend``.
+
+ The module's own fixture maps a timestamp onto a `BIGINT`, where no probe
+ result can carry a quote or a backslash at all. These tests are about what
+ the probe *answers*, so both ends have to be text.
+ """
+ table = _mapped_table(
+ partition_column="region_key",
+ mapped_column="country",
+ partition_mapped_column="country",
+ transform=transform,
+ monotonic=False,
+ )
+ table.database = Database(database_name="probe_db", sqlalchemy_uri=backend)
+ return table
+
+
+def test_a_probe_result_the_engine_reads_back_differently_is_not_mirrored(
+ app: Flask,
+) -> None:
+ """
+ The other end of the round trip `evaluate_transform` makes on the way in.
+
+ The chart query is compiled with ``literal_binds``, so the probed key is
+ rendered into it by the same renderer and read by the same lexer -- and
+ `concat(:value, chr(92), 'b')` turns the unremarkable input `US` into the key
+ `us\\b`, which Hive reads back as `us` followed by a backspace. Emitted, the
+ mirror asks for a partition no row is in, and because it is ANDed onto the
+ query the chart loses every row the filter keeps rather than losing its
+ pruning.
+
+ No verdict is recorded, for the reason the type mismatch above gives: the
+ probe succeeded, and this is a property of one of its answers.
+ """
+ table = _text_mapped_table(
+ "hive://localhost:10000/default", "concat(lower(:value), chr(92), 'b')"
Review Comment:
A bare `hive://` URL makes `resolve_partition_mapping()` resolve the default PyHive driver, which imports `TCLIService` and fails with `No module named 'thrift'` on CI. That fails `test_a_probe_result_the_engine_reads_back_differently_is_not_mirrored`, `test_one_unspellable_answer_costs_only_its_own_request` and `test_one_unspellable_answer_declines_the_whole_in_list` (same URL at the other two call sites) before they reach their escaping assertions. Could these build the engine spec/dialect without importing the optional driver, so the result-escaping checks actually run?
##########
docs/static/resources/openapi.json:
##########
@@ -24899,6 +25030,120 @@
]
}
},
+ "/api/v1/dataset/{pk}/partition_mapping/preview/": {
+ "post": {
+ "description": "Evaluate a partition value transform at sample values and return the predicate that would be appended to queries. The predicate is built by the same code the query path uses, so the preview cannot drift from what a chart emits. Parse and denylist checks run before anything reaches the engine, so an unparseable transform costs no query.",
+ "parameters": [
+ {
+ "description": "The dataset ID",
+ "in": "path",
+ "name": "pk",
+ "required": true,
+ "schema": {
+ "type": "integer"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PartitionMappingPreviewSchema"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "properties": {
+ "result": {
+ "properties": {
+ "emitted_predicate": {
+ "type": "string"
+ },
+ "error": {
+ "type": "string"
+ },
+ "reason": {
+ "description": "Why the mapping is not valid. Absent when it is. The editor branches on this to decide how to present the failure.",
+ "enum": [
+ "unconfigured",
+ "validation",
+ "parse",
+ "operator",
+ "resolution",
+ "offset",
+ "escaping",
Review Comment:
The preview response's `reason` enum is missing `transform_escaping`, which `_preview_probe` returns with HTTP 200 (and the endpoint docstring lists). A client generated from, or validating against, this spec rejects a legitimate response, e.g. `concat(lower(:value), chr(92), 'b')` on Postgres. Could the spec be regenerated from the current schema (`check-openapi-spec-drift` is also red at this head)?
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/useDebouncedCommit.ts:
##########
@@ -0,0 +1,100 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { debounce } from 'lodash-es';
+import { Constants } from '@superset-ui/core/components';
+
+/**
+ * Local text state that commits upward on a debounce.
+ *
+ * The dataset editor's commit path is asynchronous and snapshot-based: a value
+ * handed to `onChange` travels Field -> Fieldset -> CollectionTable ->
+ * DatasourceEditor -> DatasourceModal and arrives back on the `value` prop
+ * several renders later, and the callback that commits it was built during an
+ * earlier render. An input driven straight off that prop therefore loses any
+ * keystroke that lands while a commit is in flight -- which is why every other
+ * control in the editor types into local state and commits on a debounce, and
+ * why Fieldset's own comment says the editor assumes exactly that. This is
+ * TextControl's contract (src/explore/components/controls/TextControl), minus
+ * the ControlHeader and the number parsing this field does not want.
+ */
+export function useDebouncedCommit(
+ value: string | null | undefined,
+ commit: (next: string) => void,
+ delay: number = Constants.FAST_DEBOUNCE,
+) {
+ const [localValue, setLocalValue] = useState(value ?? '');
+ const [prevValue, setPrevValue] = useState(value);
+ // What was last handed to `commit`. A commit's own echo arrives as a prop
+ // change like any other, and the re-seed below cannot tell the two apart --
+ // so a commit landing while typing continues (a blur or Enter flushes
+ // immediately) used to reset the input to the committed text and drop every
+ // keystroke since. State rather than a ref because the re-seed reads it
+ // during render, which is exactly what a ref is not for.
+ const [lastCommitted, setLastCommitted] = useState<string | undefined>(
+ undefined,
+ );
+
+ // The commit fires from a timer, so the callback is handed in at call time
+ // rather than captured when the debounce was built -- otherwise it would
+ // close over whichever render happened to create it, and fire a stale
+ // callback that writes to a superseded owner.
+ const debouncedCommit = useRef(
+ debounce((next: string, commitFn: (value: string) => void) => {
+ setLastCommitted(next);
+ commitFn(next);
+ }, delay),
+ );
+
+ useEffect(() => () => debouncedCommit.current.cancel(), []);
+
+ const onChange = useCallback(
+ (next: string) => {
+ setLocalValue(next);
+ debouncedCommit.current(next, commit);
+ },
+ [commit],
+ );
+
+ /**
+ * Commit a pending edit now. lodash's `flush` is a no-op when nothing is
+ * pending, so a blur with no edit behind it costs nothing.
+ */
+ const flush = useCallback(() => {
+ debouncedCommit.current.flush();
+ }, []);
+
+ // Re-seed from the prop only when the prop itself changed. Adjusting state
+ // during render is React's documented pattern for this; deriving a display
+ // value without writing it back leaves `localValue` holding superseded text,
+ // so the next render that changes only an unrelated prop -- and so does not
+ // re-enter this branch -- puts the stale value back in the input.
+ if (prevValue !== value) {
+ setPrevValue(value);
+ if (value === lastCommitted) {
Review Comment:
The echo check compares against `lastCommitted === ''`, but `PartitionMappingSection` commits a cleared value upward as `null` (`next || null`), so the echo never matches. Clear an existing transform, press Enter, and keep typing before the prop round-trips: when `value: null` arrives it fails `value === lastCommitted`, `setLocalValue('')` runs, and the characters typed since are dropped. Could null and `''` be normalized the same way before comparing?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,3524 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Writing the value into the probe
+--------------------------------
+The probe evaluates the transform at a *literal*, because it runs with no bound
+parameters at all -- so every value is written into SQL text by the driver's
+literal renderer and read back by the engine's lexer, and the two do not always
+agree. SQLAlchemy's default renderer doubles apostrophes and leaves backslashes
+alone; Hive honours backslash escapes and not doubling, so ``'O''Brien'`` is
+read there as two adjacent literals and ``'x\\''`` ends four characters into a
+value the filter carries whole. A disagreement is either a mirror built from a
+value nobody filtered on -- dropping rows the filter keeps -- or, where the
+value closes its own quote, an expression of the filterer's choosing running in
+the probe.
+
+Which side is right is not knowable from the driver: it is a per-session server
+setting (``standard_conforming_strings``, ``NO_BACKSLASH_ESCAPES``,
+``spark.sql.parser.escapedStringLiterals``), and SQLAlchemy's own view of it is
+only correct on a dialect that has connected. So escaping is not what makes
+this safe. `literal_round_trips` renders the literal and reads it back in the
+engine's own dialect instead, and a value that does not survive the trip is not
+mirrored -- the usual trade, pruning for correctness. `probe_sql_is_evaluable`
+re-reads the finished statement behind it.
+
+The probe's *answers* make the same trip, in the other direction. The chart
+query is compiled with ``literal_binds``, so a probed partition key is rendered
+into its SQL by the same renderer and read by the same lexer -- and
+``concat(:value, chr(92), 'b')`` turns the unremarkable input ``a`` into the key
+``a\\b``, which Hive reads back as ``a`` followed by a backspace. So
+`_predicates_from_probe` asks `literal_round_trips` about each result too, and
+declines the request rather than emitting a predicate no row can satisfy: the
+mirror is ``AND``-ed onto the query, so a mirror that matches nothing costs the
+chart its rows rather than its pruning.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: The opening and closing delimiters of each kind of Jinja block. The probe
+#: would render these in a different context at a different time from the chart
+#: query, so a transform holding one is rejected at save time.
+JINJA_BLOCK_DELIMITERS = (("{{", "}}"), ("{%", "%}"), ("{#", "#}"))
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: A PostgreSQL Unicode-escaped identifier, ``U&"..."``.
+#:
+#: The second construct that breaks the premise above, and in the same way:
+#: ``U&"\\0071uery_to_xml"(...)`` parses as an anonymous function whose name is
+#: the *literal* ``\\0071uery_to_xml``, so the function denylist is matching a
+#: name the engine never sees -- PostgreSQL decodes the escape and runs
+#: ``query_to_xml``, handing a dataset owner rows from outside their RLS scope
+#: through the preview's ``emitted_predicate``.
+#:
+#: Normalizing the escapes and re-checking would be the other repair, and is
+#: worse: it means reimplementing one engine's identifier decoding well enough
+#: to be a security boundary. Refusing the construct is exact, and costs
+#: nothing real -- a transform is a scalar function of ``:value``, and there is
+#: no reason to name a function or column through an escape sequence.
+#:
+#: Refused on every engine, like the executable comment, so a transform stored
+#: on SQLite cannot detonate when the dataset is re-pointed at PostgreSQL. The
+#: ``&`` may be separated from the ``U`` by nothing at all, but whitespace or a
+#: comment between the prefix and the string is not accepted by PostgreSQL
+#: either, so the strict form is the whole surface.
+#:
+#: Matched in raw text, so the prefix is refused inside a string literal too.
+#: That is the same trade the executable comment makes and has the same
+#: justification: a gate whose contract is to fire *before* the parse cannot
+#: ask the parse whether the text was quoted. ``concat(:value, 'u&"x"')`` is
+#: refused, which costs an owner nothing anyone writes.
+UNICODE_ESCAPED_IDENTIFIER_RE = re.compile(r'\bU&"', re.IGNORECASE)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate: a transform such as
+#: ``datediff(day, :value, LOCALTIMESTAMP)`` for a relative partition key is
+#: evaluated once and then keeps emitting yesterday's answer, so the chart
+#: silently drops rows after midnight.
+#:
+#: Matched by SQL function name, so every engine's spelling of "now" has to be
+#: named -- the ANSI four were not enough. Listed rather than delegated to the
+#: engine specs because the risk is the same everywhere and a spec that had not
+#: got round to declaring its own would fail open; a name no engine has is
+#: inert, so over-listing costs nothing.
+NON_DETERMINISTIC_FUNCTIONS = {
+ # ANSI, and the engines that spell it this way.
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "LOCALTIME",
+ "LOCALTIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+ # PostgreSQL. `now()` is statement-stable; these two are not even that.
+ "CLOCK_TIMESTAMP",
+ "STATEMENT_TIMESTAMP",
+ "TIMEOFDAY",
+ # MySQL and MariaDB.
+ "CURDATE",
+ "CURTIME",
+ "SYSDATE",
+ "UTC_DATE",
+ "UTC_TIME",
+ "UTC_TIMESTAMP",
+ "UUID_SHORT",
+ # Oracle.
+ "SYSTIMESTAMP",
+ "SYS_GUID",
+ # SQL Server.
+ "GETDATE",
+ "GETUTCDATE",
+ "SYSDATETIME",
+ "SYSUTCDATETIME",
+ "SYSDATETIMEOFFSET",
+ "NEWID",
+ # BigQuery.
+ "CURRENT_DATETIME",
+ "GENERATE_UUID",
+ # Snowflake.
+ "RANDSTR",
+ "UUID_STRING",
+ # ClickHouse.
+ "NOW64",
+ "RANDCANONICAL",
+ "GENERATEUUIDV4",
+ # H2 and Derby, which the test fixtures use.
+ "RANDOM_UUID",
+}
+
+#: The wall-clock names an engine evaluates with no parentheses at all.
+#:
+#: These parse as *column references*, not functions, so the name-based walk
+#: below cannot see them: `datediff(UTC_DATE, :value)` on MySQL and
+#: `:value - SYSDATE` on Oracle both cleared the gate and froze probe time into
+#: a cached mirror.
+#:
+#: A subset of `NON_DETERMINISTIC_FUNCTIONS` rather than the whole of it,
+#: because refusing a bare name costs an owner a column genuinely called that.
+#: Only the names SQL lets you write without ``()`` are listed -- the datetime
+#: keywords -- so `rand`, `uuid` and `newid`, which always need parentheses and
+#: are plausible column names, stay out.
+BARE_WALL_CLOCK_KEYWORDS = frozenset(
+ {
+ "current_date",
+ "current_time",
+ "current_timestamp",
+ "localtime",
+ "localtimestamp",
+ "utc_date",
+ "utc_time",
+ "utc_timestamp",
+ "sysdate",
+ "systimestamp",
+ }
+)
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+class Unmirrorable:
+ """
+ A filter no mirror can stand in for, and why.
+
+ Returned by `ExploreMixin.mirror_probe_request` for a value the engine
+ compares more coarsely than the filter carries, one it cannot render as a
+ literal, one whose rendered literal the engine would not read back as the
+ same value, one in a time frame the transform would discard, or an ``IN``
+ list with a member of any of those kinds. An object rather than `None`,
+ because `None` is a filter value in its own right.
+
+ The reason rides along because the preview has to explain the decline to
+ the owner, and the two declines want different advice: "the engine compares
+ less of this value than you typed, so map a column it compares in full" is
+ sound guidance for a `DATE` column and actively misleading for an
+ offset-bearing bound on a `TIMESTAMP` one, which already is such a column.
+ Carried rather than re-derived so the preview's explanation cannot come
+ apart from the chart path's decision.
+
+ Lives here rather than beside that method so the preview can read it too:
+ `superset.models.helpers` imports this module, so these can only cross the
+ boundary in this direction. Both callers recognise the same instances -- a
+ preview that answered "valid" for a request the chart path declines is the
+ drift this is here to prevent.
+ """
+
+ __slots__ = ("reason",)
+
+ def __init__(self, reason: str) -> None:
+ self.reason = reason
+
+ def __repr__(self) -> str:
+ return f"<Unmirrorable {self.reason}>"
+
+
+#: The ordinary decline: whatever the mirror cannot be built from, with the
+#: engine's own comparison resolution as the reason an owner can act on.
+UNMIRRORABLE = Unmirrorable("resolution")
+
+#: A value carrying a UTC offset, declined whatever the column's resolution.
+#: A transform such as ``CAST(:value AS TIMESTAMP)`` drops the offset, so even
+#: an engine that compares the whole instant would be probed in the wrong
+#: frame -- which is not something mapping a different column fixes.
+UNMIRRORABLE_OFFSET = Unmirrorable("offset")
+
+#: A value the driver and the engine would not spell the same way, declined
+#: whatever the column's resolution and whatever the operator. Nothing about
+#: the column or the transform fixes it -- see `literal_round_trips` -- so the
+#: advice the resolution reason carries would send an owner after the wrong
+#: thing entirely.
+UNMIRRORABLE_ESCAPING = Unmirrorable("escaping")
+
+
+def is_unmirrorable(value: Any) -> bool:
+ """Whether `mirror_probe_request` declined this request."""
+ return isinstance(value, Unmirrorable)
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def _native_generic_type(
+ column: "TableColumn",
+) -> utils.GenericDataType | None:
+ """
+ What the engine spec makes of ``column``'s declared type.
+
+ `TableColumn.type_generic` answers ``TEMPORAL`` for every column carrying
+ ``is_dttm``, which is the right answer for a chart's time axis and the
+ wrong one for a comparison: an epoch ``BIGINT`` is a number to the engine
+ however it is labelled here. Falls back to the flag where the spec has no
+ answer, so a type Superset cannot resolve is no worse off than before.
+ """
+ try:
+ column_spec = column.db_engine_spec.get_column_spec(
+ column.type, db_extra=column.db_extra
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ column_spec = None
+ if column_spec is not None and column_spec.generic_type is not None:
+ return column_spec.generic_type
+ try:
+ return column.type_generic
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+#: Declared types whose comparison ignores trailing blanks.
+#:
+#: The fixed-width character types, which the SQL standard has compare as
+#: though both sides were padded to the same length -- so ``'US'`` and
+#: ``'US '`` are equal in a ``CHARACTER(3)``, while ``lower()`` of the two is
+#: not. Spelled out rather than matched by prefix because the variable-width
+#: names start with the same letters: ``VARCHAR`` and ``CHARACTER VARYING``
+#: compare the blanks and must not land here.
+PADDED_CHARACTER_TYPES = frozenset(
+ {
+ "CHAR",
+ "NCHAR",
+ # PostgreSQL's own name for ``CHARACTER``, which is what reflection
+ # reports for a ``CHAR(n)`` column there.
+ "BPCHAR",
+ "CHARACTER",
+ "NATIONAL CHAR",
+ "NATIONAL CHARACTER",
+ }
+)
+
+
+def _is_padded_character_type(column: TableColumn) -> bool:
+ """
+ Whether ``column``'s declared type compares without its trailing blanks.
+
+ Read off the declared type rather than the engine spec's resolved one: the
+ specs map ``CHAR`` and ``VARCHAR`` onto the same `sqlalchemy.String`, so
+ the distinction this needs is gone by then. The length suffix is dropped
+ and the name matched against `PADDED_CHARACTER_TYPES`, so an unfamiliar
+ spelling answers ``False`` and the engine-level flag decides as before --
+ this gate adds a decline rather than lifting one. A column with no
+ declared type has nothing to read, and answers the same way.
+ """
+ if not isinstance(column.type, str):
+ return False
+ native = re.sub(r"\s+", " ", column.type.strip().upper())
+ return native.split("(")[0].strip() in PADDED_CHARACTER_TYPES
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ Padding is asked about per column, because it is a property of the *type*
+ rather than of the engine. ``binary_string_comparison`` speaks for an
+ engine's default text comparison, and on PostgreSQL -- which declares it
+ -- a ``CHAR(2)`` still matches a filter for ``'US '`` against a stored
+ ``'US'``, because the standard says a padded character type compares
+ without its trailing blanks. The mirror ``region_key = lower('US ')`` then
+ excludes the row. So a fixed-width character type declines whatever the
+ engine says, and an engine that ignores trailing blanks on its *variable*
+ types says so by not declaring the flag at all (see `RedshiftEngineSpec`).
+
+ The type asked for is the engine spec's reading of the column's declared
+ type, not `TableColumn.type_generic`, which answers ``TEMPORAL`` for
+ anything carrying ``is_dttm``. A ``VARCHAR`` flagged temporal is still text
+ to the engine: on MySQL a filter for ``'2026-01-01T00:00:00'`` matches a
+ stored ``'...t00:00:00'``, while the mirror ``p = hex('...T...')`` excludes
+ it -- and asking the semantic flag skipped the check entirely.
+
+ A type the spec cannot classify declines, which is what the paragraph above
+ promises and what only the exception branch used to do. PostgreSQL's
+ ``citext`` matches no type pattern, so it answered ``None`` -- neither
+ string nor not-string -- and was waved through, which is precisely wrong
+ for a type whose whole purpose is case-insensitive comparison. Declining
+ costs the pruning; admitting it costs rows.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ # Ahead of the generic-type question, which a padded type can lose: the
+ # specs map ``CHARACTER`` onto no generic type at all on some engines, and
+ # a fixed-width character type is a string whether or not Superset can say
+ # so from the name.
+ if _is_padded_character_type(column):
+ return False
+ generic_type = _native_generic_type(column)
+ if generic_type is None:
+ return False
+ if generic_type != utils.GenericDataType.STRING:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_unicode_escaped_identifier(transform: str | None) -> bool:
+ """Whether the transform names something through a ``U&"..."`` escape.
+
+ See `UNICODE_ESCAPED_IDENTIFIER_RE`. Answered on raw text for the same
+ reason as the comment above: the parse reports a name the engine does not
+ use, which is exactly what makes the denylist blind to it.
+ """
+ return (
+ bool(transform)
+ and UNICODE_ESCAPED_IDENTIFIER_RE.search(transform or "") is not None
+ )
+
+
+#: Sequence pseudo-columns, which advance a sequence when they are *read*.
+#:
+#: ``orders_seq.NEXTVAL`` parses as a qualified column reference, not a
+#: function call, so neither `SQLStatement.is_mutating` -- which walks function
+#: names -- nor the function denylist can see it. The probe would then run
+#: ``SELECT orders_seq.NEXTVAL + 1 FROM DUAL`` and advance the sequence, again
+#: on every cache expiry, for a dataset editor holding neither SQL Lab nor a
+#: DML grant. Reading one is a write however the parser classifies it.
+#:
+#: The function spelling (``nextval('s')`` on PostgreSQL) is a different shape
+#: and is caught as a function; this is only about the suffix form.
+SEQUENCE_PSEUDO_COLUMNS = frozenset({"nextval", "currval"})
+
+#: The same thing written as a call.
+#:
+#: Only the suffix form parses as a column; `nextval('s')` on PostgreSQL and
+#: DuckDB, `NEXTVAL(s)`/`SETVAL(s, 1)` on MySQL and MariaDB, and SQL Server's
+#: `NEXT VALUE FOR s` all parse as functions. `SQLStatement.is_mutating` walks
+#: function names on PostgreSQL alone -- deliberately, since the same names are
+#: read-only elsewhere -- so every other engine let these through.
+#:
+#: Matched on the name whatever the engine, because advancing a sequence is a
+#: write wherever it happens and a transform has no reason to call one.
+SEQUENCE_FUNCTIONS = frozenset(
+ {"nextval", "setval", "next_value_for", "nextvalfor", "prevval", "lastval"}
+)
+
+
+def references_sequence(statement: SQLStatement) -> bool:
+ """Whether the statement reads or advances a sequence.
+
+ Both spellings: the pseudo-column suffix, which parses as a column (see
+ `SEQUENCE_PSEUDO_COLUMNS`), and the call, which parses as a function (see
+ `SEQUENCE_FUNCTIONS`).
+
+ Answered on the parse rather than on raw text, because position is what
+ makes it the construct: a column or alias merely *called* ``nextval`` is
+ an ordinary column, and a string literal holding the word is text.
+ """
+ return bool(
+ statement.get_column_names() & SEQUENCE_PSEUDO_COLUMNS
+ or statement.get_disallowed_functions(set(SEQUENCE_FUNCTIONS))
+ )
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """
+ Whether the transform contains a balanced Jinja block.
+
+ A block is an opening delimiter followed, anywhere later, by its closing
+ one -- the same thing ``{{.*?}}`` and its two siblings match under
+ ``re.DOTALL``. Scanned with `str.find` rather than that pattern, because a
+ lazy match retried from every opening delimiter is quadratic in a run of
+ them, and this runs on stored transforms with no length bound of its own:
+ `is_transform_active` reads whatever the column holds. The earliest opening
+ delimiter is the only one worth trying, since any closing delimiter after a
+ later one is also after it.
+ """
+ if not transform:
+ return False
+ for opening, closing in JINJA_BLOCK_DELIMITERS:
+ start = transform.find(opening)
+ if start != -1 and transform.find(closing, start + len(opening)) != -1:
+ return True
+ return False
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+
+ Three spellings have to be looked for, because one name reaches the parse
+ three ways: as a function call, as a zero-argument call a dialect resolves
+ itself, and -- for the datetime keywords -- as a bare word that parses as a
+ column reference.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
Review Comment:
The determinism gate is name-only, so a clock read that arrives as an argument passes: on SQLite `strftime('%s', 'now') || ':' || :value` (or `date('now')`) clears `find_non_deterministic_functions`. The probe result is then cached with the probe-time clock baked into the key, and a later filter on the same value mirrors `p = '<old timestamp>:US'`, which matches no row. Should the gate also refuse `'now'`-style arguments for dialects that spell the clock that way?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,3524 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Writing the value into the probe
+--------------------------------
+The probe evaluates the transform at a *literal*, because it runs with no bound
+parameters at all -- so every value is written into SQL text by the driver's
+literal renderer and read back by the engine's lexer, and the two do not always
+agree. SQLAlchemy's default renderer doubles apostrophes and leaves backslashes
+alone; Hive honours backslash escapes and not doubling, so ``'O''Brien'`` is
+read there as two adjacent literals and ``'x\\''`` ends four characters into a
+value the filter carries whole. A disagreement is either a mirror built from a
+value nobody filtered on -- dropping rows the filter keeps -- or, where the
+value closes its own quote, an expression of the filterer's choosing running in
+the probe.
+
+Which side is right is not knowable from the driver: it is a per-session server
+setting (``standard_conforming_strings``, ``NO_BACKSLASH_ESCAPES``,
+``spark.sql.parser.escapedStringLiterals``), and SQLAlchemy's own view of it is
+only correct on a dialect that has connected. So escaping is not what makes
+this safe. `literal_round_trips` renders the literal and reads it back in the
+engine's own dialect instead, and a value that does not survive the trip is not
+mirrored -- the usual trade, pruning for correctness. `probe_sql_is_evaluable`
+re-reads the finished statement behind it.
+
+The probe's *answers* make the same trip, in the other direction. The chart
+query is compiled with ``literal_binds``, so a probed partition key is rendered
+into its SQL by the same renderer and read by the same lexer -- and
+``concat(:value, chr(92), 'b')`` turns the unremarkable input ``a`` into the key
+``a\\b``, which Hive reads back as ``a`` followed by a backspace. So
+`_predicates_from_probe` asks `literal_round_trips` about each result too, and
+declines the request rather than emitting a predicate no row can satisfy: the
+mirror is ``AND``-ed onto the query, so a mirror that matches nothing costs the
+chart its rows rather than its pruning.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: The opening and closing delimiters of each kind of Jinja block. The probe
+#: would render these in a different context at a different time from the chart
+#: query, so a transform holding one is rejected at save time.
+JINJA_BLOCK_DELIMITERS = (("{{", "}}"), ("{%", "%}"), ("{#", "#}"))
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: A PostgreSQL Unicode-escaped identifier, ``U&"..."``.
+#:
+#: The second construct that breaks the premise above, and in the same way:
+#: ``U&"\\0071uery_to_xml"(...)`` parses as an anonymous function whose name is
+#: the *literal* ``\\0071uery_to_xml``, so the function denylist is matching a
+#: name the engine never sees -- PostgreSQL decodes the escape and runs
+#: ``query_to_xml``, handing a dataset owner rows from outside their RLS scope
+#: through the preview's ``emitted_predicate``.
+#:
+#: Normalizing the escapes and re-checking would be the other repair, and is
+#: worse: it means reimplementing one engine's identifier decoding well enough
+#: to be a security boundary. Refusing the construct is exact, and costs
+#: nothing real -- a transform is a scalar function of ``:value``, and there is
+#: no reason to name a function or column through an escape sequence.
+#:
+#: Refused on every engine, like the executable comment, so a transform stored
+#: on SQLite cannot detonate when the dataset is re-pointed at PostgreSQL. The
+#: ``&`` may be separated from the ``U`` by nothing at all, but whitespace or a
+#: comment between the prefix and the string is not accepted by PostgreSQL
+#: either, so the strict form is the whole surface.
+#:
+#: Matched in raw text, so the prefix is refused inside a string literal too.
+#: That is the same trade the executable comment makes and has the same
+#: justification: a gate whose contract is to fire *before* the parse cannot
+#: ask the parse whether the text was quoted. ``concat(:value, 'u&"x"')`` is
+#: refused, which costs an owner nothing anyone writes.
+UNICODE_ESCAPED_IDENTIFIER_RE = re.compile(r'\bU&"', re.IGNORECASE)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate: a transform such as
+#: ``datediff(day, :value, LOCALTIMESTAMP)`` for a relative partition key is
+#: evaluated once and then keeps emitting yesterday's answer, so the chart
+#: silently drops rows after midnight.
+#:
+#: Matched by SQL function name, so every engine's spelling of "now" has to be
+#: named -- the ANSI four were not enough. Listed rather than delegated to the
+#: engine specs because the risk is the same everywhere and a spec that had not
+#: got round to declaring its own would fail open; a name no engine has is
+#: inert, so over-listing costs nothing.
+NON_DETERMINISTIC_FUNCTIONS = {
+ # ANSI, and the engines that spell it this way.
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "LOCALTIME",
+ "LOCALTIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+ # PostgreSQL. `now()` is statement-stable; these two are not even that.
+ "CLOCK_TIMESTAMP",
+ "STATEMENT_TIMESTAMP",
+ "TIMEOFDAY",
+ # MySQL and MariaDB.
+ "CURDATE",
+ "CURTIME",
+ "SYSDATE",
+ "UTC_DATE",
+ "UTC_TIME",
+ "UTC_TIMESTAMP",
+ "UUID_SHORT",
+ # Oracle.
+ "SYSTIMESTAMP",
+ "SYS_GUID",
+ # SQL Server.
+ "GETDATE",
+ "GETUTCDATE",
+ "SYSDATETIME",
+ "SYSUTCDATETIME",
+ "SYSDATETIMEOFFSET",
+ "NEWID",
+ # BigQuery.
+ "CURRENT_DATETIME",
+ "GENERATE_UUID",
+ # Snowflake.
+ "RANDSTR",
+ "UUID_STRING",
+ # ClickHouse.
+ "NOW64",
+ "RANDCANONICAL",
+ "GENERATEUUIDV4",
+ # H2 and Derby, which the test fixtures use.
+ "RANDOM_UUID",
+}
+
+#: The wall-clock names an engine evaluates with no parentheses at all.
+#:
+#: These parse as *column references*, not functions, so the name-based walk
+#: below cannot see them: `datediff(UTC_DATE, :value)` on MySQL and
+#: `:value - SYSDATE` on Oracle both cleared the gate and froze probe time into
+#: a cached mirror.
+#:
+#: A subset of `NON_DETERMINISTIC_FUNCTIONS` rather than the whole of it,
+#: because refusing a bare name costs an owner a column genuinely called that.
+#: Only the names SQL lets you write without ``()`` are listed -- the datetime
+#: keywords -- so `rand`, `uuid` and `newid`, which always need parentheses and
+#: are plausible column names, stay out.
+BARE_WALL_CLOCK_KEYWORDS = frozenset(
+ {
+ "current_date",
+ "current_time",
+ "current_timestamp",
+ "localtime",
+ "localtimestamp",
+ "utc_date",
+ "utc_time",
+ "utc_timestamp",
+ "sysdate",
+ "systimestamp",
+ }
+)
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+class Unmirrorable:
+ """
+ A filter no mirror can stand in for, and why.
+
+ Returned by `ExploreMixin.mirror_probe_request` for a value the engine
+ compares more coarsely than the filter carries, one it cannot render as a
+ literal, one whose rendered literal the engine would not read back as the
+ same value, one in a time frame the transform would discard, or an ``IN``
+ list with a member of any of those kinds. An object rather than `None`,
+ because `None` is a filter value in its own right.
+
+ The reason rides along because the preview has to explain the decline to
+ the owner, and the two declines want different advice: "the engine compares
+ less of this value than you typed, so map a column it compares in full" is
+ sound guidance for a `DATE` column and actively misleading for an
+ offset-bearing bound on a `TIMESTAMP` one, which already is such a column.
+ Carried rather than re-derived so the preview's explanation cannot come
+ apart from the chart path's decision.
+
+ Lives here rather than beside that method so the preview can read it too:
+ `superset.models.helpers` imports this module, so these can only cross the
+ boundary in this direction. Both callers recognise the same instances -- a
+ preview that answered "valid" for a request the chart path declines is the
+ drift this is here to prevent.
+ """
+
+ __slots__ = ("reason",)
+
+ def __init__(self, reason: str) -> None:
+ self.reason = reason
+
+ def __repr__(self) -> str:
+ return f"<Unmirrorable {self.reason}>"
+
+
+#: The ordinary decline: whatever the mirror cannot be built from, with the
+#: engine's own comparison resolution as the reason an owner can act on.
+UNMIRRORABLE = Unmirrorable("resolution")
+
+#: A value carrying a UTC offset, declined whatever the column's resolution.
+#: A transform such as ``CAST(:value AS TIMESTAMP)`` drops the offset, so even
+#: an engine that compares the whole instant would be probed in the wrong
+#: frame -- which is not something mapping a different column fixes.
+UNMIRRORABLE_OFFSET = Unmirrorable("offset")
+
+#: A value the driver and the engine would not spell the same way, declined
+#: whatever the column's resolution and whatever the operator. Nothing about
+#: the column or the transform fixes it -- see `literal_round_trips` -- so the
+#: advice the resolution reason carries would send an owner after the wrong
+#: thing entirely.
+UNMIRRORABLE_ESCAPING = Unmirrorable("escaping")
+
+
+def is_unmirrorable(value: Any) -> bool:
+ """Whether `mirror_probe_request` declined this request."""
+ return isinstance(value, Unmirrorable)
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def _native_generic_type(
+ column: "TableColumn",
+) -> utils.GenericDataType | None:
+ """
+ What the engine spec makes of ``column``'s declared type.
+
+ `TableColumn.type_generic` answers ``TEMPORAL`` for every column carrying
+ ``is_dttm``, which is the right answer for a chart's time axis and the
+ wrong one for a comparison: an epoch ``BIGINT`` is a number to the engine
+ however it is labelled here. Falls back to the flag where the spec has no
+ answer, so a type Superset cannot resolve is no worse off than before.
+ """
+ try:
+ column_spec = column.db_engine_spec.get_column_spec(
+ column.type, db_extra=column.db_extra
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ column_spec = None
+ if column_spec is not None and column_spec.generic_type is not None:
+ return column_spec.generic_type
+ try:
+ return column.type_generic
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+#: Declared types whose comparison ignores trailing blanks.
+#:
+#: The fixed-width character types, which the SQL standard has compare as
+#: though both sides were padded to the same length -- so ``'US'`` and
+#: ``'US '`` are equal in a ``CHARACTER(3)``, while ``lower()`` of the two is
+#: not. Spelled out rather than matched by prefix because the variable-width
+#: names start with the same letters: ``VARCHAR`` and ``CHARACTER VARYING``
+#: compare the blanks and must not land here.
+PADDED_CHARACTER_TYPES = frozenset(
+ {
+ "CHAR",
+ "NCHAR",
+ # PostgreSQL's own name for ``CHARACTER``, which is what reflection
+ # reports for a ``CHAR(n)`` column there.
+ "BPCHAR",
+ "CHARACTER",
+ "NATIONAL CHAR",
+ "NATIONAL CHARACTER",
+ }
+)
+
+
+def _is_padded_character_type(column: TableColumn) -> bool:
+ """
+ Whether ``column``'s declared type compares without its trailing blanks.
+
+ Read off the declared type rather than the engine spec's resolved one: the
+ specs map ``CHAR`` and ``VARCHAR`` onto the same `sqlalchemy.String`, so
+ the distinction this needs is gone by then. The length suffix is dropped
+ and the name matched against `PADDED_CHARACTER_TYPES`, so an unfamiliar
+ spelling answers ``False`` and the engine-level flag decides as before --
+ this gate adds a decline rather than lifting one. A column with no
+ declared type has nothing to read, and answers the same way.
+ """
+ if not isinstance(column.type, str):
+ return False
+ native = re.sub(r"\s+", " ", column.type.strip().upper())
+ return native.split("(")[0].strip() in PADDED_CHARACTER_TYPES
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ Padding is asked about per column, because it is a property of the *type*
+ rather than of the engine. ``binary_string_comparison`` speaks for an
+ engine's default text comparison, and on PostgreSQL -- which declares it
+ -- a ``CHAR(2)`` still matches a filter for ``'US '`` against a stored
+ ``'US'``, because the standard says a padded character type compares
+ without its trailing blanks. The mirror ``region_key = lower('US ')`` then
+ excludes the row. So a fixed-width character type declines whatever the
+ engine says, and an engine that ignores trailing blanks on its *variable*
+ types says so by not declaring the flag at all (see `RedshiftEngineSpec`).
+
+ The type asked for is the engine spec's reading of the column's declared
+ type, not `TableColumn.type_generic`, which answers ``TEMPORAL`` for
+ anything carrying ``is_dttm``. A ``VARCHAR`` flagged temporal is still text
+ to the engine: on MySQL a filter for ``'2026-01-01T00:00:00'`` matches a
+ stored ``'...t00:00:00'``, while the mirror ``p = hex('...T...')`` excludes
+ it -- and asking the semantic flag skipped the check entirely.
+
+ A type the spec cannot classify declines, which is what the paragraph above
+ promises and what only the exception branch used to do. PostgreSQL's
+ ``citext`` matches no type pattern, so it answered ``None`` -- neither
+ string nor not-string -- and was waved through, which is precisely wrong
+ for a type whose whole purpose is case-insensitive comparison. Declining
+ costs the pruning; admitting it costs rows.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ # Ahead of the generic-type question, which a padded type can lose: the
+ # specs map ``CHARACTER`` onto no generic type at all on some engines, and
+ # a fixed-width character type is a string whether or not Superset can say
+ # so from the name.
+ if _is_padded_character_type(column):
+ return False
+ generic_type = _native_generic_type(column)
+ if generic_type is None:
+ return False
+ if generic_type != utils.GenericDataType.STRING:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_unicode_escaped_identifier(transform: str | None) -> bool:
+ """Whether the transform names something through a ``U&"..."`` escape.
+
+ See `UNICODE_ESCAPED_IDENTIFIER_RE`. Answered on raw text for the same
+ reason as the comment above: the parse reports a name the engine does not
+ use, which is exactly what makes the denylist blind to it.
+ """
+ return (
+ bool(transform)
+ and UNICODE_ESCAPED_IDENTIFIER_RE.search(transform or "") is not None
+ )
+
+
+#: Sequence pseudo-columns, which advance a sequence when they are *read*.
+#:
+#: ``orders_seq.NEXTVAL`` parses as a qualified column reference, not a
+#: function call, so neither `SQLStatement.is_mutating` -- which walks function
+#: names -- nor the function denylist can see it. The probe would then run
+#: ``SELECT orders_seq.NEXTVAL + 1 FROM DUAL`` and advance the sequence, again
+#: on every cache expiry, for a dataset editor holding neither SQL Lab nor a
+#: DML grant. Reading one is a write however the parser classifies it.
+#:
+#: The function spelling (``nextval('s')`` on PostgreSQL) is a different shape
+#: and is caught as a function; this is only about the suffix form.
+SEQUENCE_PSEUDO_COLUMNS = frozenset({"nextval", "currval"})
+
+#: The same thing written as a call.
+#:
+#: Only the suffix form parses as a column; `nextval('s')` on PostgreSQL and
+#: DuckDB, `NEXTVAL(s)`/`SETVAL(s, 1)` on MySQL and MariaDB, and SQL Server's
+#: `NEXT VALUE FOR s` all parse as functions. `SQLStatement.is_mutating` walks
+#: function names on PostgreSQL alone -- deliberately, since the same names are
+#: read-only elsewhere -- so every other engine let these through.
+#:
+#: Matched on the name whatever the engine, because advancing a sequence is a
+#: write wherever it happens and a transform has no reason to call one.
+SEQUENCE_FUNCTIONS = frozenset(
+ {"nextval", "setval", "next_value_for", "nextvalfor", "prevval", "lastval"}
+)
+
+
+def references_sequence(statement: SQLStatement) -> bool:
+ """Whether the statement reads or advances a sequence.
+
+ Both spellings: the pseudo-column suffix, which parses as a column (see
+ `SEQUENCE_PSEUDO_COLUMNS`), and the call, which parses as a function (see
+ `SEQUENCE_FUNCTIONS`).
+
+ Answered on the parse rather than on raw text, because position is what
+ makes it the construct: a column or alias merely *called* ``nextval`` is
+ an ordinary column, and a string literal holding the word is text.
+ """
+ return bool(
+ statement.get_column_names() & SEQUENCE_PSEUDO_COLUMNS
+ or statement.get_disallowed_functions(set(SEQUENCE_FUNCTIONS))
+ )
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """
+ Whether the transform contains a balanced Jinja block.
+
+ A block is an opening delimiter followed, anywhere later, by its closing
+ one -- the same thing ``{{.*?}}`` and its two siblings match under
+ ``re.DOTALL``. Scanned with `str.find` rather than that pattern, because a
+ lazy match retried from every opening delimiter is quadratic in a run of
+ them, and this runs on stored transforms with no length bound of its own:
+ `is_transform_active` reads whatever the column holds. The earliest opening
+ delimiter is the only one worth trying, since any closing delimiter after a
+ later one is also after it.
+ """
+ if not transform:
+ return False
+ for opening, closing in JINJA_BLOCK_DELIMITERS:
+ start = transform.find(opening)
+ if start != -1 and transform.find(closing, start + len(opening)) != -1:
+ return True
+ return False
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+
+ Three spellings have to be looked for, because one name reaches the parse
+ three ways: as a function call, as a zero-argument call a dialect resolves
+ itself, and -- for the datetime keywords -- as a bare word that parses as a
+ column reference.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ # The parenthesis-free spellings, which parse as columns rather than
+ # functions and so are invisible to the walk above. See
+ # `BARE_WALL_CLOCK_KEYWORDS`.
+ found |= {
+ name.upper() for name in BARE_WALL_CLOCK_KEYWORDS & statement.get_column_names()
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error( # noqa: C901
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ And it must be a *read*. Shape is a separate question from effect: a bare
+ scalar expression can still write, so `SQLStatement.is_mutating` is asked
+ too -- the same question SQL Lab and the chart executor ask before letting
+ SQL run. See the gate itself for what that reaches and what it does not.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ # Also ahead of the parse, and for a stronger reason than cost: every gate
+ # below reasons about the parse tree, and this is the one construct that
+ # makes the parse tree describe a different statement from the one the
+ # engine runs. Checked here as well as in `validate_transform` because this
+ # is the door a row written by an earlier release still comes through.
+ if contains_executable_comment(transform):
+ return str(
+ _(
+ "A partition value transform cannot contain a MySQL "
+ "executable comment, which the database executes and every "
+ "validator reads as a comment."
+ )
+ )
+
+ if contains_unicode_escaped_identifier(transform):
+ return str(
+ _(
+ "A partition value transform cannot name anything through a "
+ 'U&"..." escape sequence, which the database decodes and '
+ "every validator reads literally."
+ )
+ )
+
+ # Same door, same reason: the name the denylist below would match is not
+ # the name the engine resolves. See `UNICODE_ESCAPED_IDENTIFIER_RE`.
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The read-only gate, which nothing above implies. The shape gates ask what
+ # the transform *selects*; this asks what evaluating it *does*, and a bare
+ # scalar expression can still write. `nextval(:value)` on PostgreSQL
+ # advances a sequence: one function call, no clause, no sub-query, and not
+ # in the default `DISALLOWED_SQL_FUNCTIONS` either -- so every gate above
+ # passes it and the probe then runs it. `setval` is the same shape, and
+ # `exp.Execute` and the opaque-`exp.Command` forms arrive the same way.
+ #
+ # The large-object writers (`lo_export`, `lowrite`, `lo_from_bytea`, ...)
+ # are caught here too, and the shipped denylist happens to name them as
+ # well -- but that is config an operator can replace, while this is not.
+ #
+ # `is_mutating` is the same question SQL Lab, `get_virtual_table_metadata`
+ # and the chart executor ask before letting SQL run, so a transform is held
+ # to the bar the rest of Superset already sets rather than to one invented
+ # here. Unconditional rather than gated on `Database.allow_dml`: a transform
+ # is a scalar function of `:value` by definition, so there is no legitimate
+ # mutating one, and the probe runs on a cache schedule nobody chose -- a
+ # write would repeat every time the entry expired.
+ #
+ # It bears saying what this does not reach. A user-defined function whose
+ # body writes is a plain call no parser can tell from `lower(:value)`, and
+ # `is_mutating`'s function-name walk is PostgreSQL-only by design, since the
+ # same names are read-only elsewhere. Neither residual is specific to this
+ # feature -- a dataset editor can already have the engine evaluate an
+ # arbitrary expression through a calculated column or a virtual dataset's
+ # SQL -- and closing them means authorizing the preview against the
+ # database, not parsing harder.
+ if statement.is_mutating():
+ return str(
+ _(
+ "A partition value transform cannot change data. It is "
+ "evaluated against the database to check that it mirrors, so "
+ "it has to be a read."
+ )
+ )
+
+ # Not reached by the walk above, which is why it is its own gate: a
+ # sequence pseudo-column is a *column* to the parser and a write to the
+ # engine. See `SEQUENCE_PSEUDO_COLUMNS`.
+ if references_sequence(statement):
+ return str(
+ _(
+ "A partition value transform cannot read a sequence. "
+ "NEXTVAL advances the sequence every time it is evaluated, "
+ "and the transform is evaluated on a cache schedule."
+ )
+ )
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the
+ probe uninspected. Rendering is not what makes that true: a string element
+ is checked by `literal_round_trips` before it is rendered -- the dialect's
+ literal processor and the engine's lexer do not always agree about what a
+ rendered literal says -- and `probe_sql_is_evaluable` re-reads the finished
+ query, which is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def _placeholder_is_bindable(transform: str) -> bool:
+ """
+ Whether SQLAlchemy's ``text()`` can see ``:value`` as a bound parameter.
+
+ `VALUE_PLACEHOLDER_RE` is ``:value\b``, which matches the placeholder in a
+ Postgres cast such as ``:value::bigint``. SQLAlchemy's own bind scan is
+ ``(?<![:\\w$]):([\\w$]+)(?![:\\w$])`` -- note the trailing exclusion -- so a
+ following colon stops it: ``text(":value::bigint")`` reports a parameter
+ named ``valu``, and ``.bindparams(bindparam("value"))`` then raises
+ ``ArgumentError``.
+
+ `_probe` swallows that, so the only symptom was a perfectly valid transform
+ whose mapping silently never pruned, and a preview reporting an engine
+ failure for SQL that was never sent. Every write-side gate passes the
+ transform: it parses, it is a bare expression, and the placeholder *is* in
+ an executable position.
+
+ Answered by attempting the bind itself rather than by pattern-matching
+ ``::`` or reading ``text()``'s private parameter map, so this cannot
+ disagree with what `build_probe_sql` is about to do -- on any dialect, or on
+ a SQLAlchemy whose scan changes.
+ """
+ try:
+ sa.text(transform).bindparams(sa.bindparam("value", value=None))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return False
+ return True
+
+
+def escape_foreign_colons(transform: str) -> str:
+ """
+ ``transform`` with every colon but the ``:value`` placeholder escaped.
+
+ `sqlalchemy.text` reads any ``:word`` as a bind parameter, including one
+ inside a string literal, and an unbound parameter renders as ``NULL``
+ under literal binds rather than raising. So ``:value || \':suffix\'``
+ compiled to ``'us' || 'NULL'``: the mirror asked for a partition value no
+ row holds and the chart dropped rows, with no error for `_probe` to
+ swallow and nothing on screen to say so.
+
+ Escaped rather than refused, because a colon in a literal is ordinary --
+ ``concat(:value, \':\', region)`` builds a composite key -- and the
+ placeholder is the only colon this module means to interpret. `text()`
+ reads ``\\:`` as a literal colon.
+
+ Only the bound path needs this. A `RawProbeValue` or an unbindable
+ placeholder is substituted as text by `parse_skeleton`, which never hands
+ the transform to `text()` at all.
+ """
+ pieces: list[str] = []
+ cursor = 0
+ for match in VALUE_PLACEHOLDER_RE.finditer(transform):
+ pieces.append(transform[cursor : match.start()].replace(":", r"\:"))
+ pieces.append(match.group(0))
+ cursor = match.end()
+ pieces.append(transform[cursor:].replace(":", r"\:"))
+ return "".join(pieces)
+
+
+def literal_round_trips(value: Any, dialect: Dialect | None, engine: str) -> bool:
+ """
+ Whether the engine reads a rendered ``value`` back as that same value.
+
+ The probe runs with no bound parameters, so every value reaches the engine
+ as literal text the driver wrote (see `build_probe_sql`). Whether that text
+ says what the value says is a question about two independent spellings: the
+ driver's escaping, and the engine's lexer. SQLAlchemy's default renderer
+ doubles apostrophes and passes backslashes through; Hive and Spark honour
+ the backslash and not the doubling, so ``'O''Brien'`` is read there as two
+ adjacent literals -- the transform is evaluated at ``OBrien``, and the
+ mirror asks for a partition key that holds none of the rows the filter
+ keeps. The same gap in the other direction lets a value close its own quote
+ and have the rest of it read as SQL.
+
+ Escaping is not the repair. Whether a backslash introduces an escape is a
+ per-session server setting -- ``standard_conforming_strings`` on Postgres,
+ ``NO_BACKSLASH_ESCAPES`` on MySQL, ``escapedStringLiterals`` on Spark -- and
+ nothing in the engine specs exposes it. SQLAlchemy reads it off the server
+ into ``_backslash_escapes`` during ``initialize(connection)``, which the
+ probe's dialect never reaches: `_dialect_for` asks the ``Database`` for a
+ dialect, not for a connection, so Postgres renders ``a\\b`` as
+ ``'a\\\\b'`` and a server with the standard setting reads four
+ characters. An engine-spec flag would have to be defaulted, and either
+ default is wrong for a dozen engines: one leaves the hole open, the other
+ corrupts the probed value.
+
+ So the premise is verified rather than declared, the way
+ `probe_sql_is_evaluable` verifies the finished statement. A value that does
+ not survive the round trip is not mirrored, which costs the query its
+ pruning and nothing else.
+
+ The short-circuit is a proof, not a guess, and it matters for cost: a
+ 200-member ``IN`` list would otherwise parse 200 times on the chart path.
+ If the renderer emitted the value between two quotes and changed nothing in
+ it, and the value carries neither a quote nor a backslash, then no lexer in
+ play can read it as anything but itself. Both exclusions are load-bearing:
+ on Hive ``a\\b`` renders verbatim and reads as ``a`` followed by a
+ backspace.
+
+ :param value: a filter value about to be rendered into the probe
+ :param dialect: the dialect that will render it, as `_dialect_for` reports
+ :param engine: ``database.backend``, whose lexer reads the result
+ :return: whether the two agree about what the literal says
+ """
+ if isinstance(value, RawProbeValue):
+ # Already SQL, with no single value for a parse to be compared against:
+ # its elements are checked before they are rendered, by
+ # `ExploreMixin._array_mirror_probe_value`. A backslash surviving into
+ # the finished text is refused here all the same, as the backstop for a
+ # renderer this module does not own.
+ return "\\" not in value.sql
+ if not isinstance(value, str):
+ # Numbers and instants are not written between delimiters, so there is
+ # no escaping for the two sides to disagree about.
+ return True
+
+ rendered = _compile_literal(sa.literal(value), dialect)
+ if rendered == f"'{value}'" and "'" not in value and "\\" not in value:
+ return True
+
+ try:
+ return (
+ SQLStatement(f"SELECT {rendered}", engine).get_select_literal_value()
+ == value
+ )
+ except SupersetParseError:
+ # A rendered literal the engine's own dialect will not parse is the
+ # strongest form of disagreement there is.
+ return False
+
+
+def value_round_trips(database: Database, value: Any) -> bool:
+ """
+ `literal_round_trips` for a caller holding a database, not a dialect.
+
+ Which renderer and which lexer apply is this module's business, so the two
+ callers outside it -- the chart path's own gate in
+ `ExploreMixin.mirror_probe_request` and the mapping summary Explore reads
+ -- ask in these terms and stay out of it.
+
+ :param database: the database whose driver renders and whose engine reads
+ :param value: a filter value about to be rendered into the probe
+ :return: whether the two agree about what the literal says
+ """
+ return literal_round_trips(value, _dialect_for(database), database.backend)
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text. That is not itself a boundary:
+ the processor's escaping is not always the escaping the engine honours, and
+ a value can close its own quote through the gap. The boundary is
+ `literal_round_trips` on the way in -- which callers must have run, like
+ `stored_expression_error` below -- and `probe_sql_is_evaluable` on the way
+ out.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ bindable = _placeholder_is_bindable(transform)
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ elif bindable:
+ # Every other colon escaped first: `text()` would read one inside a
+ # string literal as a second bind parameter and render it `NULL`.
+ # See `escape_foreign_colons`.
+ clause = sa.text(escape_foreign_colons(transform)).bindparams(
+ sa.bindparam("value", value=value)
+ )
+ rendered = _compile_literal(clause, dialect)
+ else:
+ # `text()` cannot see the placeholder (see
+ # `_placeholder_is_bindable`), so the value is rendered by the
+ # dialect's own literal processor first and substituted as SQL
+ # text. The same two steps in the other order: binding exists to
+ # get the value through that processor, and `_compile_literal`
+ # inlines the result either way, so this is the same string by a
+ # different route -- not a loosening of the "never interpolate a
+ # raw value" rule. `parse_skeleton` substitutes literally, so the
+ # rendered literal arrives here exactly as it was rendered, which
+ # is what makes `literal_round_trips`' verdict on it good for this
+ # branch as much as for the bound one.
+ rendered = parse_skeleton(
+ transform, _compile_literal(sa.literal(value), dialect)
+ )
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Five things have to hold, and all five are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+ * No comment, anywhere. A value that closes its own quote has to hide the
+ text `build_probe_sql` appended after it, and a comment is the only way
+ to do that and still balance the quotes -- so this is what makes the
+ alias check above sufficient rather than merely necessary. Read off the
+ parse rather than the text, so a comment *inside* a literal is data and
+ costs no pruning, and so the question is asked in the engine's own
+ dialect. A transform has no legitimate reason to carry one either; see
+ `EXECUTABLE_COMMENT_RE`.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ # Before the parse, because this gate's whole contract is that what the
+ # parse describes is what the engine will run, and an executable comment is
+ # precisely the text where that stops being true. The transform is already
+ # refused for carrying one; this covers the compiled statement, so no later
+ # change to how values are rendered can reintroduce it behind the gates
+ # below.
+ if contains_executable_comment(sql) or contains_unicode_escaped_identifier(sql):
+ return False
+
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if not isinstance(statement, SQLStatement):
+ # A dialect whose statements this gate cannot take apart -- KQL -- gets
+ # no probe rather than an unchecked one. It never had one: the clause
+ # inspection below is implemented for SQL statements only, and the
+ # alternative to declining here is an `AttributeError` that `_probe`
+ # swallows into the same outcome, less legibly.
+ return False
+ if statement.has_comment():
+ return False
+ if statement.has_subquery():
+ return False
+ if statement.get_clause_names() - {"from"}:
+ return False
+ if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+ """
+ The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+ Parsed rather than string-compared so that the comparison in
+ `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+ not parse answers ``None``, which no statement carrying a FROM can match --
+ the probe then declines, which is the right way for an unreadable engine
+ constant to fail.
+ """
+ if not from_suffix.strip():
+ return None
+ try:
+ return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+ except SupersetParseError:
+ return None
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ # The value side of the premise `probe_sql_is_evaluable` checks on the
+ # finished statement: a value the driver and the engine would spell
+ # differently is not probed at all -- see `literal_round_trips`.
+ #
+ # `ExploreMixin.mirror_probe_request` declines one earlier, with a reason
+ # the preview can explain, and that is the gate an owner sees. This is the
+ # one that cannot be walked around. `_collect_partition_mirror_range`
+ # appends its bounds into the sink without passing through that method at
+ # all, and both paths can hand back a value the gate never saw: on a column
+ # carrying a `python_date_format`, what is probed is
+ # `strftime(that format)` -- text no mapping gate has ever read.
+ #
+ # Above `_run_probe` on purpose. This is a property of one input, not of
+ # the transform, and a verdict recorded here would withdraw the mirror for
+ # every later value of a transform the engine evaluates perfectly well.
+ dialect = _dialect_for(database)
+ if not all(
+ literal_round_trips(value, dialect, database.backend) for value in distinct
+ ):
+ logger.warning(
+ "A filter value is not written the same way by the driver and the "
+ "database, so the partition transform is not probed at it; this "
+ "query will not prune"
+ )
+ return None
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+
+ The verdict is about the *transform*: whether the engine evaluated it at
+ all. A ``NULL`` among the results is not that -- it is this input's answer,
+ and `NULLIF(:value, 0)` returning ``NULL`` for ``n = 0`` says nothing about
+ the same transform on ``n = 2``. Counting it withdrew the promise for the
+ whole transform, and nothing restored it: a *failed* probe is deliberately
+ not cached, so the next chart re-probes and re-records, but a ``NULL`` is a
+ successful probe and *is* cached -- so the false verdict outlived every
+ later hit, and the editor reported a working mapping as not mirroring
+ while the query went on pruning. The per-input skip still happens where it
+ belongs, in the caller's own ``NULL`` guard.
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=values is not None,
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ from_suffix = database.db_engine_spec.select_without_from_suffix
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ from_suffix,
+ )
+ if not probe_sql_is_evaluable(
+ sql, database.backend, len(distinct), from_suffix
+ ):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _execution_identity(database: Database) -> str | None:
+ """
+ Who the warehouse will run the probe as, when that can vary by caller.
+
+ `_probe_cache_key` keys on the `Database` record, which is the *connection*
+ -- not the identity it is opened under. Two hooks make that identity a
+ function of the Superset user instead:
+
+ * ``impersonate_user`` on the database, which hands the effective username
+ to `db_engine_spec.impersonate_user`;
+ * ``DB_CONNECTION_MUTATOR``, which receives the effective username and may
+ return an entirely different account's URL.
+
+ Under either one, a cached probe result computed under user A's grants was
+ served to user B, and the preview echoed it back in ``emitted_predicate``.
+ A transform wrapping a read-capable function the denylist does not name --
+ Oracle's ``DBMS_XMLGEN.GETXML`` is the worked example -- then leaks across
+ users who were never allowed the same rows.
+
+ Returns ``None`` when neither hook is configured, which is the common case
+ and deliberately leaves the key as it was: the cache exists to keep a
+ synchronous warehouse round trip off the chart-query path, and keying every
+ deployment on the username would cost every deployment the hit rate to fix
+ the two that need it.
+
+ The *Superset* username rather than the resolved warehouse account, because
+ it is the input both hooks branch on, and reading it needs no URL parse and
+ puts no credential in the key.
+ """
+ if not (database.impersonate_user or app.config["DB_CONNECTION_MUTATOR"]):
+ return None
+ return get_username()
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _mirror_verdict_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str:
+ """
+ `_probe_cache_key` without the values.
+
+ Whether a transform can be evaluated at all is a property of the transform
+ and the connection, not of the filter that happened to be probing it, so
+ one chart's answer settles the question for the next one.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ # Whether a transform *can* be evaluated is a property of the
+ # transform and the connection -- but under impersonation the
+ # connection is per-user, and a function one account may call can
+ # be refused to another. See `_execution_identity`.
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_verdict:{digest}"
+
+
+def record_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ *,
+ mirrors: bool,
+) -> None:
+ """
+ Remember whether this transform produced a mirror, for the UI to read.
+
+ Advisory only. Nothing in the query path consults it: a probe that failed
+ once is retried on the next chart exactly as it is today, because declining
+ to prune for a whole cache timeout over one transient engine blip is the
+ trade `evaluate_transform` deliberately refuses -- see the comment where it
+ declines to cache a failure.
+
+ What this is for is the *claim*. `is_transform_active` parses the transform
+ and no more, so a transform the database rejects -- a misspelled function
+ is the common case -- is "active", and the editor's banner and Explore's
+ pruning glyph promise a speed-up that never happens. A promise is exactly
+ the thing that may be withheld on one bad answer and restored on a good
+ one, which is why this is a separate entry from the probe's own results
+ rather than a relaxation of that rule.
+
+ Written by `_run_probe`, so the preview endpoint -- which shares the
+ evaluator -- settles the question before the owner has even saved.
+ """
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(
+ _mirror_verdict_cache_key(database, catalog, schema, transform),
+ mirrors,
+ timeout=timeout,
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform verdict", exc_info=True)
+
+
+def known_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> bool | None:
+ """
+ The last verdict `record_mirror_verdict` stored, or `None` if there is none.
+
+ `None` is the honest answer on a cold cache and is deliberately not `False`:
+ reporting a working mapping as broken until something probes it would
+ trade one wrong claim for another. The alternative -- probing from the
+ read side -- would put a warehouse round trip on every Explore and
+ dashboard load, and a failing transform is not cached at all, so it would
+ be a round trip every single time.
+ """
+ try:
+ verdict = cache_manager.cache.get(
+ _mirror_verdict_cache_key(database, catalog, schema, transform)
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return verdict if isinstance(verdict, bool) else None
+
+
+def _compile_literal(element: Any, dialect: Dialect | None) -> str:
+ """
+ Compile with inline literals, undoing the paramstyle's percent doubling.
+
+ Both ``TextClause`` and literal compilation run the dialect's
+ ``post_process_text``, which doubles every ``%`` whenever the identifier
+ preparer asks it to -- true for MySQL and Postgres and for every spec
+ inheriting their paramstyle. That doubling exists so a later DBAPI
+ parameter-interpolation pass can undo it, and the probe has no such pass:
+ it executes with no bound parameters at all. So a transform of
+ ``date_format(:value, '%Y%m%d')`` reaches the warehouse asking for the
+ literal string ``%%Y%%m%%d``, the probe returns that instead of a date, and
+ the mirrored predicate drops every row the filter keeps.
+
+ The same normalization ``Database.compile_sqla_query`` applies for the same
+ reason. ``_double_percents`` is private and not guaranteed on a third-party
+ dialect, hence the ``getattr`` default.
+ """
+ compiled = str(
+ element.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
+ )
+ if dialect is not None and getattr(
+ dialect.identifier_preparer, "_double_percents", False
+ ):
+ compiled = compiled.replace("%%", "%")
+ return compiled
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be *asked* to stand in for itself, and the transform
+ cannot carry Jinja or call a non-deterministic function. Tier 2
+ (``blocking=False``) is everything that merely leaves the mapping inactive
+ -- including a self-mapping nobody asked for, where the partition column
+ merely happens to be the default datetime column.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column == partition_column:
+ # Asked for explicitly, so report it as the mistake it is.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+ elif not partition_mapped_column and main_dttm_col == partition_column:
+ # Resolved onto itself only because the default datetime column happens
+ # to be the partition column -- a state metadata sync could produce
+ # without anyone asking for it. The mapping is inert either way, since
+ # `resolve_partition_mapping` bails out on it, so this reports and lets
+ # the write through: blocking here means a dataset already in the state
+ # can never be saved again, not even to change its description, and
+ # there is no field whose edit would clear the error first.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "%(name)s is both the partition column and the default "
+ "datetime column, so the mapping points at itself and "
+ "stays inactive. Set a mapped column override, or change "
+ "the default datetime column.",
+ name=partition_column,
+ ),
+ blocking=False,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def drop_unmapped_value_transforms(
+ columns: list[dict[str, Any]] | None,
+ *,
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ names_by_id: dict[int, str] | None = None,
+ stored_by_name: dict[str, tuple[str | None, bool]] | None = None,
+) -> list[str]:
+ """
+ Null the value transform on every *incoming* column the mapping cannot mirror.
+
+ The write-side twin of `DatasetDAO.clear_unmapped_partition_transforms`,
+ which answers for the model. A mapping has exactly one mirrored column, so
+ at most one column may carry a transform. One parked on any other column is
+ invisible -- no row but the mapped one renders a transform -- and yet it is
+ stored, and it goes live the moment the mapped column resolves back to it.
+ Clearing an override is enough to do that: a null
+ ``partition_mapped_column`` means "follow ``main_dttm_col``".
+
+ Ungated on the feature flag, unlike its model-level twin, and the difference
+ is what each one discards. That one drops stored configuration, so with the
+ flag off it would be pure loss. This one drops only a value the request in
+ hand is asking to write where the invariant says none may live -- and the
+ flag-off window is precisely when such a value gets parked for later, since
+ the editor hides these fields and the model-level pass declines to run.
+
+ Three writers reach the columns with no effective model-level pass between
+ them, which is why this exists at all: the deprecated
+ ``POST /datasource/save/``, which writes straight through
+ `update_from_object` and so never had one; and a
+ ``PUT /api/v1/dataset/<pk>`` or a dataset import made while the flag is
+ off, where the pass runs on both sides of the write and declines on both.
+
+ Mutates the payload in place, because every caller hands its own request
+ dict straight on to the code that writes it. Returns the names it cleared,
+ so the caller can say so in a log: this is a silent correction to a payload
+ whose author may have meant it.
+
+ A column whose payload mentions neither field is left alone. "Incoming" is
+ the whole scope -- a transform already in storage on a column this request
+ says nothing about is the model-level pass's business, under its own flag.
+
+ The mapped column resolves the way every other reader resolves it,
+ ``partition_mapped_column or main_dttm_col``, and resolves to nothing
+ without a partition column -- in which case no column may hold a transform
+ either.
+
+ :param names_by_id: how to read the name off a payload entry that gives
+ only an ``id``. `DatasetDAO._upsert_columns` identifies an existing
+ column by its primary key and lets ``column_name`` be omitted -- the
+ column keeps the name it has -- so without this an ordinary PUT looked
+ like a payload of nameless columns, none of which matched the mapped
+ one, and every transform in it was dropped. Callers whose writer keys
+ on the name instead (`update_from_object`, the importer) pass nothing.
+ An entry this cannot name is left alone rather than guessed at.
+ :param stored_by_name: ``(transform, is_monotonic)`` as currently stored,
+ per column name, so an *echo* can be told from an introduction. A
+ GET-then-PUT client sends back every column exactly as it received it,
+ so changing the default datetime column away from the mapped one made
+ the payload's unchanged copy of its transform look like a value being
+ parked -- and nulling it destroyed configuration the owner never
+ touched, unrecoverably, with the flag off and the editor's own fields
+ hidden. An unchanged value is the model-level pass's business under its
+ own flag, which is the same line this function's docstring already
+ draws for a column the payload omits. Callers that cannot see storage
+ pass nothing and keep the stricter behaviour.
+ """
+ mapped_column = (
+ (partition_mapped_column or main_dttm_col) if partition_column else None
+ )
+ cleared: list[str] = []
+ for column in columns or []:
+ name = column.get("column_name")
+ if name is None and names_by_id is not None:
+ column_id = column.get("id")
+ if column_id is not None:
+ name = names_by_id.get(column_id)
+ if name is None or name == mapped_column:
+ continue
+ transform = column.get("partition_value_transform")
+ is_monotonic = column.get("partition_transform_is_monotonic")
+ if not transform and not is_monotonic:
+ continue
+ if stored_by_name is not None and name in stored_by_name:
+ stored_transform, stored_monotonic = stored_by_name[name]
+ # A key the entry does not carry is unchanged, not `False`:
+ # `_upsert_columns` writes only the keys present, so echoing the
+ # transform without the declaration is a valid partial update. Read
+ # as a change, it failed the exemption and wrote both fields back
+ # as null -- the loss the exemption exists to prevent.
+ monotonic_echoes = "partition_transform_is_monotonic" not in column or bool(
+ is_monotonic
+ ) == bool(stored_monotonic)
+ transform_echoes = (
+ "partition_value_transform" not in column
+ or transform == stored_transform
+ )
+ if transform_echoes and monotonic_echoes:
+ # An echo, not an introduction. See `stored_by_name`.
+ continue
+ column["partition_value_transform"] = None
+ column["partition_transform_is_monotonic"] = False
+ cleared.append(name)
+ return cleared
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if contains_executable_comment(transform):
+ # Blocking, and checked on raw text next to the Jinja gate because no
+ # parse reports it: sqlglot reads `/*!50000 ... */` as comment data
+ # while MySQL and MariaDB execute it, so every shape gate downstream
+ # inspects a statement the engine will not run. See
+ # `EXECUTABLE_COMMENT_RE`.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform cannot contain a MySQL executable "
+ "comment (/*! ... */ or /*M! ... */). Those are comments "
+ "to every validator and statement text to the database, "
+ "so what would run is not what was checked."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if contains_unicode_escaped_identifier(transform):
+ # Beside the comment gate, for the same reason and on raw text: the
+ # parse reports the escape sequence verbatim as the function's name,
+ # so the function denylist compares against a name PostgreSQL never
+ # uses -- it decodes `U&"\0071uery_to_xml"` and runs `query_to_xml`.
+ # See `UNICODE_ESCAPED_IDENTIFIER_RE`.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ 'A value transform cannot name anything through a U&"..." '
+ "escape sequence. The database decodes it and every "
+ "validator reads it literally, so what would run is not "
+ "what was checked."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_bare_expression(transform, engine):
+ # Blocking, and deliberately placed in `validate_transform` rather than
+ # only at the probe: one issue here closes the PUT, the importer, the
+ # query-time gate through `is_transform_active`, the Explore indicator's
+ # active verdict and the preview endpoint, all of which already consult
+ # this function.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform must be a single SQL expression. It "
+ "cannot carry a FROM, WHERE, GROUP BY or any other clause, "
+ "and it cannot contain a sub-query."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not contains_value_placeholder(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform must contain the :value placeholder, "
+ "which stands for the filter value being mirrored."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not placeholder_is_executable(transform, engine):
+ # Blocking, and for the same reason the shape gate above is: this is
+ # the function the PUT, the importer, `is_transform_active`, the
+ # Explore indicator and the preview all consult, so one issue here
+ # closes every door at once. A placeholder inside a string literal is
+ # a sub-query the engine will run once a filter value closes the quote;
+ # one inside a comment silently eats the probe's own alias.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The :value placeholder must appear where the engine will "
+ "evaluate it. It cannot sit inside a string literal or a "
+ "comment."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if functions := find_non_deterministic_functions(transform, engine):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform calls %(functions)s, whose result "
+ "depends on when and where it runs. The transform is "
+ "evaluated in a separate session and the result is cached, "
+ "so the emitted predicate would freeze a snapshot of that "
+ "moment.",
+ functions=", ".join(sorted(functions)),
+ ),
+ blocking=True,
+ )
+ ]
+
+ return []
+
+
+@lru_cache(maxsize=LRU_CACHE_MAX_SIZE)
+def is_transform_active(transform: str | None, engine: str) -> bool:
+ """
+ Whether Superset will mirror filters through this transform.
+
+ `validate_transform` with the messages discarded, so the Explore indicator
+ cannot advertise a mapping the save path recorded as inactive. Anything
+ cheaper here would be a second, weaker statement of the same rule, free to
+ drift from the one the save path applies.
+
+ Blocking issues count too. Jinja and non-deterministic transforms are
+ rejected on PUT, but `CreateDatasetCommand` and import do not validate the
+ mapping, so one can still reach the database -- and it would never mirror a
+ filter either.
+
+ Memoized because `partition_filter_mapping_summary` is serialized on every
+ Explore and dashboard load and this parses the transform. The key is
+ everything the answer depends on: `validate_transform` reads no session, no
+ locale and no config beyond `SQL_MAX_PARSE_LENGTH`, which bounds the parser
+ rather than changing a verdict within that bound.
+ """
+ return not validate_transform(transform, engine)
+
+
+def preview_partition_mapping( # pylint: disable=too-many-return-statements
+ datasource: SqlaTable,
+ *,
+ mapped_column: str,
+ value_transform: str | None,
+ sample_values: list[str],
+ operator: FilterOperator = FilterOperator.EQUALS,
+ is_monotonic: bool = False,
+ partition_column: str | None = None,
+) -> dict[str, Any]:
+ """
+ Evaluate a candidate mapping and describe the predicate it would emit.
+
+ Shares the evaluator -- and therefore the probe cache -- with the query
+ path, so preview and runtime cannot drift and a previewed transform warms
+ the chart path for free. The predicate itself comes from
+ `build_mirrored_predicates`, the same builder the query path uses, so
+ operator shapes cannot drift either: what the panel shows is what a chart
+ would emit.
+
+ Validation runs first and the engine second: a half-typed transform is by
+ definition unparseable, so most of what a text input produces costs zero
+ queries.
+
+ Every part of the mapping is taken from the request rather than the stored
+ dataset. The editor previews while the owner is still editing -- a mapping
+ that has to be saved before it can be checked is not a preview.
+ """
+ partition_column = partition_column or datasource.partition_column
+ if not partition_column:
+ return {
+ "valid": False,
+ "reason": "unconfigured",
+ "error": _("No partition column is set."),
+ }
+
+ columns_by_name = {str(column.column_name): column for column in datasource.columns}
+ if mapped_column not in columns_by_name:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _("%(name)s is not a column on this dataset.", name=mapped_column),
+ }
+
+ # The bail-out `resolve_partition_mapping` makes at query time, and that
+ # `partition_filter_mapping_summary` repeats for the Explore indicator.
+ # Without it here, preview reports a valid emitted predicate for a mapping
+ # no chart will ever mirror -- the one answer a preview panel must not give.
+ if has_active_advanced_data_type(columns_by_name[mapped_column]):
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _(
+ "%(name)s has an advanced data type, so its filters are "
+ "translated into their own predicate shape and cannot be "
+ "mirrored onto the partition column.",
+ name=mapped_column,
+ ),
+ }
+
+ engine = datasource.database.backend
+ for issue in validate_partition_mapping(
+ column_names=set(columns_by_name),
+ partition_column=str(partition_column),
+ partition_mapped_column=mapped_column,
+ main_dttm_col=datasource.main_dttm_col,
+ transform=value_transform,
+ engine=engine,
+ ):
+ return {
+ "valid": False,
+ # The parse failure is the one an owner sees constantly, and it is
+ # the only one the mockup gives its own headline to.
+ "reason": (
+ "parse"
+ if issue.field == "partition_value_transform"
+ and not is_parseable(value_transform, engine)
+ else "validation"
+ ),
+ "error": str(issue.message),
+ }
+
+ # The policy every other stored expression goes through. The save path
+ # applies it in `UpdateDatasetCommand._validate_partition_mapping`, but
+ # preview evaluates a candidate transform that has not been saved, so
+ # without this the gate had a door around it. See
+ # `stored_expression_error` for what is being kept out and why.
+ if reason := stored_expression_error(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ cast(str, value_transform),
+ ):
+ return {"valid": False, "reason": "validation", "error": reason}
+
+ mapping = PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=mapped_column,
+ value_transform=cast(str, value_transform),
+ is_monotonic=is_monotonic,
+ equality_is_safe=equality_mirrors_safely(
+ columns_by_name[mapped_column], datasource.database.db_engine_spec
+ ),
+ )
+ sample_input = _render_sample_input(
+ datasource, mapped_column, operator, sample_values
+ )
+
+ if operator not in PREVIEWABLE_OPERATORS:
+ # Checked before `mirrors`, which lets `TEMPORAL_RANGE` through when the
+ # transform is declared monotonic -- and the single sample value would
+ # then reach `handle_comparison_filter`, which has no case for a range
+ # and raises. The request schema rejects it too; this keeps the function
+ # honest for any other caller.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is mirrored as a pair of bounds, which "
+ "a preview of a single value cannot describe.",
+ operator=operator.value,
+ ),
+ }
+
+ if operator in MIRRORABLE_ALWAYS and not mapping.equality_is_safe:
+ # Withdrawn by `equality_mirrors_safely`, which no declaration about
+ # ordering can change -- so naming monotonicity here would send the
+ # owner to a checkbox that leaves the answer as it is.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter on this text column is not mirrored: "
+ "the database may treat strings that differ in case or "
+ "trailing spaces as equal, and the mirrored predicate could "
+ "then drop rows the filter keeps.",
+ operator=operator.value,
+ ),
+ }
+
+ if not mapping.mirrors(operator):
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is only mirrored when the transform "
+ "preserves ordering, which this one is not declared to do.",
+ operator=operator.value,
+ ),
+ }
+
+ return _preview_probe(
+ datasource,
+ mapping,
+ columns_by_name[mapped_column],
+ operator,
+ sample_values,
+ sample_input,
+ )
+
+
+def _preview_probe(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ mapped_col: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+ sample_input: str,
+) -> dict[str, Any]:
+ """
+ The half of a preview that needs the warehouse.
+
+ Split out from `preview_partition_mapping` so that the gates which answer
+ from the stored mapping alone stay readable as the single run of guard
+ clauses they are. Everything here has either run a query or decided not to.
+ """
+ value = datasource.mirror_probe_request(
+ operator,
+ _probe_input(datasource, mapped_col, operator, sample_values),
+ mapped_col,
+ )
+ if is_unmirrorable(value):
+ # The same step the chart path applies, so the preview cannot promise a
+ # mirror the query declines -- and it reports the reason that step
+ # recorded rather than deriving one of its own, which is what let the
+ # offset case be explained as a precision loss it is not.
+ if value.reason == "offset":
+ # The transform is fine and the column may well compare the whole
+ # instant; what cannot be mirrored is the frame. Advising a
+ # different column here would send the owner after a column they
+ # already have.
+ return {
+ "valid": False,
+ "reason": "offset",
+ "sample_input": sample_input,
+ "error": _(
+ "A filter value carrying a UTC offset is not mirrored: a "
+ "transform is evaluated in the database's own time frame, "
+ "so the mirrored predicate could ask for a partition the "
+ "matching rows are not in. Write the bound without an "
+ "offset to mirror this filter.",
+ ),
+ }
+ if value.reason == "escaping":
+ # Nothing about the column, the operator or the transform is wrong
+ # here, so none of the advice the other branches carry applies: the
+ # driver and the database disagree about how to write this value
+ # down. Said in terms of the value, which is the only thing the
+ # owner can change.
+ return {
+ "valid": False,
+ "reason": "escaping",
+ "sample_input": sample_input,
+ "error": _(
+ "A filter value containing a quote or a backslash is not "
+ "mirrored on this database: the driver and the database do "
+ "not agree on how to write it into a query, so the "
+ "transform would be evaluated at a value the filter does "
+ "not compare. Filters whose values carry neither still "
+ "mirror.",
+ ),
+ }
+ # The transform is fine and the engine evaluates it, the filter just
+ # carries more of the value than the engine compares on this column --
+ # which is the column's type talking, not a broken expression.
+ return {
+ "valid": False,
+ "reason": "resolution",
+ "sample_input": sample_input,
+ "error": _(
+ "This engine compares less of a %(operator)s value on "
+ "%(column)s than the filter carries, so there is no mirror a "
+ "predicate on the partition column could stand in for. Map a "
+ "column the engine compares in full to mirror this operator.",
+ operator=operator.value,
+ column=mapped_col.column_name,
+ ),
+ }
+ errors: list[str] = []
+ type_errors: list[str] = []
+ escaping_errors: list[str] = []
+ predicates = build_mirrored_predicates(
+ datasource,
+ mapping,
+ [(operator, value)],
+ errors=errors,
+ type_errors=type_errors,
+ escaping_errors=escaping_errors,
+ )
+ if type_errors:
+ # Its own reason, because "the database would not evaluate this" and
+ # "it evaluated and answered with the wrong kind of thing" are
+ # different problems with different fixes, and the owner is the only
+ # one who can tell which transform they meant to write.
+ return {
+ "valid": False,
+ "reason": "type",
+ "sample_input": sample_input,
+ "error": type_errors[0],
+ }
+ if escaping_errors:
+ # Its own reason, and distinct from the `escaping` one above: that is
+ # about the value the chart author typed, this is about what the
+ # transform made of it. Falling through to `engine` below told the owner
+ # the database would not evaluate the transform, when it evaluated it
+ # perfectly and answered with a key that cannot be asked for here.
+ return {
+ "valid": False,
+ "reason": "transform_escaping",
+ "sample_input": sample_input,
+ "error": escaping_errors[0],
+ }
+ if not predicates:
+ return {
+ "valid": False,
+ "reason": "engine",
+ "sample_input": sample_input,
+ "error": (
+ _(
+ "The transform could not be evaluated against the "
+ "database: %(reason)s",
+ reason=errors[0],
+ )
+ if errors
+ else _("The transform could not be evaluated against the database.")
+ ),
+ }
+
+ return {
+ "valid": True,
+ "sample_input": sample_input,
+ "emitted_predicate": _render_predicate(datasource, predicates[0]),
+ }
+
+
+def _probe_input(
+ datasource: SqlaTable,
+ column: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+) -> Any:
+ """
+ The sample values as the query path would bind them.
+
+ The request carries samples as strings, and the probe is keyed on exactly
+ what it is handed, so passing them through raw asks the engine a different
+ question from the one a chart asks. A sample of ``2025`` on a numeric
+ column has to arrive as the integer the chart compares: under a transform
+ of ``typeof(:value)`` the raw string previewed ``'text'`` where the chart
+ emitted ``'integer'``. And because `_probe_cache_key` keys on each value's
+ ``repr``, the two also missed each other's cache entirely -- so the "a
+ previewed transform warms the chart path for free" claim in
+ `preview_partition_mapping`'s docstring did not actually hold.
+
+ Coerced by `filter_values_handler`, the same function the query path uses,
+ rather than by a second implementation of the same rules. Everything the
+ query path then does to the coerced value -- rendering an expression as a
+ literal, widening a bound, declining a comparison the engine resolves too
+ coarsely -- is `ExploreMixin.mirror_probe_request`'s, and the caller hands
+ this result straight to it.
+
+ Ranges are not previewable (see `PREVIEWABLE_OPERATORS`), so the bound
+ conversion `_collect_partition_mirror_range` applies -- a ``datetime`` into
+ the column's stored representation -- has no counterpart here.
+
+ An array column is the exception to `filter_values_handler`: its predicate
+ is built from the raw value, parsed into elements and rendered as the
+ engine's own array literal, so the chart path probes that literal
+ (`ExploreMixin._array_mirror_probe_value`) and this does too. Passing the
+ handled text instead previewed ``length('[1, 2]')`` for a filter whose
+ query probes ``length(array(1, 2))``.
+
+ Answers with a value, or `None` where an engine spec claims array columns
+ without an array literal -- which `mirror_probe_request` then declines, as
+ the chart path declines it. It may also answer with an `Unmirrorable` the
+ array branch raised itself, which `mirror_probe_request` passes through;
+ otherwise the decline is that method's to make, and the caller hands this
+ straight to it.
+ """
+ is_list = operator == FilterOperator.IN
+ column_spec = datasource.db_engine_spec.get_column_spec(native_type=column.type)
+ if (
+ column_spec
+ and column_spec.generic_type == utils.GenericDataType.MULTI_VALUE
+ and operator in MIRRORABLE_ALWAYS
+ ):
+ # `=` and `IN` are the previewable operators the array branch builds a
+ # literal for; a bound on an array column binds the handled value on
+ # the chart path too, so it falls through to the same here.
+ return datasource._array_mirror_probe_value( # noqa: SLF001
+ sample_values if is_list else sample_values[0],
+ operator,
+ datasource.db_engine_spec.get_array_element_type(column.type),
+ datasource.db_engine_spec,
+ )
+ handled = datasource.filter_values_handler(
+ # `list[str]` is not a `list[FilterValue]` to mypy, invariantly, even
+ # though every `str` is a `FilterValue`.
+ values=cast(FilterValues, sample_values if is_list else sample_values[0]),
+ operator=operator,
+ target_generic_type=(
+ column_spec.generic_type if column_spec else utils.GenericDataType.STRING
+ ),
+ target_native_type=column.type,
+ is_list_target=is_list,
+ db_engine_spec=datasource.db_engine_spec,
+ db_extra=datasource.db_extra,
+ )
+ # No `ColumnElement` conversion here: an epoch-milliseconds sample comes back
+ # as engine SQL rather than a value, and `mirror_probe_request` renders it --
+ # the same step, on the same values, as for a chart filter.
+ return handled
+
+
+def _render_sample_input(
+ datasource: SqlaTable,
+ mapped_column: str,
+ operator: FilterOperator,
+ values: list[str],
+) -> str:
+ """
+ The filter being previewed, written the way an owner would read it.
+
+ Display-only -- it is never executed -- but it is still read as SQL, so the
+ column is quoted and the values are rendered by the dialect rather than
+ concatenated raw. A column named ``order date`` would otherwise come out as
+ two bare words.
+ """
+ quoted = datasource.quote_identifier(mapped_column)
+ if operator == FilterOperator.IN:
+ rendered = ", ".join(
+ _render_literal(datasource.database, value) for value in values
+ )
+ return f"{quoted} IN ({rendered})"
+ return (
+ f"{quoted} {operator.value} {_render_literal(datasource.database, values[0])}"
+ )
+
+
+def _render_predicate(datasource: SqlaTable, predicate: ColumnElement[Any]) -> str:
+ """
+ Compile a mirrored predicate to the text a reader would see in View query.
+
+ Every value in it is a probed constant by this point, so ``literal_binds``
+ renders the same literals the chart query carries.
+ """
+ return _compile_literal(predicate, _dialect_for(datasource.database)).replace(
+ "\n", " "
+ )
+
+
+def _render_literal(database: Database, value: Any) -> str:
+ """
+ Render a value the way it appears in the generated SQL.
+
+ Compiled by the dialect rather than formatted by hand. `str()` would render
+ a NULL as the Python repr `None` and leave a date unquoted, neither of which
+ is SQL, and hand-rolled quote-doubling would only ever have been right for
+ strings.
+ """
+ return _compile_literal(sa.literal(value), _dialect_for(database))
+
+
+def build_mirrored_predicates(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ requests: list[tuple[FilterOperator, Any]],
+ *,
+ errors: list[str] | None = None,
+ type_errors: list[str] | None = None,
+ escaping_errors: list[str] | None = None,
+) -> list[ColumnElement[Any]]:
+ """
+ Turn collected ``(operator, value)`` mirror requests into predicates.
+
+ ``requests`` is expected to be deduplicated by the caller. Every value is
+ resolved in a single probe round trip -- one per chart query at most -- then
+ emitted as a literal constant, so "View query" shows the reader an ordinary
+ ``WHERE`` clause rather than an inline expression.
+
+ A strict bound is emitted non-strictly; see `mirror_operator`. That happens
+ here, at the one point where a ``FilterOperator`` becomes SQL, rather than
+ at the collection sites in `ExploreMixin`: the preview endpoint calls this
+ directly, so this is what keeps the predicate the editor shows an owner and
+ the predicate the chart carries from disagreeing.
+
+ :param errors: optional sink; see `evaluate_transform`.
+ :param type_errors: optional sink for a probe result the partition column
+ cannot hold -- see `probed_value_type_error`. Separate from ``errors``
+ because the two say different things to an owner: that one is "the
+ database would not evaluate this", and this one is "it evaluated, and
+ answered with the wrong kind of thing".
+ :param escaping_errors: optional sink for a probe result the driver and the
+ engine would spell differently -- see `_predicates_from_probe`. Its own
+ sink for the same reason: "it evaluated, and answered with something
+ this database cannot be asked about" is a third problem, and the only
+ one of the three whose fix is to stop the transform producing the
+ character.
+ """
+ if not requests:
+ return []
+
+ partition_column = next(
+ (
+ column
+ for column in datasource.columns
+ if column.column_name == mapping.partition_column
+ ),
+ None,
+ )
+ if partition_column is None:
+ return []
+
+ # Flatten every value that needs probing into one list, remembering how many
+ # each request consumed so the results can be handed back out.
+ flat: list[Any] = []
+ spans: list[tuple[FilterOperator, int, int]] = []
+ for operator, value in requests:
+ values = list(value) if operator == FilterOperator.IN else [value]
+ spans.append((operator, len(flat), len(values)))
+ flat.extend(values)
+
+ evaluated = evaluate_transform(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ mapping.value_transform,
+ flat,
+ errors=errors,
+ )
+ if evaluated is None:
+ return []
+
+ if not _bounds_are_ordered(evaluated, spans):
+ return []
+
+ # Declining here is the last chance to decline at all: once these
+ # predicates are in the statement, a value the partition column cannot
+ # hold fails the whole chart rather than its pruning.
+ if reason := probed_value_type_error(partition_column, evaluated):
+ logger.warning(
+ "Partition transform returned a value the partition column cannot "
+ "hold; queries will not prune: %s",
+ reason,
+ )
+ if type_errors is not None:
+ type_errors.append(reason)
+ # Deliberately *not* recorded as a mirror verdict. The transform
+ # evaluated perfectly; what failed is the comparison against this
+ # dataset's partition column -- and `_mirror_verdict_cache_key` is
+ # keyed on database, catalog, schema and transform, with no partition
+ # column in it. Recorded, this dataset-specific outcome answered for
+ # every other dataset sharing the transform: `CAST(:value AS text)`
+ # mirroring happily onto a text key in dataset A was reported
+ # `evaluable: false` -- and its pruning indicator hidden -- because
+ # someone previewed the same transform against a numeric key in
+ # dataset B. A probe cache hit on A never rewrites the verdict, so it
+ # stayed wrong until the entry expired.
+ return []
+
+ sqla_col = datasource.convert_tbl_column_to_sqla_col(partition_column)
+ predicates = _predicates_from_probe(
+ sqla_col,
+ datasource.database,
+ evaluated,
+ spans,
+ escaping_errors=escaping_errors,
+ )
+ if not predicates:
+ return []
+
+ # A comparison against a NULL partition value is NULL, so a row parked in a
+ # NULL partition is dropped by the mirror even when the real filter matches
+ # it -- Hive and Impala's default partition, or a transform that returns
+ # NULL for an input it cannot convert. The mirror only has to be no
+ # narrower than the filter it stands in for, so admitting NULL partitions
+ # keeps those rows. Engines still prune; they read one extra partition.
+ return [sa.or_(sa.and_(*predicates), sqla_col.is_(None))]
+
+
+def _predicates_from_probe(
+ sqla_col: ColumnElement[Any],
+ database: Database,
+ evaluated: list[Any],
+ spans: list[tuple[FilterOperator, int, int]],
+ *,
+ escaping_errors: list[str] | None = None,
+) -> list[ColumnElement[Any]]:
+ """
+ One predicate on the partition column per surviving mirror request.
+
+ A request whose probe answered `None` for any of its values is skipped
+ rather than emitted: `col = NULL` is `NULL`, so it would drop every row the
+ filter keeps. A strict bound is emitted non-strictly; see `mirror_operator`.
+
+ A request whose probe answered with a value the driver and the engine spell
+ differently is skipped for the same reason -- see `literal_round_trips`.
+ `evaluate_transform` asks that question of the probe's *inputs*; the answers
+ are the other end of the same round trip, because the chart query is
+ compiled with ``literal_binds`` and every one of them is rendered into its
+ SQL as a literal too. A transform of ``concat(:value, chr(92), 'b')`` maps
+ the unremarkable input ``a`` to the partition key ``a\\b``, which Hive reads
+ back as ``a`` followed by a backspace: the mirror then asks for a partition
+ no row is in, and because it is ``AND``-ed onto the query the chart loses
+ every row the filter keeps rather than losing its pruning.
+
+ :param escaping_errors: optional sink; see `build_mirrored_predicates`.
+ """
+ # Once for the whole call, not once per value: `_dialect_for` asks the
+ # `Database` for a dialect, and a 200-member `IN` would otherwise ask 200
+ # times. The same reading `evaluate_transform` takes on the way in.
+ dialect = _dialect_for(database)
+
+ predicates: list[ColumnElement[Any]] = []
+ for operator, start, length in spans:
+ chunk = evaluated[start : start + length]
+ if any(value is None for value in chunk):
+ continue
+ if not all(
+ literal_round_trips(value, dialect, database.backend) for value in chunk
+ ):
+ # One member is the whole request's problem, as for `None` above:
+ # mirroring the rest of an `IN` list would be narrower than the
+ # filter. Dropping this request alone is not, which is why the
+ # decline is per request rather than per query -- a range arrives as
+ # two of them, and keeping only the bound that survives the trip is
+ # a mirror wider than the filter, which is all the mirror has to be.
+ logger.warning(
+ "The partition transform answered with a value the driver and "
+ "the database do not write down the same way, so this filter "
+ "is not mirrored; the query will not prune for it"
+ )
+ if escaping_errors is not None:
+ escaping_errors.append(
+ _(
+ "The transform answered with a value the driver and the "
Review Comment:
This new message isn't in `messages.pot`, and the `babel-extract` job and `test_committed_template_matches_a_fresh_extraction` both fail at this head on exactly this string. Could the template (and any changed catalogs) be regenerated with `scripts/translations/babel_update.sh`?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,3524 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Writing the value into the probe
+--------------------------------
+The probe evaluates the transform at a *literal*, because it runs with no bound
+parameters at all -- so every value is written into SQL text by the driver's
+literal renderer and read back by the engine's lexer, and the two do not always
+agree. SQLAlchemy's default renderer doubles apostrophes and leaves backslashes
+alone; Hive honours backslash escapes and not doubling, so ``'O''Brien'`` is
+read there as two adjacent literals and ``'x\\''`` ends four characters into a
+value the filter carries whole. A disagreement is either a mirror built from a
+value nobody filtered on -- dropping rows the filter keeps -- or, where the
+value closes its own quote, an expression of the filterer's choosing running in
+the probe.
+
+Which side is right is not knowable from the driver: it is a per-session server
+setting (``standard_conforming_strings``, ``NO_BACKSLASH_ESCAPES``,
+``spark.sql.parser.escapedStringLiterals``), and SQLAlchemy's own view of it is
+only correct on a dialect that has connected. So escaping is not what makes
+this safe. `literal_round_trips` renders the literal and reads it back in the
+engine's own dialect instead, and a value that does not survive the trip is not
+mirrored -- the usual trade, pruning for correctness. `probe_sql_is_evaluable`
+re-reads the finished statement behind it.
+
+The probe's *answers* make the same trip, in the other direction. The chart
+query is compiled with ``literal_binds``, so a probed partition key is rendered
+into its SQL by the same renderer and read by the same lexer -- and
+``concat(:value, chr(92), 'b')`` turns the unremarkable input ``a`` into the key
+``a\\b``, which Hive reads back as ``a`` followed by a backspace. So
+`_predicates_from_probe` asks `literal_round_trips` about each result too, and
+declines the request rather than emitting a predicate no row can satisfy: the
+mirror is ``AND``-ed onto the query, so a mirror that matches nothing costs the
+chart its rows rather than its pruning.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: The opening and closing delimiters of each kind of Jinja block. The probe
+#: would render these in a different context at a different time from the chart
+#: query, so a transform holding one is rejected at save time.
+JINJA_BLOCK_DELIMITERS = (("{{", "}}"), ("{%", "%}"), ("{#", "#}"))
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: A PostgreSQL Unicode-escaped identifier, ``U&"..."``.
+#:
+#: The second construct that breaks the premise above, and in the same way:
+#: ``U&"\\0071uery_to_xml"(...)`` parses as an anonymous function whose name is
+#: the *literal* ``\\0071uery_to_xml``, so the function denylist is matching a
+#: name the engine never sees -- PostgreSQL decodes the escape and runs
+#: ``query_to_xml``, handing a dataset owner rows from outside their RLS scope
+#: through the preview's ``emitted_predicate``.
+#:
+#: Normalizing the escapes and re-checking would be the other repair, and is
+#: worse: it means reimplementing one engine's identifier decoding well enough
+#: to be a security boundary. Refusing the construct is exact, and costs
+#: nothing real -- a transform is a scalar function of ``:value``, and there is
+#: no reason to name a function or column through an escape sequence.
+#:
+#: Refused on every engine, like the executable comment, so a transform stored
+#: on SQLite cannot detonate when the dataset is re-pointed at PostgreSQL. The
+#: ``&`` may be separated from the ``U`` by nothing at all, but whitespace or a
+#: comment between the prefix and the string is not accepted by PostgreSQL
+#: either, so the strict form is the whole surface.
+#:
+#: Matched in raw text, so the prefix is refused inside a string literal too.
+#: That is the same trade the executable comment makes and has the same
+#: justification: a gate whose contract is to fire *before* the parse cannot
+#: ask the parse whether the text was quoted. ``concat(:value, 'u&"x"')`` is
+#: refused, which costs an owner nothing anyone writes.
+UNICODE_ESCAPED_IDENTIFIER_RE = re.compile(r'\bU&"', re.IGNORECASE)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate: a transform such as
+#: ``datediff(day, :value, LOCALTIMESTAMP)`` for a relative partition key is
+#: evaluated once and then keeps emitting yesterday's answer, so the chart
+#: silently drops rows after midnight.
+#:
+#: Matched by SQL function name, so every engine's spelling of "now" has to be
+#: named -- the ANSI four were not enough. Listed rather than delegated to the
+#: engine specs because the risk is the same everywhere and a spec that had not
+#: got round to declaring its own would fail open; a name no engine has is
+#: inert, so over-listing costs nothing.
+NON_DETERMINISTIC_FUNCTIONS = {
+ # ANSI, and the engines that spell it this way.
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "LOCALTIME",
+ "LOCALTIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+ # PostgreSQL. `now()` is statement-stable; these two are not even that.
+ "CLOCK_TIMESTAMP",
+ "STATEMENT_TIMESTAMP",
+ "TIMEOFDAY",
+ # MySQL and MariaDB.
+ "CURDATE",
+ "CURTIME",
+ "SYSDATE",
+ "UTC_DATE",
+ "UTC_TIME",
+ "UTC_TIMESTAMP",
+ "UUID_SHORT",
+ # Oracle.
+ "SYSTIMESTAMP",
+ "SYS_GUID",
+ # SQL Server.
+ "GETDATE",
+ "GETUTCDATE",
+ "SYSDATETIME",
+ "SYSUTCDATETIME",
+ "SYSDATETIMEOFFSET",
+ "NEWID",
+ # BigQuery.
+ "CURRENT_DATETIME",
+ "GENERATE_UUID",
+ # Snowflake.
+ "RANDSTR",
+ "UUID_STRING",
+ # ClickHouse.
+ "NOW64",
+ "RANDCANONICAL",
+ "GENERATEUUIDV4",
+ # H2 and Derby, which the test fixtures use.
+ "RANDOM_UUID",
+}
+
+#: The wall-clock names an engine evaluates with no parentheses at all.
+#:
+#: These parse as *column references*, not functions, so the name-based walk
+#: below cannot see them: `datediff(UTC_DATE, :value)` on MySQL and
+#: `:value - SYSDATE` on Oracle both cleared the gate and froze probe time into
+#: a cached mirror.
+#:
+#: A subset of `NON_DETERMINISTIC_FUNCTIONS` rather than the whole of it,
+#: because refusing a bare name costs an owner a column genuinely called that.
+#: Only the names SQL lets you write without ``()`` are listed -- the datetime
+#: keywords -- so `rand`, `uuid` and `newid`, which always need parentheses and
+#: are plausible column names, stay out.
+BARE_WALL_CLOCK_KEYWORDS = frozenset(
+ {
+ "current_date",
+ "current_time",
+ "current_timestamp",
+ "localtime",
+ "localtimestamp",
+ "utc_date",
+ "utc_time",
+ "utc_timestamp",
+ "sysdate",
+ "systimestamp",
+ }
+)
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+class Unmirrorable:
+ """
+ A filter no mirror can stand in for, and why.
+
+ Returned by `ExploreMixin.mirror_probe_request` for a value the engine
+ compares more coarsely than the filter carries, one it cannot render as a
+ literal, one whose rendered literal the engine would not read back as the
+ same value, one in a time frame the transform would discard, or an ``IN``
+ list with a member of any of those kinds. An object rather than `None`,
+ because `None` is a filter value in its own right.
+
+ The reason rides along because the preview has to explain the decline to
+ the owner, and the two declines want different advice: "the engine compares
+ less of this value than you typed, so map a column it compares in full" is
+ sound guidance for a `DATE` column and actively misleading for an
+ offset-bearing bound on a `TIMESTAMP` one, which already is such a column.
+ Carried rather than re-derived so the preview's explanation cannot come
+ apart from the chart path's decision.
+
+ Lives here rather than beside that method so the preview can read it too:
+ `superset.models.helpers` imports this module, so these can only cross the
+ boundary in this direction. Both callers recognise the same instances -- a
+ preview that answered "valid" for a request the chart path declines is the
+ drift this is here to prevent.
+ """
+
+ __slots__ = ("reason",)
+
+ def __init__(self, reason: str) -> None:
+ self.reason = reason
+
+ def __repr__(self) -> str:
+ return f"<Unmirrorable {self.reason}>"
+
+
+#: The ordinary decline: whatever the mirror cannot be built from, with the
+#: engine's own comparison resolution as the reason an owner can act on.
+UNMIRRORABLE = Unmirrorable("resolution")
+
+#: A value carrying a UTC offset, declined whatever the column's resolution.
+#: A transform such as ``CAST(:value AS TIMESTAMP)`` drops the offset, so even
+#: an engine that compares the whole instant would be probed in the wrong
+#: frame -- which is not something mapping a different column fixes.
+UNMIRRORABLE_OFFSET = Unmirrorable("offset")
+
+#: A value the driver and the engine would not spell the same way, declined
+#: whatever the column's resolution and whatever the operator. Nothing about
+#: the column or the transform fixes it -- see `literal_round_trips` -- so the
+#: advice the resolution reason carries would send an owner after the wrong
+#: thing entirely.
+UNMIRRORABLE_ESCAPING = Unmirrorable("escaping")
+
+
+def is_unmirrorable(value: Any) -> bool:
+ """Whether `mirror_probe_request` declined this request."""
+ return isinstance(value, Unmirrorable)
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def _native_generic_type(
+ column: "TableColumn",
+) -> utils.GenericDataType | None:
+ """
+ What the engine spec makes of ``column``'s declared type.
+
+ `TableColumn.type_generic` answers ``TEMPORAL`` for every column carrying
+ ``is_dttm``, which is the right answer for a chart's time axis and the
+ wrong one for a comparison: an epoch ``BIGINT`` is a number to the engine
+ however it is labelled here. Falls back to the flag where the spec has no
+ answer, so a type Superset cannot resolve is no worse off than before.
+ """
+ try:
+ column_spec = column.db_engine_spec.get_column_spec(
+ column.type, db_extra=column.db_extra
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ column_spec = None
+ if column_spec is not None and column_spec.generic_type is not None:
+ return column_spec.generic_type
+ try:
+ return column.type_generic
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+#: Declared types whose comparison ignores trailing blanks.
+#:
+#: The fixed-width character types, which the SQL standard has compare as
+#: though both sides were padded to the same length -- so ``'US'`` and
+#: ``'US '`` are equal in a ``CHARACTER(3)``, while ``lower()`` of the two is
+#: not. Spelled out rather than matched by prefix because the variable-width
+#: names start with the same letters: ``VARCHAR`` and ``CHARACTER VARYING``
+#: compare the blanks and must not land here.
+PADDED_CHARACTER_TYPES = frozenset(
+ {
+ "CHAR",
+ "NCHAR",
+ # PostgreSQL's own name for ``CHARACTER``, which is what reflection
+ # reports for a ``CHAR(n)`` column there.
+ "BPCHAR",
+ "CHARACTER",
+ "NATIONAL CHAR",
+ "NATIONAL CHARACTER",
+ }
+)
+
+
+def _is_padded_character_type(column: TableColumn) -> bool:
+ """
+ Whether ``column``'s declared type compares without its trailing blanks.
+
+ Read off the declared type rather than the engine spec's resolved one: the
+ specs map ``CHAR`` and ``VARCHAR`` onto the same `sqlalchemy.String`, so
+ the distinction this needs is gone by then. The length suffix is dropped
+ and the name matched against `PADDED_CHARACTER_TYPES`, so an unfamiliar
+ spelling answers ``False`` and the engine-level flag decides as before --
+ this gate adds a decline rather than lifting one. A column with no
+ declared type has nothing to read, and answers the same way.
+ """
+ if not isinstance(column.type, str):
+ return False
+ native = re.sub(r"\s+", " ", column.type.strip().upper())
+ return native.split("(")[0].strip() in PADDED_CHARACTER_TYPES
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ Padding is asked about per column, because it is a property of the *type*
+ rather than of the engine. ``binary_string_comparison`` speaks for an
+ engine's default text comparison, and on PostgreSQL -- which declares it
+ -- a ``CHAR(2)`` still matches a filter for ``'US '`` against a stored
+ ``'US'``, because the standard says a padded character type compares
+ without its trailing blanks. The mirror ``region_key = lower('US ')`` then
+ excludes the row. So a fixed-width character type declines whatever the
+ engine says, and an engine that ignores trailing blanks on its *variable*
+ types says so by not declaring the flag at all (see `RedshiftEngineSpec`).
+
+ The type asked for is the engine spec's reading of the column's declared
+ type, not `TableColumn.type_generic`, which answers ``TEMPORAL`` for
+ anything carrying ``is_dttm``. A ``VARCHAR`` flagged temporal is still text
+ to the engine: on MySQL a filter for ``'2026-01-01T00:00:00'`` matches a
+ stored ``'...t00:00:00'``, while the mirror ``p = hex('...T...')`` excludes
+ it -- and asking the semantic flag skipped the check entirely.
+
+ A type the spec cannot classify declines, which is what the paragraph above
+ promises and what only the exception branch used to do. PostgreSQL's
+ ``citext`` matches no type pattern, so it answered ``None`` -- neither
+ string nor not-string -- and was waved through, which is precisely wrong
+ for a type whose whole purpose is case-insensitive comparison. Declining
+ costs the pruning; admitting it costs rows.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ # Ahead of the generic-type question, which a padded type can lose: the
+ # specs map ``CHARACTER`` onto no generic type at all on some engines, and
+ # a fixed-width character type is a string whether or not Superset can say
+ # so from the name.
+ if _is_padded_character_type(column):
+ return False
+ generic_type = _native_generic_type(column)
+ if generic_type is None:
+ return False
+ if generic_type != utils.GenericDataType.STRING:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_unicode_escaped_identifier(transform: str | None) -> bool:
+ """Whether the transform names something through a ``U&"..."`` escape.
+
+ See `UNICODE_ESCAPED_IDENTIFIER_RE`. Answered on raw text for the same
+ reason as the comment above: the parse reports a name the engine does not
+ use, which is exactly what makes the denylist blind to it.
+ """
+ return (
+ bool(transform)
+ and UNICODE_ESCAPED_IDENTIFIER_RE.search(transform or "") is not None
+ )
+
+
+#: Sequence pseudo-columns, which advance a sequence when they are *read*.
+#:
+#: ``orders_seq.NEXTVAL`` parses as a qualified column reference, not a
+#: function call, so neither `SQLStatement.is_mutating` -- which walks function
+#: names -- nor the function denylist can see it. The probe would then run
+#: ``SELECT orders_seq.NEXTVAL + 1 FROM DUAL`` and advance the sequence, again
+#: on every cache expiry, for a dataset editor holding neither SQL Lab nor a
+#: DML grant. Reading one is a write however the parser classifies it.
+#:
+#: The function spelling (``nextval('s')`` on PostgreSQL) is a different shape
+#: and is caught as a function; this is only about the suffix form.
+SEQUENCE_PSEUDO_COLUMNS = frozenset({"nextval", "currval"})
+
+#: The same thing written as a call.
+#:
+#: Only the suffix form parses as a column; `nextval('s')` on PostgreSQL and
+#: DuckDB, `NEXTVAL(s)`/`SETVAL(s, 1)` on MySQL and MariaDB, and SQL Server's
+#: `NEXT VALUE FOR s` all parse as functions. `SQLStatement.is_mutating` walks
+#: function names on PostgreSQL alone -- deliberately, since the same names are
+#: read-only elsewhere -- so every other engine let these through.
+#:
+#: Matched on the name whatever the engine, because advancing a sequence is a
+#: write wherever it happens and a transform has no reason to call one.
+SEQUENCE_FUNCTIONS = frozenset(
+ {"nextval", "setval", "next_value_for", "nextvalfor", "prevval", "lastval"}
+)
+
+
+def references_sequence(statement: SQLStatement) -> bool:
+ """Whether the statement reads or advances a sequence.
+
+ Both spellings: the pseudo-column suffix, which parses as a column (see
+ `SEQUENCE_PSEUDO_COLUMNS`), and the call, which parses as a function (see
+ `SEQUENCE_FUNCTIONS`).
+
+ Answered on the parse rather than on raw text, because position is what
+ makes it the construct: a column or alias merely *called* ``nextval`` is
+ an ordinary column, and a string literal holding the word is text.
+ """
+ return bool(
+ statement.get_column_names() & SEQUENCE_PSEUDO_COLUMNS
+ or statement.get_disallowed_functions(set(SEQUENCE_FUNCTIONS))
+ )
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """
+ Whether the transform contains a balanced Jinja block.
+
+ A block is an opening delimiter followed, anywhere later, by its closing
+ one -- the same thing ``{{.*?}}`` and its two siblings match under
+ ``re.DOTALL``. Scanned with `str.find` rather than that pattern, because a
+ lazy match retried from every opening delimiter is quadratic in a run of
+ them, and this runs on stored transforms with no length bound of its own:
+ `is_transform_active` reads whatever the column holds. The earliest opening
+ delimiter is the only one worth trying, since any closing delimiter after a
+ later one is also after it.
+ """
+ if not transform:
+ return False
+ for opening, closing in JINJA_BLOCK_DELIMITERS:
+ start = transform.find(opening)
+ if start != -1 and transform.find(closing, start + len(opening)) != -1:
+ return True
+ return False
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+
+ Three spellings have to be looked for, because one name reaches the parse
+ three ways: as a function call, as a zero-argument call a dialect resolves
+ itself, and -- for the datetime keywords -- as a bare word that parses as a
+ column reference.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ # The parenthesis-free spellings, which parse as columns rather than
+ # functions and so are invisible to the walk above. See
+ # `BARE_WALL_CLOCK_KEYWORDS`.
+ found |= {
+ name.upper() for name in BARE_WALL_CLOCK_KEYWORDS & statement.get_column_names()
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error( # noqa: C901
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ And it must be a *read*. Shape is a separate question from effect: a bare
+ scalar expression can still write, so `SQLStatement.is_mutating` is asked
+ too -- the same question SQL Lab and the chart executor ask before letting
+ SQL run. See the gate itself for what that reaches and what it does not.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ # Also ahead of the parse, and for a stronger reason than cost: every gate
+ # below reasons about the parse tree, and this is the one construct that
+ # makes the parse tree describe a different statement from the one the
+ # engine runs. Checked here as well as in `validate_transform` because this
+ # is the door a row written by an earlier release still comes through.
+ if contains_executable_comment(transform):
+ return str(
+ _(
+ "A partition value transform cannot contain a MySQL "
+ "executable comment, which the database executes and every "
+ "validator reads as a comment."
+ )
+ )
+
+ if contains_unicode_escaped_identifier(transform):
+ return str(
+ _(
+ "A partition value transform cannot name anything through a "
+ 'U&"..." escape sequence, which the database decodes and '
+ "every validator reads literally."
+ )
+ )
+
+ # Same door, same reason: the name the denylist below would match is not
+ # the name the engine resolves. See `UNICODE_ESCAPED_IDENTIFIER_RE`.
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The read-only gate, which nothing above implies. The shape gates ask what
+ # the transform *selects*; this asks what evaluating it *does*, and a bare
+ # scalar expression can still write. `nextval(:value)` on PostgreSQL
+ # advances a sequence: one function call, no clause, no sub-query, and not
+ # in the default `DISALLOWED_SQL_FUNCTIONS` either -- so every gate above
+ # passes it and the probe then runs it. `setval` is the same shape, and
+ # `exp.Execute` and the opaque-`exp.Command` forms arrive the same way.
+ #
+ # The large-object writers (`lo_export`, `lowrite`, `lo_from_bytea`, ...)
+ # are caught here too, and the shipped denylist happens to name them as
+ # well -- but that is config an operator can replace, while this is not.
+ #
+ # `is_mutating` is the same question SQL Lab, `get_virtual_table_metadata`
+ # and the chart executor ask before letting SQL run, so a transform is held
+ # to the bar the rest of Superset already sets rather than to one invented
+ # here. Unconditional rather than gated on `Database.allow_dml`: a transform
+ # is a scalar function of `:value` by definition, so there is no legitimate
+ # mutating one, and the probe runs on a cache schedule nobody chose -- a
+ # write would repeat every time the entry expired.
+ #
+ # It bears saying what this does not reach. A user-defined function whose
+ # body writes is a plain call no parser can tell from `lower(:value)`, and
+ # `is_mutating`'s function-name walk is PostgreSQL-only by design, since the
+ # same names are read-only elsewhere. Neither residual is specific to this
+ # feature -- a dataset editor can already have the engine evaluate an
+ # arbitrary expression through a calculated column or a virtual dataset's
+ # SQL -- and closing them means authorizing the preview against the
+ # database, not parsing harder.
+ if statement.is_mutating():
+ return str(
+ _(
+ "A partition value transform cannot change data. It is "
+ "evaluated against the database to check that it mirrors, so "
+ "it has to be a read."
+ )
+ )
+
+ # Not reached by the walk above, which is why it is its own gate: a
+ # sequence pseudo-column is a *column* to the parser and a write to the
+ # engine. See `SEQUENCE_PSEUDO_COLUMNS`.
+ if references_sequence(statement):
+ return str(
+ _(
+ "A partition value transform cannot read a sequence. "
+ "NEXTVAL advances the sequence every time it is evaluated, "
+ "and the transform is evaluated on a cache schedule."
+ )
+ )
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the
+ probe uninspected. Rendering is not what makes that true: a string element
+ is checked by `literal_round_trips` before it is rendered -- the dialect's
+ literal processor and the engine's lexer do not always agree about what a
+ rendered literal says -- and `probe_sql_is_evaluable` re-reads the finished
+ query, which is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def _placeholder_is_bindable(transform: str) -> bool:
+ """
+ Whether SQLAlchemy's ``text()`` can see ``:value`` as a bound parameter.
+
+ `VALUE_PLACEHOLDER_RE` is ``:value\b``, which matches the placeholder in a
+ Postgres cast such as ``:value::bigint``. SQLAlchemy's own bind scan is
+ ``(?<![:\\w$]):([\\w$]+)(?![:\\w$])`` -- note the trailing exclusion -- so a
+ following colon stops it: ``text(":value::bigint")`` reports a parameter
+ named ``valu``, and ``.bindparams(bindparam("value"))`` then raises
+ ``ArgumentError``.
+
+ `_probe` swallows that, so the only symptom was a perfectly valid transform
+ whose mapping silently never pruned, and a preview reporting an engine
+ failure for SQL that was never sent. Every write-side gate passes the
+ transform: it parses, it is a bare expression, and the placeholder *is* in
+ an executable position.
+
+ Answered by attempting the bind itself rather than by pattern-matching
+ ``::`` or reading ``text()``'s private parameter map, so this cannot
+ disagree with what `build_probe_sql` is about to do -- on any dialect, or on
+ a SQLAlchemy whose scan changes.
+ """
+ try:
+ sa.text(transform).bindparams(sa.bindparam("value", value=None))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return False
+ return True
+
+
+def escape_foreign_colons(transform: str) -> str:
+ """
+ ``transform`` with every colon but the ``:value`` placeholder escaped.
+
+ `sqlalchemy.text` reads any ``:word`` as a bind parameter, including one
+ inside a string literal, and an unbound parameter renders as ``NULL``
+ under literal binds rather than raising. So ``:value || \':suffix\'``
+ compiled to ``'us' || 'NULL'``: the mirror asked for a partition value no
+ row holds and the chart dropped rows, with no error for `_probe` to
+ swallow and nothing on screen to say so.
+
+ Escaped rather than refused, because a colon in a literal is ordinary --
+ ``concat(:value, \':\', region)`` builds a composite key -- and the
+ placeholder is the only colon this module means to interpret. `text()`
+ reads ``\\:`` as a literal colon.
+
+ Only the bound path needs this. A `RawProbeValue` or an unbindable
+ placeholder is substituted as text by `parse_skeleton`, which never hands
+ the transform to `text()` at all.
+ """
+ pieces: list[str] = []
+ cursor = 0
+ for match in VALUE_PLACEHOLDER_RE.finditer(transform):
+ pieces.append(transform[cursor : match.start()].replace(":", r"\:"))
+ pieces.append(match.group(0))
+ cursor = match.end()
+ pieces.append(transform[cursor:].replace(":", r"\:"))
+ return "".join(pieces)
+
+
+def literal_round_trips(value: Any, dialect: Dialect | None, engine: str) -> bool:
+ """
+ Whether the engine reads a rendered ``value`` back as that same value.
+
+ The probe runs with no bound parameters, so every value reaches the engine
+ as literal text the driver wrote (see `build_probe_sql`). Whether that text
+ says what the value says is a question about two independent spellings: the
+ driver's escaping, and the engine's lexer. SQLAlchemy's default renderer
+ doubles apostrophes and passes backslashes through; Hive and Spark honour
+ the backslash and not the doubling, so ``'O''Brien'`` is read there as two
+ adjacent literals -- the transform is evaluated at ``OBrien``, and the
+ mirror asks for a partition key that holds none of the rows the filter
+ keeps. The same gap in the other direction lets a value close its own quote
+ and have the rest of it read as SQL.
+
+ Escaping is not the repair. Whether a backslash introduces an escape is a
+ per-session server setting -- ``standard_conforming_strings`` on Postgres,
+ ``NO_BACKSLASH_ESCAPES`` on MySQL, ``escapedStringLiterals`` on Spark -- and
+ nothing in the engine specs exposes it. SQLAlchemy reads it off the server
+ into ``_backslash_escapes`` during ``initialize(connection)``, which the
+ probe's dialect never reaches: `_dialect_for` asks the ``Database`` for a
+ dialect, not for a connection, so Postgres renders ``a\\b`` as
+ ``'a\\\\b'`` and a server with the standard setting reads four
+ characters. An engine-spec flag would have to be defaulted, and either
+ default is wrong for a dozen engines: one leaves the hole open, the other
+ corrupts the probed value.
+
+ So the premise is verified rather than declared, the way
+ `probe_sql_is_evaluable` verifies the finished statement. A value that does
+ not survive the round trip is not mirrored, which costs the query its
+ pruning and nothing else.
+
+ The short-circuit is a proof, not a guess, and it matters for cost: a
+ 200-member ``IN`` list would otherwise parse 200 times on the chart path.
+ If the renderer emitted the value between two quotes and changed nothing in
+ it, and the value carries neither a quote nor a backslash, then no lexer in
+ play can read it as anything but itself. Both exclusions are load-bearing:
+ on Hive ``a\\b`` renders verbatim and reads as ``a`` followed by a
+ backspace.
+
+ :param value: a filter value about to be rendered into the probe
+ :param dialect: the dialect that will render it, as `_dialect_for` reports
+ :param engine: ``database.backend``, whose lexer reads the result
+ :return: whether the two agree about what the literal says
+ """
+ if isinstance(value, RawProbeValue):
+ # Already SQL, with no single value for a parse to be compared against:
+ # its elements are checked before they are rendered, by
+ # `ExploreMixin._array_mirror_probe_value`. A backslash surviving into
+ # the finished text is refused here all the same, as the backstop for a
+ # renderer this module does not own.
+ return "\\" not in value.sql
+ if not isinstance(value, str):
+ # Numbers and instants are not written between delimiters, so there is
+ # no escaping for the two sides to disagree about.
+ return True
+
+ rendered = _compile_literal(sa.literal(value), dialect)
+ if rendered == f"'{value}'" and "'" not in value and "\\" not in value:
+ return True
+
+ try:
+ return (
+ SQLStatement(f"SELECT {rendered}", engine).get_select_literal_value()
+ == value
+ )
+ except SupersetParseError:
+ # A rendered literal the engine's own dialect will not parse is the
+ # strongest form of disagreement there is.
+ return False
+
+
+def value_round_trips(database: Database, value: Any) -> bool:
+ """
+ `literal_round_trips` for a caller holding a database, not a dialect.
+
+ Which renderer and which lexer apply is this module's business, so the two
+ callers outside it -- the chart path's own gate in
+ `ExploreMixin.mirror_probe_request` and the mapping summary Explore reads
+ -- ask in these terms and stay out of it.
+
+ :param database: the database whose driver renders and whose engine reads
+ :param value: a filter value about to be rendered into the probe
+ :return: whether the two agree about what the literal says
+ """
+ return literal_round_trips(value, _dialect_for(database), database.backend)
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text. That is not itself a boundary:
+ the processor's escaping is not always the escaping the engine honours, and
+ a value can close its own quote through the gap. The boundary is
+ `literal_round_trips` on the way in -- which callers must have run, like
+ `stored_expression_error` below -- and `probe_sql_is_evaluable` on the way
+ out.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ bindable = _placeholder_is_bindable(transform)
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ elif bindable:
+ # Every other colon escaped first: `text()` would read one inside a
+ # string literal as a second bind parameter and render it `NULL`.
+ # See `escape_foreign_colons`.
+ clause = sa.text(escape_foreign_colons(transform)).bindparams(
+ sa.bindparam("value", value=value)
+ )
+ rendered = _compile_literal(clause, dialect)
+ else:
+ # `text()` cannot see the placeholder (see
+ # `_placeholder_is_bindable`), so the value is rendered by the
+ # dialect's own literal processor first and substituted as SQL
+ # text. The same two steps in the other order: binding exists to
+ # get the value through that processor, and `_compile_literal`
+ # inlines the result either way, so this is the same string by a
+ # different route -- not a loosening of the "never interpolate a
+ # raw value" rule. `parse_skeleton` substitutes literally, so the
+ # rendered literal arrives here exactly as it was rendered, which
+ # is what makes `literal_round_trips`' verdict on it good for this
+ # branch as much as for the bound one.
+ rendered = parse_skeleton(
+ transform, _compile_literal(sa.literal(value), dialect)
+ )
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Five things have to hold, and all five are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+ * No comment, anywhere. A value that closes its own quote has to hide the
+ text `build_probe_sql` appended after it, and a comment is the only way
+ to do that and still balance the quotes -- so this is what makes the
+ alias check above sufficient rather than merely necessary. Read off the
+ parse rather than the text, so a comment *inside* a literal is data and
+ costs no pruning, and so the question is asked in the engine's own
+ dialect. A transform has no legitimate reason to carry one either; see
+ `EXECUTABLE_COMMENT_RE`.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ # Before the parse, because this gate's whole contract is that what the
+ # parse describes is what the engine will run, and an executable comment is
+ # precisely the text where that stops being true. The transform is already
+ # refused for carrying one; this covers the compiled statement, so no later
+ # change to how values are rendered can reintroduce it behind the gates
+ # below.
+ if contains_executable_comment(sql) or contains_unicode_escaped_identifier(sql):
+ return False
+
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if not isinstance(statement, SQLStatement):
+ # A dialect whose statements this gate cannot take apart -- KQL -- gets
+ # no probe rather than an unchecked one. It never had one: the clause
+ # inspection below is implemented for SQL statements only, and the
+ # alternative to declining here is an `AttributeError` that `_probe`
+ # swallows into the same outcome, less legibly.
+ return False
+ if statement.has_comment():
+ return False
+ if statement.has_subquery():
+ return False
+ if statement.get_clause_names() - {"from"}:
+ return False
+ if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+ """
+ The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+ Parsed rather than string-compared so that the comparison in
+ `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+ not parse answers ``None``, which no statement carrying a FROM can match --
+ the probe then declines, which is the right way for an unreadable engine
+ constant to fail.
+ """
+ if not from_suffix.strip():
+ return None
+ try:
+ return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+ except SupersetParseError:
+ return None
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ # The value side of the premise `probe_sql_is_evaluable` checks on the
+ # finished statement: a value the driver and the engine would spell
+ # differently is not probed at all -- see `literal_round_trips`.
+ #
+ # `ExploreMixin.mirror_probe_request` declines one earlier, with a reason
+ # the preview can explain, and that is the gate an owner sees. This is the
+ # one that cannot be walked around. `_collect_partition_mirror_range`
+ # appends its bounds into the sink without passing through that method at
+ # all, and both paths can hand back a value the gate never saw: on a column
+ # carrying a `python_date_format`, what is probed is
+ # `strftime(that format)` -- text no mapping gate has ever read.
+ #
+ # Above `_run_probe` on purpose. This is a property of one input, not of
+ # the transform, and a verdict recorded here would withdraw the mirror for
+ # every later value of a transform the engine evaluates perfectly well.
+ dialect = _dialect_for(database)
+ if not all(
+ literal_round_trips(value, dialect, database.backend) for value in distinct
+ ):
+ logger.warning(
+ "A filter value is not written the same way by the driver and the "
+ "database, so the partition transform is not probed at it; this "
+ "query will not prune"
+ )
+ return None
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+
+ The verdict is about the *transform*: whether the engine evaluated it at
+ all. A ``NULL`` among the results is not that -- it is this input's answer,
+ and `NULLIF(:value, 0)` returning ``NULL`` for ``n = 0`` says nothing about
+ the same transform on ``n = 2``. Counting it withdrew the promise for the
+ whole transform, and nothing restored it: a *failed* probe is deliberately
+ not cached, so the next chart re-probes and re-records, but a ``NULL`` is a
+ successful probe and *is* cached -- so the false verdict outlived every
+ later hit, and the editor reported a working mapping as not mirroring
+ while the query went on pruning. The per-input skip still happens where it
+ belongs, in the caller's own ``NULL`` guard.
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=values is not None,
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ from_suffix = database.db_engine_spec.select_without_from_suffix
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ from_suffix,
+ )
+ if not probe_sql_is_evaluable(
+ sql, database.backend, len(distinct), from_suffix
+ ):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _execution_identity(database: Database) -> str | None:
+ """
+ Who the warehouse will run the probe as, when that can vary by caller.
+
+ `_probe_cache_key` keys on the `Database` record, which is the *connection*
+ -- not the identity it is opened under. Two hooks make that identity a
+ function of the Superset user instead:
+
+ * ``impersonate_user`` on the database, which hands the effective username
+ to `db_engine_spec.impersonate_user`;
+ * ``DB_CONNECTION_MUTATOR``, which receives the effective username and may
+ return an entirely different account's URL.
+
+ Under either one, a cached probe result computed under user A's grants was
+ served to user B, and the preview echoed it back in ``emitted_predicate``.
+ A transform wrapping a read-capable function the denylist does not name --
+ Oracle's ``DBMS_XMLGEN.GETXML`` is the worked example -- then leaks across
+ users who were never allowed the same rows.
+
+ Returns ``None`` when neither hook is configured, which is the common case
+ and deliberately leaves the key as it was: the cache exists to keep a
+ synchronous warehouse round trip off the chart-query path, and keying every
+ deployment on the username would cost every deployment the hit rate to fix
+ the two that need it.
+
+ The *Superset* username rather than the resolved warehouse account, because
+ it is the input both hooks branch on, and reading it needs no URL parse and
+ puts no credential in the key.
+ """
+ if not (database.impersonate_user or app.config["DB_CONNECTION_MUTATOR"]):
+ return None
+ return get_username()
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _mirror_verdict_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str:
+ """
+ `_probe_cache_key` without the values.
+
+ Whether a transform can be evaluated at all is a property of the transform
+ and the connection, not of the filter that happened to be probing it, so
+ one chart's answer settles the question for the next one.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ # Whether a transform *can* be evaluated is a property of the
+ # transform and the connection -- but under impersonation the
+ # connection is per-user, and a function one account may call can
+ # be refused to another. See `_execution_identity`.
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_verdict:{digest}"
+
+
+def record_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ *,
+ mirrors: bool,
+) -> None:
+ """
+ Remember whether this transform produced a mirror, for the UI to read.
+
+ Advisory only. Nothing in the query path consults it: a probe that failed
+ once is retried on the next chart exactly as it is today, because declining
+ to prune for a whole cache timeout over one transient engine blip is the
+ trade `evaluate_transform` deliberately refuses -- see the comment where it
+ declines to cache a failure.
+
+ What this is for is the *claim*. `is_transform_active` parses the transform
+ and no more, so a transform the database rejects -- a misspelled function
+ is the common case -- is "active", and the editor's banner and Explore's
+ pruning glyph promise a speed-up that never happens. A promise is exactly
+ the thing that may be withheld on one bad answer and restored on a good
+ one, which is why this is a separate entry from the probe's own results
+ rather than a relaxation of that rule.
+
+ Written by `_run_probe`, so the preview endpoint -- which shares the
+ evaluator -- settles the question before the owner has even saved.
+ """
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(
+ _mirror_verdict_cache_key(database, catalog, schema, transform),
+ mirrors,
+ timeout=timeout,
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform verdict", exc_info=True)
+
+
+def known_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> bool | None:
+ """
+ The last verdict `record_mirror_verdict` stored, or `None` if there is none.
+
+ `None` is the honest answer on a cold cache and is deliberately not `False`:
+ reporting a working mapping as broken until something probes it would
+ trade one wrong claim for another. The alternative -- probing from the
+ read side -- would put a warehouse round trip on every Explore and
+ dashboard load, and a failing transform is not cached at all, so it would
+ be a round trip every single time.
+ """
+ try:
+ verdict = cache_manager.cache.get(
+ _mirror_verdict_cache_key(database, catalog, schema, transform)
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return verdict if isinstance(verdict, bool) else None
+
+
+def _compile_literal(element: Any, dialect: Dialect | None) -> str:
+ """
+ Compile with inline literals, undoing the paramstyle's percent doubling.
+
+ Both ``TextClause`` and literal compilation run the dialect's
+ ``post_process_text``, which doubles every ``%`` whenever the identifier
+ preparer asks it to -- true for MySQL and Postgres and for every spec
+ inheriting their paramstyle. That doubling exists so a later DBAPI
+ parameter-interpolation pass can undo it, and the probe has no such pass:
+ it executes with no bound parameters at all. So a transform of
+ ``date_format(:value, '%Y%m%d')`` reaches the warehouse asking for the
+ literal string ``%%Y%%m%%d``, the probe returns that instead of a date, and
+ the mirrored predicate drops every row the filter keeps.
+
+ The same normalization ``Database.compile_sqla_query`` applies for the same
+ reason. ``_double_percents`` is private and not guaranteed on a third-party
+ dialect, hence the ``getattr`` default.
+ """
+ compiled = str(
+ element.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
+ )
+ if dialect is not None and getattr(
+ dialect.identifier_preparer, "_double_percents", False
+ ):
+ compiled = compiled.replace("%%", "%")
+ return compiled
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be *asked* to stand in for itself, and the transform
+ cannot carry Jinja or call a non-deterministic function. Tier 2
+ (``blocking=False``) is everything that merely leaves the mapping inactive
+ -- including a self-mapping nobody asked for, where the partition column
+ merely happens to be the default datetime column.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column == partition_column:
+ # Asked for explicitly, so report it as the mistake it is.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+ elif not partition_mapped_column and main_dttm_col == partition_column:
+ # Resolved onto itself only because the default datetime column happens
+ # to be the partition column -- a state metadata sync could produce
+ # without anyone asking for it. The mapping is inert either way, since
+ # `resolve_partition_mapping` bails out on it, so this reports and lets
+ # the write through: blocking here means a dataset already in the state
+ # can never be saved again, not even to change its description, and
+ # there is no field whose edit would clear the error first.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "%(name)s is both the partition column and the default "
+ "datetime column, so the mapping points at itself and "
+ "stays inactive. Set a mapped column override, or change "
+ "the default datetime column.",
+ name=partition_column,
+ ),
+ blocking=False,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def drop_unmapped_value_transforms(
+ columns: list[dict[str, Any]] | None,
+ *,
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ names_by_id: dict[int, str] | None = None,
+ stored_by_name: dict[str, tuple[str | None, bool]] | None = None,
+) -> list[str]:
+ """
+ Null the value transform on every *incoming* column the mapping cannot mirror.
+
+ The write-side twin of `DatasetDAO.clear_unmapped_partition_transforms`,
+ which answers for the model. A mapping has exactly one mirrored column, so
+ at most one column may carry a transform. One parked on any other column is
+ invisible -- no row but the mapped one renders a transform -- and yet it is
+ stored, and it goes live the moment the mapped column resolves back to it.
+ Clearing an override is enough to do that: a null
+ ``partition_mapped_column`` means "follow ``main_dttm_col``".
+
+ Ungated on the feature flag, unlike its model-level twin, and the difference
+ is what each one discards. That one drops stored configuration, so with the
+ flag off it would be pure loss. This one drops only a value the request in
+ hand is asking to write where the invariant says none may live -- and the
+ flag-off window is precisely when such a value gets parked for later, since
+ the editor hides these fields and the model-level pass declines to run.
+
+ Three writers reach the columns with no effective model-level pass between
+ them, which is why this exists at all: the deprecated
+ ``POST /datasource/save/``, which writes straight through
+ `update_from_object` and so never had one; and a
+ ``PUT /api/v1/dataset/<pk>`` or a dataset import made while the flag is
+ off, where the pass runs on both sides of the write and declines on both.
+
+ Mutates the payload in place, because every caller hands its own request
+ dict straight on to the code that writes it. Returns the names it cleared,
+ so the caller can say so in a log: this is a silent correction to a payload
+ whose author may have meant it.
+
+ A column whose payload mentions neither field is left alone. "Incoming" is
+ the whole scope -- a transform already in storage on a column this request
+ says nothing about is the model-level pass's business, under its own flag.
+
+ The mapped column resolves the way every other reader resolves it,
+ ``partition_mapped_column or main_dttm_col``, and resolves to nothing
+ without a partition column -- in which case no column may hold a transform
+ either.
+
+ :param names_by_id: how to read the name off a payload entry that gives
+ only an ``id``. `DatasetDAO._upsert_columns` identifies an existing
+ column by its primary key and lets ``column_name`` be omitted -- the
+ column keeps the name it has -- so without this an ordinary PUT looked
+ like a payload of nameless columns, none of which matched the mapped
+ one, and every transform in it was dropped. Callers whose writer keys
+ on the name instead (`update_from_object`, the importer) pass nothing.
+ An entry this cannot name is left alone rather than guessed at.
+ :param stored_by_name: ``(transform, is_monotonic)`` as currently stored,
+ per column name, so an *echo* can be told from an introduction. A
+ GET-then-PUT client sends back every column exactly as it received it,
+ so changing the default datetime column away from the mapped one made
+ the payload's unchanged copy of its transform look like a value being
+ parked -- and nulling it destroyed configuration the owner never
+ touched, unrecoverably, with the flag off and the editor's own fields
+ hidden. An unchanged value is the model-level pass's business under its
+ own flag, which is the same line this function's docstring already
+ draws for a column the payload omits. Callers that cannot see storage
+ pass nothing and keep the stricter behaviour.
+ """
+ mapped_column = (
+ (partition_mapped_column or main_dttm_col) if partition_column else None
+ )
+ cleared: list[str] = []
+ for column in columns or []:
+ name = column.get("column_name")
+ if name is None and names_by_id is not None:
+ column_id = column.get("id")
+ if column_id is not None:
+ name = names_by_id.get(column_id)
+ if name is None or name == mapped_column:
+ continue
+ transform = column.get("partition_value_transform")
+ is_monotonic = column.get("partition_transform_is_monotonic")
+ if not transform and not is_monotonic:
+ continue
+ if stored_by_name is not None and name in stored_by_name:
+ stored_transform, stored_monotonic = stored_by_name[name]
+ # A key the entry does not carry is unchanged, not `False`:
+ # `_upsert_columns` writes only the keys present, so echoing the
+ # transform without the declaration is a valid partial update. Read
+ # as a change, it failed the exemption and wrote both fields back
+ # as null -- the loss the exemption exists to prevent.
+ monotonic_echoes = "partition_transform_is_monotonic" not in column or bool(
+ is_monotonic
+ ) == bool(stored_monotonic)
+ transform_echoes = (
+ "partition_value_transform" not in column
+ or transform == stored_transform
+ )
+ if transform_echoes and monotonic_echoes:
+ # An echo, not an introduction. See `stored_by_name`.
+ continue
+ column["partition_value_transform"] = None
+ column["partition_transform_is_monotonic"] = False
+ cleared.append(name)
+ return cleared
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if contains_executable_comment(transform):
+ # Blocking, and checked on raw text next to the Jinja gate because no
+ # parse reports it: sqlglot reads `/*!50000 ... */` as comment data
+ # while MySQL and MariaDB execute it, so every shape gate downstream
+ # inspects a statement the engine will not run. See
+ # `EXECUTABLE_COMMENT_RE`.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform cannot contain a MySQL executable "
+ "comment (/*! ... */ or /*M! ... */). Those are comments "
+ "to every validator and statement text to the database, "
+ "so what would run is not what was checked."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if contains_unicode_escaped_identifier(transform):
+ # Beside the comment gate, for the same reason and on raw text: the
+ # parse reports the escape sequence verbatim as the function's name,
+ # so the function denylist compares against a name PostgreSQL never
+ # uses -- it decodes `U&"\0071uery_to_xml"` and runs `query_to_xml`.
+ # See `UNICODE_ESCAPED_IDENTIFIER_RE`.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ 'A value transform cannot name anything through a U&"..." '
+ "escape sequence. The database decodes it and every "
+ "validator reads it literally, so what would run is not "
+ "what was checked."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_bare_expression(transform, engine):
+ # Blocking, and deliberately placed in `validate_transform` rather than
+ # only at the probe: one issue here closes the PUT, the importer, the
+ # query-time gate through `is_transform_active`, the Explore indicator's
+ # active verdict and the preview endpoint, all of which already consult
+ # this function.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform must be a single SQL expression. It "
+ "cannot carry a FROM, WHERE, GROUP BY or any other clause, "
+ "and it cannot contain a sub-query."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not contains_value_placeholder(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform must contain the :value placeholder, "
+ "which stands for the filter value being mirrored."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not placeholder_is_executable(transform, engine):
+ # Blocking, and for the same reason the shape gate above is: this is
+ # the function the PUT, the importer, `is_transform_active`, the
+ # Explore indicator and the preview all consult, so one issue here
+ # closes every door at once. A placeholder inside a string literal is
+ # a sub-query the engine will run once a filter value closes the quote;
+ # one inside a comment silently eats the probe's own alias.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The :value placeholder must appear where the engine will "
+ "evaluate it. It cannot sit inside a string literal or a "
+ "comment."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if functions := find_non_deterministic_functions(transform, engine):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform calls %(functions)s, whose result "
+ "depends on when and where it runs. The transform is "
+ "evaluated in a separate session and the result is cached, "
+ "so the emitted predicate would freeze a snapshot of that "
+ "moment.",
+ functions=", ".join(sorted(functions)),
+ ),
+ blocking=True,
+ )
+ ]
+
+ return []
+
+
+@lru_cache(maxsize=LRU_CACHE_MAX_SIZE)
+def is_transform_active(transform: str | None, engine: str) -> bool:
+ """
+ Whether Superset will mirror filters through this transform.
+
+ `validate_transform` with the messages discarded, so the Explore indicator
+ cannot advertise a mapping the save path recorded as inactive. Anything
+ cheaper here would be a second, weaker statement of the same rule, free to
+ drift from the one the save path applies.
+
+ Blocking issues count too. Jinja and non-deterministic transforms are
+ rejected on PUT, but `CreateDatasetCommand` and import do not validate the
+ mapping, so one can still reach the database -- and it would never mirror a
+ filter either.
+
+ Memoized because `partition_filter_mapping_summary` is serialized on every
+ Explore and dashboard load and this parses the transform. The key is
+ everything the answer depends on: `validate_transform` reads no session, no
+ locale and no config beyond `SQL_MAX_PARSE_LENGTH`, which bounds the parser
+ rather than changing a verdict within that bound.
+ """
+ return not validate_transform(transform, engine)
+
+
+def preview_partition_mapping( # pylint: disable=too-many-return-statements
+ datasource: SqlaTable,
+ *,
+ mapped_column: str,
+ value_transform: str | None,
+ sample_values: list[str],
+ operator: FilterOperator = FilterOperator.EQUALS,
+ is_monotonic: bool = False,
+ partition_column: str | None = None,
+) -> dict[str, Any]:
+ """
+ Evaluate a candidate mapping and describe the predicate it would emit.
+
+ Shares the evaluator -- and therefore the probe cache -- with the query
+ path, so preview and runtime cannot drift and a previewed transform warms
+ the chart path for free. The predicate itself comes from
+ `build_mirrored_predicates`, the same builder the query path uses, so
+ operator shapes cannot drift either: what the panel shows is what a chart
+ would emit.
+
+ Validation runs first and the engine second: a half-typed transform is by
+ definition unparseable, so most of what a text input produces costs zero
+ queries.
+
+ Every part of the mapping is taken from the request rather than the stored
+ dataset. The editor previews while the owner is still editing -- a mapping
+ that has to be saved before it can be checked is not a preview.
+ """
+ partition_column = partition_column or datasource.partition_column
+ if not partition_column:
+ return {
+ "valid": False,
+ "reason": "unconfigured",
+ "error": _("No partition column is set."),
+ }
+
+ columns_by_name = {str(column.column_name): column for column in datasource.columns}
+ if mapped_column not in columns_by_name:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _("%(name)s is not a column on this dataset.", name=mapped_column),
+ }
+
+ # The bail-out `resolve_partition_mapping` makes at query time, and that
+ # `partition_filter_mapping_summary` repeats for the Explore indicator.
+ # Without it here, preview reports a valid emitted predicate for a mapping
+ # no chart will ever mirror -- the one answer a preview panel must not give.
+ if has_active_advanced_data_type(columns_by_name[mapped_column]):
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _(
+ "%(name)s has an advanced data type, so its filters are "
+ "translated into their own predicate shape and cannot be "
+ "mirrored onto the partition column.",
+ name=mapped_column,
+ ),
+ }
+
+ engine = datasource.database.backend
+ for issue in validate_partition_mapping(
+ column_names=set(columns_by_name),
+ partition_column=str(partition_column),
+ partition_mapped_column=mapped_column,
+ main_dttm_col=datasource.main_dttm_col,
+ transform=value_transform,
+ engine=engine,
+ ):
+ return {
+ "valid": False,
+ # The parse failure is the one an owner sees constantly, and it is
+ # the only one the mockup gives its own headline to.
+ "reason": (
+ "parse"
+ if issue.field == "partition_value_transform"
+ and not is_parseable(value_transform, engine)
+ else "validation"
+ ),
+ "error": str(issue.message),
+ }
+
+ # The policy every other stored expression goes through. The save path
+ # applies it in `UpdateDatasetCommand._validate_partition_mapping`, but
+ # preview evaluates a candidate transform that has not been saved, so
+ # without this the gate had a door around it. See
+ # `stored_expression_error` for what is being kept out and why.
+ if reason := stored_expression_error(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ cast(str, value_transform),
+ ):
+ return {"valid": False, "reason": "validation", "error": reason}
+
+ mapping = PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=mapped_column,
+ value_transform=cast(str, value_transform),
+ is_monotonic=is_monotonic,
+ equality_is_safe=equality_mirrors_safely(
+ columns_by_name[mapped_column], datasource.database.db_engine_spec
+ ),
+ )
+ sample_input = _render_sample_input(
+ datasource, mapped_column, operator, sample_values
+ )
+
+ if operator not in PREVIEWABLE_OPERATORS:
+ # Checked before `mirrors`, which lets `TEMPORAL_RANGE` through when the
+ # transform is declared monotonic -- and the single sample value would
+ # then reach `handle_comparison_filter`, which has no case for a range
+ # and raises. The request schema rejects it too; this keeps the function
+ # honest for any other caller.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is mirrored as a pair of bounds, which "
+ "a preview of a single value cannot describe.",
+ operator=operator.value,
+ ),
+ }
+
+ if operator in MIRRORABLE_ALWAYS and not mapping.equality_is_safe:
+ # Withdrawn by `equality_mirrors_safely`, which no declaration about
+ # ordering can change -- so naming monotonicity here would send the
+ # owner to a checkbox that leaves the answer as it is.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter on this text column is not mirrored: "
+ "the database may treat strings that differ in case or "
+ "trailing spaces as equal, and the mirrored predicate could "
+ "then drop rows the filter keeps.",
+ operator=operator.value,
+ ),
+ }
+
+ if not mapping.mirrors(operator):
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is only mirrored when the transform "
+ "preserves ordering, which this one is not declared to do.",
+ operator=operator.value,
+ ),
+ }
+
+ return _preview_probe(
+ datasource,
+ mapping,
+ columns_by_name[mapped_column],
+ operator,
+ sample_values,
+ sample_input,
+ )
+
+
+def _preview_probe(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ mapped_col: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+ sample_input: str,
+) -> dict[str, Any]:
+ """
+ The half of a preview that needs the warehouse.
+
+ Split out from `preview_partition_mapping` so that the gates which answer
+ from the stored mapping alone stay readable as the single run of guard
+ clauses they are. Everything here has either run a query or decided not to.
+ """
+ value = datasource.mirror_probe_request(
+ operator,
+ _probe_input(datasource, mapped_col, operator, sample_values),
+ mapped_col,
+ )
+ if is_unmirrorable(value):
+ # The same step the chart path applies, so the preview cannot promise a
+ # mirror the query declines -- and it reports the reason that step
+ # recorded rather than deriving one of its own, which is what let the
+ # offset case be explained as a precision loss it is not.
+ if value.reason == "offset":
+ # The transform is fine and the column may well compare the whole
+ # instant; what cannot be mirrored is the frame. Advising a
+ # different column here would send the owner after a column they
+ # already have.
+ return {
+ "valid": False,
+ "reason": "offset",
+ "sample_input": sample_input,
+ "error": _(
+ "A filter value carrying a UTC offset is not mirrored: a "
+ "transform is evaluated in the database's own time frame, "
+ "so the mirrored predicate could ask for a partition the "
+ "matching rows are not in. Write the bound without an "
+ "offset to mirror this filter.",
+ ),
+ }
+ if value.reason == "escaping":
+ # Nothing about the column, the operator or the transform is wrong
+ # here, so none of the advice the other branches carry applies: the
+ # driver and the database disagree about how to write this value
+ # down. Said in terms of the value, which is the only thing the
+ # owner can change.
+ return {
+ "valid": False,
+ "reason": "escaping",
+ "sample_input": sample_input,
+ "error": _(
+ "A filter value containing a quote or a backslash is not "
+ "mirrored on this database: the driver and the database do "
+ "not agree on how to write it into a query, so the "
+ "transform would be evaluated at a value the filter does "
+ "not compare. Filters whose values carry neither still "
+ "mirror.",
+ ),
+ }
+ # The transform is fine and the engine evaluates it, the filter just
+ # carries more of the value than the engine compares on this column --
+ # which is the column's type talking, not a broken expression.
+ return {
+ "valid": False,
+ "reason": "resolution",
+ "sample_input": sample_input,
+ "error": _(
+ "This engine compares less of a %(operator)s value on "
+ "%(column)s than the filter carries, so there is no mirror a "
+ "predicate on the partition column could stand in for. Map a "
+ "column the engine compares in full to mirror this operator.",
+ operator=operator.value,
+ column=mapped_col.column_name,
+ ),
+ }
+ errors: list[str] = []
+ type_errors: list[str] = []
+ escaping_errors: list[str] = []
+ predicates = build_mirrored_predicates(
+ datasource,
+ mapping,
+ [(operator, value)],
+ errors=errors,
+ type_errors=type_errors,
+ escaping_errors=escaping_errors,
+ )
+ if type_errors:
+ # Its own reason, because "the database would not evaluate this" and
+ # "it evaluated and answered with the wrong kind of thing" are
+ # different problems with different fixes, and the owner is the only
+ # one who can tell which transform they meant to write.
+ return {
+ "valid": False,
+ "reason": "type",
+ "sample_input": sample_input,
+ "error": type_errors[0],
+ }
+ if escaping_errors:
+ # Its own reason, and distinct from the `escaping` one above: that is
+ # about the value the chart author typed, this is about what the
+ # transform made of it. Falling through to `engine` below told the owner
+ # the database would not evaluate the transform, when it evaluated it
+ # perfectly and answered with a key that cannot be asked for here.
+ return {
+ "valid": False,
+ "reason": "transform_escaping",
+ "sample_input": sample_input,
+ "error": escaping_errors[0],
+ }
+ if not predicates:
+ return {
+ "valid": False,
+ "reason": "engine",
+ "sample_input": sample_input,
+ "error": (
+ _(
+ "The transform could not be evaluated against the "
+ "database: %(reason)s",
+ reason=errors[0],
+ )
+ if errors
+ else _("The transform could not be evaluated against the database.")
+ ),
+ }
+
+ return {
+ "valid": True,
+ "sample_input": sample_input,
+ "emitted_predicate": _render_predicate(datasource, predicates[0]),
+ }
+
+
+def _probe_input(
+ datasource: SqlaTable,
+ column: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+) -> Any:
+ """
+ The sample values as the query path would bind them.
+
+ The request carries samples as strings, and the probe is keyed on exactly
+ what it is handed, so passing them through raw asks the engine a different
+ question from the one a chart asks. A sample of ``2025`` on a numeric
+ column has to arrive as the integer the chart compares: under a transform
+ of ``typeof(:value)`` the raw string previewed ``'text'`` where the chart
+ emitted ``'integer'``. And because `_probe_cache_key` keys on each value's
+ ``repr``, the two also missed each other's cache entirely -- so the "a
+ previewed transform warms the chart path for free" claim in
+ `preview_partition_mapping`'s docstring did not actually hold.
+
+ Coerced by `filter_values_handler`, the same function the query path uses,
+ rather than by a second implementation of the same rules. Everything the
+ query path then does to the coerced value -- rendering an expression as a
+ literal, widening a bound, declining a comparison the engine resolves too
+ coarsely -- is `ExploreMixin.mirror_probe_request`'s, and the caller hands
+ this result straight to it.
+
+ Ranges are not previewable (see `PREVIEWABLE_OPERATORS`), so the bound
+ conversion `_collect_partition_mirror_range` applies -- a ``datetime`` into
+ the column's stored representation -- has no counterpart here.
+
+ An array column is the exception to `filter_values_handler`: its predicate
+ is built from the raw value, parsed into elements and rendered as the
+ engine's own array literal, so the chart path probes that literal
+ (`ExploreMixin._array_mirror_probe_value`) and this does too. Passing the
+ handled text instead previewed ``length('[1, 2]')`` for a filter whose
+ query probes ``length(array(1, 2))``.
+
+ Answers with a value, or `None` where an engine spec claims array columns
+ without an array literal -- which `mirror_probe_request` then declines, as
+ the chart path declines it. It may also answer with an `Unmirrorable` the
+ array branch raised itself, which `mirror_probe_request` passes through;
+ otherwise the decline is that method's to make, and the caller hands this
+ straight to it.
+ """
+ is_list = operator == FilterOperator.IN
+ column_spec = datasource.db_engine_spec.get_column_spec(native_type=column.type)
+ if (
+ column_spec
+ and column_spec.generic_type == utils.GenericDataType.MULTI_VALUE
+ and operator in MIRRORABLE_ALWAYS
+ ):
+ # `=` and `IN` are the previewable operators the array branch builds a
+ # literal for; a bound on an array column binds the handled value on
+ # the chart path too, so it falls through to the same here.
+ return datasource._array_mirror_probe_value( # noqa: SLF001
+ sample_values if is_list else sample_values[0],
+ operator,
+ datasource.db_engine_spec.get_array_element_type(column.type),
+ datasource.db_engine_spec,
+ )
+ handled = datasource.filter_values_handler(
+ # `list[str]` is not a `list[FilterValue]` to mypy, invariantly, even
+ # though every `str` is a `FilterValue`.
+ values=cast(FilterValues, sample_values if is_list else sample_values[0]),
+ operator=operator,
+ target_generic_type=(
+ column_spec.generic_type if column_spec else utils.GenericDataType.STRING
+ ),
+ target_native_type=column.type,
+ is_list_target=is_list,
+ db_engine_spec=datasource.db_engine_spec,
+ db_extra=datasource.db_extra,
+ )
+ # No `ColumnElement` conversion here: an epoch-milliseconds sample comes back
+ # as engine SQL rather than a value, and `mirror_probe_request` renders it --
+ # the same step, on the same values, as for a chart filter.
+ return handled
+
+
+def _render_sample_input(
+ datasource: SqlaTable,
+ mapped_column: str,
+ operator: FilterOperator,
+ values: list[str],
+) -> str:
+ """
+ The filter being previewed, written the way an owner would read it.
+
+ Display-only -- it is never executed -- but it is still read as SQL, so the
+ column is quoted and the values are rendered by the dialect rather than
+ concatenated raw. A column named ``order date`` would otherwise come out as
+ two bare words.
+ """
+ quoted = datasource.quote_identifier(mapped_column)
+ if operator == FilterOperator.IN:
+ rendered = ", ".join(
+ _render_literal(datasource.database, value) for value in values
+ )
+ return f"{quoted} IN ({rendered})"
+ return (
+ f"{quoted} {operator.value} {_render_literal(datasource.database, values[0])}"
+ )
+
+
+def _render_predicate(datasource: SqlaTable, predicate: ColumnElement[Any]) -> str:
+ """
+ Compile a mirrored predicate to the text a reader would see in View query.
+
+ Every value in it is a probed constant by this point, so ``literal_binds``
+ renders the same literals the chart query carries.
+ """
+ return _compile_literal(predicate, _dialect_for(datasource.database)).replace(
+ "\n", " "
+ )
+
+
+def _render_literal(database: Database, value: Any) -> str:
+ """
+ Render a value the way it appears in the generated SQL.
+
+ Compiled by the dialect rather than formatted by hand. `str()` would render
+ a NULL as the Python repr `None` and leave a date unquoted, neither of which
+ is SQL, and hand-rolled quote-doubling would only ever have been right for
+ strings.
+ """
+ return _compile_literal(sa.literal(value), _dialect_for(database))
+
+
+def build_mirrored_predicates(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ requests: list[tuple[FilterOperator, Any]],
+ *,
+ errors: list[str] | None = None,
+ type_errors: list[str] | None = None,
+ escaping_errors: list[str] | None = None,
+) -> list[ColumnElement[Any]]:
+ """
+ Turn collected ``(operator, value)`` mirror requests into predicates.
+
+ ``requests`` is expected to be deduplicated by the caller. Every value is
+ resolved in a single probe round trip -- one per chart query at most -- then
+ emitted as a literal constant, so "View query" shows the reader an ordinary
+ ``WHERE`` clause rather than an inline expression.
+
+ A strict bound is emitted non-strictly; see `mirror_operator`. That happens
+ here, at the one point where a ``FilterOperator`` becomes SQL, rather than
+ at the collection sites in `ExploreMixin`: the preview endpoint calls this
+ directly, so this is what keeps the predicate the editor shows an owner and
+ the predicate the chart carries from disagreeing.
+
+ :param errors: optional sink; see `evaluate_transform`.
+ :param type_errors: optional sink for a probe result the partition column
+ cannot hold -- see `probed_value_type_error`. Separate from ``errors``
+ because the two say different things to an owner: that one is "the
+ database would not evaluate this", and this one is "it evaluated, and
+ answered with the wrong kind of thing".
+ :param escaping_errors: optional sink for a probe result the driver and the
+ engine would spell differently -- see `_predicates_from_probe`. Its own
+ sink for the same reason: "it evaluated, and answered with something
+ this database cannot be asked about" is a third problem, and the only
+ one of the three whose fix is to stop the transform producing the
+ character.
+ """
+ if not requests:
+ return []
+
+ partition_column = next(
+ (
+ column
+ for column in datasource.columns
+ if column.column_name == mapping.partition_column
+ ),
+ None,
+ )
+ if partition_column is None:
+ return []
+
+ # Flatten every value that needs probing into one list, remembering how many
+ # each request consumed so the results can be handed back out.
+ flat: list[Any] = []
+ spans: list[tuple[FilterOperator, int, int]] = []
+ for operator, value in requests:
+ values = list(value) if operator == FilterOperator.IN else [value]
+ spans.append((operator, len(flat), len(values)))
+ flat.extend(values)
+
+ evaluated = evaluate_transform(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ mapping.value_transform,
+ flat,
+ errors=errors,
+ )
+ if evaluated is None:
+ return []
+
+ if not _bounds_are_ordered(evaluated, spans):
+ return []
+
+ # Declining here is the last chance to decline at all: once these
+ # predicates are in the statement, a value the partition column cannot
+ # hold fails the whole chart rather than its pruning.
+ if reason := probed_value_type_error(partition_column, evaluated):
+ logger.warning(
+ "Partition transform returned a value the partition column cannot "
+ "hold; queries will not prune: %s",
+ reason,
+ )
+ if type_errors is not None:
+ type_errors.append(reason)
+ # Deliberately *not* recorded as a mirror verdict. The transform
+ # evaluated perfectly; what failed is the comparison against this
+ # dataset's partition column -- and `_mirror_verdict_cache_key` is
+ # keyed on database, catalog, schema and transform, with no partition
+ # column in it. Recorded, this dataset-specific outcome answered for
+ # every other dataset sharing the transform: `CAST(:value AS text)`
+ # mirroring happily onto a text key in dataset A was reported
+ # `evaluable: false` -- and its pruning indicator hidden -- because
+ # someone previewed the same transform against a numeric key in
+ # dataset B. A probe cache hit on A never rewrites the verdict, so it
+ # stayed wrong until the entry expired.
+ return []
+
+ sqla_col = datasource.convert_tbl_column_to_sqla_col(partition_column)
+ predicates = _predicates_from_probe(
+ sqla_col,
+ datasource.database,
+ evaluated,
+ spans,
+ escaping_errors=escaping_errors,
+ )
+ if not predicates:
+ return []
+
+ # A comparison against a NULL partition value is NULL, so a row parked in a
+ # NULL partition is dropped by the mirror even when the real filter matches
+ # it -- Hive and Impala's default partition, or a transform that returns
+ # NULL for an input it cannot convert. The mirror only has to be no
+ # narrower than the filter it stands in for, so admitting NULL partitions
+ # keeps those rows. Engines still prune; they read one extra partition.
+ return [sa.or_(sa.and_(*predicates), sqla_col.is_(None))]
+
+
+def _predicates_from_probe(
+ sqla_col: ColumnElement[Any],
+ database: Database,
+ evaluated: list[Any],
+ spans: list[tuple[FilterOperator, int, int]],
+ *,
+ escaping_errors: list[str] | None = None,
+) -> list[ColumnElement[Any]]:
+ """
+ One predicate on the partition column per surviving mirror request.
+
+ A request whose probe answered `None` for any of its values is skipped
+ rather than emitted: `col = NULL` is `NULL`, so it would drop every row the
+ filter keeps. A strict bound is emitted non-strictly; see `mirror_operator`.
+
+ A request whose probe answered with a value the driver and the engine spell
+ differently is skipped for the same reason -- see `literal_round_trips`.
+ `evaluate_transform` asks that question of the probe's *inputs*; the answers
+ are the other end of the same round trip, because the chart query is
+ compiled with ``literal_binds`` and every one of them is rendered into its
+ SQL as a literal too. A transform of ``concat(:value, chr(92), 'b')`` maps
+ the unremarkable input ``a`` to the partition key ``a\\b``, which Hive reads
+ back as ``a`` followed by a backspace: the mirror then asks for a partition
+ no row is in, and because it is ``AND``-ed onto the query the chart loses
+ every row the filter keeps rather than losing its pruning.
+
+ :param escaping_errors: optional sink; see `build_mirrored_predicates`.
+ """
+ # Once for the whole call, not once per value: `_dialect_for` asks the
+ # `Database` for a dialect, and a 200-member `IN` would otherwise ask 200
+ # times. The same reading `evaluate_transform` takes on the way in.
+ dialect = _dialect_for(database)
+
+ predicates: list[ColumnElement[Any]] = []
+ for operator, start, length in spans:
+ chunk = evaluated[start : start + length]
+ if any(value is None for value in chunk):
+ continue
+ if not all(
+ literal_round_trips(value, dialect, database.backend) for value in chunk
+ ):
+ # One member is the whole request's problem, as for `None` above:
+ # mirroring the rest of an `IN` list would be narrower than the
+ # filter. Dropping this request alone is not, which is why the
+ # decline is per request rather than per query -- a range arrives as
+ # two of them, and keeping only the bound that survives the trip is
+ # a mirror wider than the filter, which is all the mirror has to be.
+ logger.warning(
+ "The partition transform answered with a value the driver and "
+ "the database do not write down the same way, so this filter "
+ "is not mirrored; the query will not prune for it"
+ )
+ if escaping_errors is not None:
+ escaping_errors.append(
+ _(
+ "The transform answered with a value the driver and the "
+ "database do not agree on how to write into a query, so "
+ "the mirrored predicate would ask for a partition key no "
+ "row holds. A transform whose result carries neither a "
+ "quote nor a backslash still mirrors."
+ )
+ )
+ continue
+ if operator == FilterOperator.IN:
+ # The probe answers per value, so a transform over a mixed-number
+ # filter can answer with a mixed-number partition key -- and
+ # `in_` infers the bind type from the first element it is handed.
+ # Without this, probe results of `[33, 29.02]` emit
+ # `IN (33, 29)` and prune away the partition holding `29.02`.
+ predicates.append(sqla_col.in_(normalize_mixed_numbers(chunk)))
Review Comment:
`normalize_mixed_numbers` widens every number to `float` once any one is a float, so an exact integer probe result above 2^53 is rounded here even though the database returned it exactly. On SQLite, `n IN (1, 2)` with `CASE WHEN :value = 1 THEN 9007199254740993 ELSE 2.5 END` probes to `[9007199254740993, 2.5]` but binds `p IN (9007199254740992.0, 2.5)`, so the `n = 1` row (`p = 9007199254740993`) is pruned. Could the mirror decline when widening would change an integer's value, instead of rounding it?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4339385288
##########
tests/unit_tests/models/partition_mirroring_test.py:
##########
@@ -0,0 +1,3204 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mirroring inside ``ExploreMixin.get_sqla_query``.
+
+The probe that resolves ``T(v)`` against the engine is stubbed throughout; what
+these tests pin down is *which* predicates get mirrored and with what values,
+which is where the correctness argument lives.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from typing import Any
+from unittest.mock import MagicMock, patch
+
+import pandas as pd
+import pytest
+import sqlalchemy as sa
+from flask import Flask
+
+from superset.connectors.sqla.models import SqlaTable, SqlMetric, TableColumn
+from superset.connectors.sqla.partition_mapping import RawProbeValue
+from superset.db_engine_specs.clickhouse import ClickHouseEngineSpec
+from superset.db_engine_specs.presto import PrestoEngineSpec
+from superset.db_engine_specs.sqlite import SqliteEngineSpec
+from superset.models.core import Database
+from superset.superset_typing import QueryObjectDict
+from superset.utils import json
+from superset.utils.core import FilterOperator
+
+PROBE = "superset.connectors.sqla.partition_mapping.evaluate_transform"
+
+
+@pytest.fixture(autouse=True)
+def enable_partition_filter_mapping(app: Flask) -> Any:
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = True
+ yield
+ del app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"]
+
+
+def _table(
+ *,
+ transform: str = "unix_timestamp(:value)",
+ monotonic: bool = True,
+ partition_column: str | None = "dt_epoch",
+ mapped_column: str = "event_time",
+ partition_mapped_column: str | None = None,
+ main_dttm_col: str | None = "event_time",
+) -> SqlaTable:
+ database = Database(database_name="test_db", sqlalchemy_uri="sqlite://")
+ columns = [
+ TableColumn(column_name="event_time", is_dttm=True, type="TIMESTAMP"),
+ TableColumn(column_name="other_time", is_dttm=True, type="TIMESTAMP"),
+ TableColumn(column_name="dt_epoch", type="BIGINT"),
+ TableColumn(column_name="country", type="VARCHAR"),
+ TableColumn(column_name="region_key", type="VARCHAR"),
+ ]
+ table = SqlaTable(
+ table_name="web_events",
+ database=database,
+ schema=None,
+ main_dttm_col=main_dttm_col,
+ columns=columns,
+ metrics=[SqlMetric(metric_name="hits", expression="COUNT(*)")],
+ )
+ table.partition_column = partition_column
+ table.partition_mapped_column = partition_mapped_column
+ for column in columns:
+ if column.column_name == mapped_column:
+ column.partition_value_transform = transform
+ column.partition_transform_is_monotonic = monotonic
+ return table
+
+
+def _mapped_date_table() -> SqlaTable:
+ """
+ A dataset whose mapped column is a ``DATE``.
+
+ That is the type whose literal an engine resolves to a bare day, which is
+ what the resolution reasoning is about; `_rendering_dates_like_presto` is
+ what makes this table's spec answer that way.
+ """
+ table = _table(mapped_column="event_date", main_dttm_col="event_date")
+ table.columns.append(
+ TableColumn(column_name="event_date", is_dttm=True, type="DATE")
+ )
+ table.columns[-1].partition_value_transform = "unix_timestamp(:value)"
+ table.columns[-1].partition_transform_is_monotonic = True
+ return table
+
+
+def _rendering_dates_like_presto(table: SqlaTable) -> Any:
+ """
+ Make the dataset's engine spec render a bound the way Presto does.
+
+ `Database.db_engine_spec` is a derived property, so the spec cannot be
+ swapped wholesale; delegating `convert_dttm` keeps the test tied to the real
+ spec rather than to a hand-copied format string. Presto's DATE branch is
+ `DATE '{dttm.date().isoformat()}'`, which Trino, BigQuery and some two dozen
+ others share.
+ """
+ return patch.object(
+ table.database.db_engine_spec,
+ "convert_dttm",
+ classmethod(
+ lambda cls, target_type, dttm, db_extra=None: PrestoEngineSpec.convert_dttm(
+ target_type, dttm, db_extra=db_extra
+ )
+ ),
+ )
+
+
+def _query(table: SqlaTable, **kwargs: Any) -> str:
+ defaults: dict[str, Any] = {
+ "columns": ["country"],
+ "metrics": [],
+ "orderby": [],
+ "extras": {},
+ "filter": [],
+ "granularity": None,
+ "is_timeseries": False,
+ }
+ defaults.update(kwargs)
+ result = table.get_sqla_query(**defaults)
+ return str(
+ result.sqla_query.compile(compile_kwargs={"literal_binds": True})
+ ).replace("\n", " ")
+
+
+# ---------------------------------------------------------------------------
+# The safe operators
+# ---------------------------------------------------------------------------
+
+
+def test_equality_filter_mirrors_onto_the_partition_column(app: Flask) -> None:
+ table = _table(
+ transform="lower(:value)",
+ monotonic=False,
+ mapped_column="country",
+ partition_mapped_column="country",
+ partition_column="region_key",
+ )
+
+ with app.app_context():
+ with patch(PROBE, return_value=["us"]):
+ sql = _query(
+ table,
+ filter=[
+ {"col": "country", "op": FilterOperator.EQUALS.value, "val": "US"}
+ ],
+ )
+
+ assert "region_key = 'us'" in sql
+ assert "country = 'US'" in sql
+
+
+def _with_date_partition_column(table: SqlaTable) -> SqlaTable:
+ """Re-point the mapping's partition column at a ``DATE`` column."""
+ table.columns.append(
+ TableColumn(column_name="part_date", is_dttm=True, type="DATE")
+ )
+ table.partition_column = "part_date"
+ return table
+
+
+def test_ordinary_text_does_not_mirror_onto_a_temporal_partition_column(
+ app: Flask,
+) -> None:
+ """
+ `lower(:value)` on a `VARCHAR` mapped column answers with text, and a
+ temporal partition column admits text -- a day key is legitimately text.
+ But it admitted *any* text: `country = 'US'` probed to `'us'` and emitted
+ `part_date = 'us'`, which PostgreSQL refuses as a date. By then the mirror
+ is in the statement, so a chart that worked before the mapping returned an
+ error rather than losing its pruning. The preview called it valid.
+ """
+ table = _with_date_partition_column(
+ _table(
+ transform="lower(:value)",
+ monotonic=False,
+ mapped_column="country",
+ partition_mapped_column="country",
+ )
+ )
+
+ with app.app_context():
+ with patch(PROBE, return_value=["us"]):
+ sql = _query(
+ table,
+ filter=[
+ {"col": "country", "op": FilterOperator.EQUALS.value, "val": "US"}
+ ],
+ )
+
+ assert "part_date" not in sql
+ assert "country = 'US'" in sql
+
+
+def test_a_text_column_s_bound_is_not_rounded_as_though_it_were_temporal(
+ app: Flask,
+) -> None:
+ """
+ SQLite's `convert_dttm` renders for `types.String` as well as the date
+ types, so a VARCHAR mapped column read as second-resolution -- and a filter
+ value that merely *looks* like an instant had its bound rounded as though
+ the engine had truncated it.
+
+ On a VARCHAR `country` mapped onto VARCHAR `region_key` by `:value`,
+ `country < '2026-07-06T10:08:11.500000'` was mirrored as
+ `region_key <= '2026-07-06 10:08:12.000000'`. A space sorts before `T`, so a
+ row holding `2026-07-06T09:00:00` -- which the filter keeps -- fell outside
+ the mirror and was dropped.
+
+ `_column_literal_resolution` already guarded on `is_dttm` and said in its
+ docstring that the per-instant callers never met this case. They do: the
+ value parses as an instant while the column is still text.
+ """
+ table = _table(
+ transform=":value",
+ monotonic=True,
+ mapped_column="country",
+ partition_mapped_column="country",
+ partition_column="region_key",
+ )
+
+ with app.app_context():
+ with patch(PROBE, return_value=["2026-07-06T10:08:11.500000"]) as probe:
+ _query(
+ table,
+ filter=[
+ {
+ "col": "country",
+ "op": FilterOperator.LESS_THAN.value,
+ "val": "2026-07-06T10:08:11.500000",
+ }
+ ],
+ )
+
+ # Handed through untouched: no rounding, and no seconds-shaped rewrite.
+ assert probe.call_args.args[-1] == ["2026-07-06T10:08:11.500000"]
+
+
+def test_a_day_key_still_mirrors_onto_a_temporal_partition_column(
+ app: Flask,
+) -> None:
+ """
+ The narrowing above must not cost the case the text admission exists for:
+ `to_char(:value, 'YYYYMMDD')` answers with a day key, which PostgreSQL
+ reads as a date and so declares in `temporal_literal_formats`.
+
+ Its sibling `test_a_day_key_still_mirrors_onto_a_text_partition_column`
+ covers the same transform onto a *text* key, which is the other axis --
+ that one is about `GenericDataType.STRING` and never reached this gate.
+ """
+ table = _with_date_partition_column(
+ _table(
+ transform="to_char(:value, 'YYYYMMDD')",
+ monotonic=False,
+ mapped_column="country",
+ partition_mapped_column="country",
+ )
+ )
+
+ with app.app_context():
+ with patch.object(SqliteEngineSpec, "temporal_literal_formats", ("%Y%m%d",)):
+ with patch(PROBE, return_value=["20260101"]):
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "country",
+ "op": FilterOperator.EQUALS.value,
+ "val": "US",
+ }
+ ],
+ )
+
+ assert "part_date = '20260101'" in sql
+
+
+def test_a_day_key_declines_where_the_engine_has_not_claimed_it(
+ app: Flask,
+) -> None:
+ """
+ BigQuery coerces a STRING literal to `DATE` only in the canonical
+ `YYYY-MM-DD` form and Trino wants an explicit cast, so `part_date =
+ '20260101'` fails the whole chart there rather than merely losing its
+ pruning. An engine that has not declared the format declines instead.
+ """
+ table = _with_date_partition_column(
+ _table(
+ transform="to_char(:value, 'YYYYMMDD')",
+ monotonic=False,
+ mapped_column="country",
+ partition_mapped_column="country",
+ )
+ )
+
+ assert SqliteEngineSpec.temporal_literal_formats == ()
+
+ with app.app_context():
+ with patch(PROBE, return_value=["20260101"]):
+ sql = _query(
+ table,
+ filter=[
+ {"col": "country", "op": FilterOperator.EQUALS.value, "val": "US"}
+ ],
+ )
+
+ assert "part_date" not in sql
+
+
+def test_in_filter_mirrors_element_wise(app: Flask) -> None:
+ table = _table(
+ transform="lower(:value)",
+ monotonic=False,
+ mapped_column="country",
+ partition_mapped_column="country",
+ partition_column="region_key",
+ )
+
+ with app.app_context():
+ with patch(PROBE, return_value=["us", "ca"]):
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "country",
+ "op": FilterOperator.IN.value,
+ "val": ["US", "CA"],
+ }
+ ],
+ )
+
+ assert "region_key IN ('us', 'ca')" in sql
+
+
+def test_time_range_mirrors_both_bounds(app: Flask) -> None:
+ """
+ The Explore time range is the most important operator in the feature, and it
+ is a range operator -- so it only mirrors on a declared-monotonic transform.
+ """
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1767225600, 1769904000]):
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ )
+
+ assert "dt_epoch >= 1767225600" in sql
+ assert "dt_epoch <= 1769904000" in sql
+
+
+def test_temporal_range_filter_mirrors_both_bounds(app: Flask) -> None:
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1767225600, 1769904000]):
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_time",
+ "op": FilterOperator.TEMPORAL_RANGE.value,
+ "val": "2026-01-01 : 2026-02-01",
+ }
+ ],
+ )
+
+ assert "dt_epoch >= 1767225600" in sql
+ assert "dt_epoch <= 1769904000" in sql
+
+
+@pytest.mark.parametrize(
+ "operator,expected",
+ [
+ (FilterOperator.GREATER_THAN, "dt_epoch >= 1767225600"),
+ (FilterOperator.GREATER_THAN_OR_EQUALS, "dt_epoch >= 1767225600"),
+ (FilterOperator.LESS_THAN, "dt_epoch <= 1767225600"),
+ (FilterOperator.LESS_THAN_OR_EQUALS, "dt_epoch <= 1767225600"),
+ ],
+)
+def test_strict_range_operators_mirror_non_strictly(
+ app: Flask, operator: FilterOperator, expected: str
+) -> None:
+ """
+ The direction is preserved; the strictness is not. "Preserves ordering"
+ means non-decreasing, so `col < v` only implies `T(col) <= T(v)` -- a
+ strict mirror would drop the rows a bucketing transform puts at the
+ boundary. The non-strict mirror reads one extra partition, and the original
+ filter is still there to exclude whatever it admits.
+ """
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1767225600]):
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_time",
+ "op": operator.value,
+ "val": "2026-01-01 00:00:00",
+ }
+ ],
+ )
+
+ assert expected in sql
+
+
+def test_a_bucketing_transform_keeps_the_boundary_bucket(app: Flask) -> None:
+ """
+ A day key is monotonic but not *strictly* so: every instant in a day
+ maps to one value, so an upper bound at `2026-07-06 12:00` and a row at
+ `2026-07-06 06:00` share the bucket `20260706`. Mirroring that bound
+ strictly prunes the bucket the row is in and drops it from the chart --
+ silently, with the pruning glyph still promising only a speed-up.
+ """
+ table = _table(
+ transform="to_char(:value, 'YYYYMMDD')",
+ partition_column="region_key",
+ )
+
+ with app.app_context():
+ with patch(PROBE, return_value=["20260705", "20260706"]):
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 7, 5),
+ to_dttm=datetime(2026, 7, 6, 12, 0),
+ )
+
+ assert "region_key >= '20260705'" in sql
+ assert "region_key <= '20260706'" in sql
+
+
+def test_an_intraday_strict_pair_does_not_mirror_to_an_empty_range(
+ app: Flask,
+) -> None:
+ """
+ The zero-instead-of-nine case. `event_time > '2026-07-05 06:00'` plus
+ `event_time < '2026-07-06 00:00'` is an ordinary pair of ad-hoc filters, and
+ under a day key the bounds land in adjacent buckets. Mirrored strictly it
+ reads `day_key > '20260705' AND day_key < '20260706'`, which is empty by
+ construction whatever the table holds -- so the chart returns nothing while
+ SQL Lab returns the real rows.
+ """
+ table = _table(
+ transform="to_char(:value, 'YYYYMMDD')",
+ partition_column="region_key",
+ )
+
+ with app.app_context():
+ with patch(PROBE, return_value=["20260705", "20260706"]):
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_time",
+ "op": FilterOperator.GREATER_THAN.value,
+ "val": "2026-07-05 06:00:00",
+ },
+ {
+ "col": "event_time",
+ "op": FilterOperator.LESS_THAN.value,
+ "val": "2026-07-06 00:00:00",
+ },
+ ],
+ )
+
+ assert "region_key >= '20260705'" in sql
+ assert "region_key <= '20260706'" in sql
+
+
+def test_an_integer_bucket_key_is_mirrored_non_strictly_too(app: Flask) -> None:
+ """
+ The same loss was measured on a day *number* as well as a day string, so it
+ is a property of any many-to-one transform rather than of text keys or of
+ the formatting function used to build them.
+ """
+ table = _table(transform="cast(unix_timestamp(:value) / 86400 as bigint)")
+
+ with app.app_context():
+ with patch(PROBE, return_value=[20638, 20639]):
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 7, 5),
+ to_dttm=datetime(2026, 7, 6, 12, 0),
+ )
+
+ assert "dt_epoch >= 20638" in sql
+ assert "dt_epoch <= 20639" in sql
+
+
+# ---------------------------------------------------------------------------
+# The unsafe operators — nothing is emitted
+# ---------------------------------------------------------------------------
+
+
+@pytest.mark.parametrize(
+ "flt",
+ [
+ {"col": "country", "op": FilterOperator.NOT_EQUALS.value, "val": "US"},
+ {"col": "country", "op": FilterOperator.NOT_IN.value, "val": ["US"]},
+ {"col": "country", "op": FilterOperator.LIKE.value, "val": "U%"},
+ {"col": "country", "op": FilterOperator.ILIKE.value, "val": "U%"},
+ {"col": "country", "op": FilterOperator.NOT_LIKE.value, "val": "U%"},
+ {"col": "country", "op": FilterOperator.IS_NULL.value},
+ {"col": "country", "op": FilterOperator.IS_NOT_NULL.value},
+ ],
+)
+def test_unsafe_operators_emit_nothing(app: Flask, flt: dict[str, Any]) -> None:
+ """
+ ``T`` need not be injective, so ``country != 'US'`` does not imply
+ ``region_key != 'us'`` -- mirroring it would drop rows whose ``country`` is
+ already lowercase, rows the original filter keeps.
+ """
+ table = _table(
+ transform="lower(:value)",
+ monotonic=False,
+ mapped_column="country",
+ partition_mapped_column="country",
+ partition_column="region_key",
+ )
+
+ with app.app_context():
+ with patch(PROBE, side_effect=AssertionError("probe must not run")):
+ sql = _query(table, filter=[flt])
+
+ assert "region_key" not in sql
+
+
+def test_ranges_do_not_mirror_when_the_transform_is_not_order_preserving(
+ app: Flask,
+) -> None:
+ """
+ ``hour(:value)`` is a perfectly reasonable partition transform on a
+ ``TIMESTAMP`` column and it is not monotonic, so a time range must not
+ mirror through it.
+ """
+ table = _table(transform="hour(:value)", monotonic=False)
+
+ with app.app_context():
+ with patch(PROBE, side_effect=AssertionError("probe must not run")):
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ )
+
+ assert "dt_epoch" not in sql
+
+
+def test_equality_still_mirrors_when_the_transform_is_not_order_preserving(
+ app: Flask,
+) -> None:
+ table = _table(transform="hour(:value)", monotonic=False)
+
+ with app.app_context():
+ with patch(PROBE, return_value=[13]):
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_time",
+ "op": FilterOperator.EQUALS.value,
+ "val": "2026-01-01 13:00:00",
+ }
+ ],
+ )
+
+ assert "dt_epoch = 13" in sql
+
+
+# ---------------------------------------------------------------------------
+# Bail-outs and edge cases
+# ---------------------------------------------------------------------------
+
+
+def test_nothing_mirrors_when_the_feature_flag_is_off(app: Flask) -> None:
+ table = _table()
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = False
+
+ with app.app_context():
+ with patch(PROBE, side_effect=AssertionError("probe must not run")):
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ )
+
+ assert "dt_epoch" not in sql
+
+
+def test_an_open_ended_range_mirrors_only_the_bound_it_has(app: Flask) -> None:
+ """``from_dttm``/``to_dttm`` are ``None`` for open-ended ranges."""
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1767225600]) as probe:
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=None,
+ )
+
+ assert probe.call_args.args[-1] == [datetime(2026, 1, 1)]
+ assert "dt_epoch >= 1767225600" in sql
+ assert "dt_epoch <" not in sql
+
+
+def test_no_filter_range_mirrors_nothing(app: Flask) -> None:
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, side_effect=AssertionError("probe must not run")):
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=None,
+ to_dttm=None,
+ )
+
+ assert "dt_epoch" not in sql
+
+
+def test_the_same_bound_is_not_mirrored_twice(app: Flask) -> None:
+ """
+ A ``granularity`` time filter *and* a ``TEMPORAL_RANGE`` ad-hoc filter on the
+ same column is a routine Explore configuration. Emitting the predicate twice
+ is harmless SQL but makes "View query" surprising.
+ """
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1767225600, 1769904000]):
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ filter=[
+ {
+ "col": "event_time",
+ "op": FilterOperator.TEMPORAL_RANGE.value,
+ "val": "2026-01-01 : 2026-02-01",
+ }
+ ],
+ )
+
+ assert sql.count("dt_epoch >= 1767225600") == 1
+ assert sql.count("dt_epoch <= 1769904000") == 1
+
+
+def test_always_filter_main_dttm_mirrors_the_main_column_too(app: Flask) -> None:
+ """
+ With ``always_filter_main_dttm`` the query also filters ``main_dttm_col``,
+ which is a *different* column from the one the chart grouped by. That filter
+ is the one the mapping tracks, so it has to mirror.
+ """
+ table = _table()
+ table.always_filter_main_dttm = True
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1767225600, 1769904000]):
+ sql = _query(
+ table,
+ granularity="other_time",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ )
+
+ assert "dt_epoch >= 1767225600" in sql
+ assert "dt_epoch <= 1769904000" in sql
+
+
+def test_a_failing_probe_leaves_the_query_correct_and_unpruned(app: Flask) -> None:
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=None):
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ )
+
+ assert "dt_epoch" not in sql
+ assert "event_time" in sql
+
+
+def test_a_probe_result_the_partition_column_cannot_hold_emits_nothing(
+ app: Flask,
+) -> None:
+ """
+ `cast(:value as text) || 'x'` evaluates perfectly and answers with a string,
+ and `dt_epoch` is a BIGINT. The predicate used to go out as
+ `dt_epoch >= '2026-01-01 00:00:00x'`, which Postgres refuses -- and by then
+ the mirror is in the statement, so the chart returned a 400 rather than
+ losing its pruning.
+ """
+ table = _table(transform="cast(:value as text) || 'x'")
+
+ with app.app_context():
+ probed = ["2026-01-01 00:00:00x", "2026-02-01 00:00:00x"]
+ with patch(PROBE, return_value=probed):
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ )
+
+ assert "dt_epoch" not in sql
+ assert "event_time" in sql
+
+
+def test_a_numeric_probe_result_still_mirrors_onto_a_numeric_key(
+ app: Flask,
+) -> None:
+ """The other side of the gate: the ordinary case is untouched."""
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1767225600, 1769904000]):
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ )
+
+ assert "dt_epoch >= 1767225600" in sql
+
+
+def test_a_day_key_still_mirrors_onto_a_text_partition_column(app: Flask) -> None:
+ """
+ A `to_char(:value, 'YYYYMMDD')`-style transform answers with text, and a
+ text partition column holds text. Refusing that would break the commonest
+ bucketing mapping there is.
+ """
+ table = _table(
+ transform="to_char(:value, 'YYYYMMDD')", partition_column="region_key"
+ )
+
+ with app.app_context():
+ with patch(PROBE, return_value=["20260101", "20260201"]):
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ )
+
+ assert "region_key >= '20260101'" in sql
+
+
+def test_an_inverted_transform_emits_nothing(app: Flask) -> None:
+ """
+ ``T(lower) <= T(upper)`` is a nearly-free runtime backstop for the
+ monotonicity *declaration*: it catches inverted transforms, and catches
+ ``hour()`` on any range spanning a day boundary. Necessary, not sufficient.
+ """
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1769904000, 1767225600]):
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ )
+
+ assert "dt_epoch" not in sql
+
+
+def test_incomparable_probe_results_emit_nothing(app: Flask) -> None:
+ """Probe results come back as pandas scalars; not every pair compares."""
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=[object(), object()]):
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ )
+
+ assert "dt_epoch" not in sql
+
+
+def test_self_mapping_is_skipped_defensively(app: Flask) -> None:
+ """Save-time validation rejects this, but older rows can carry it."""
+ table = _table(partition_column="event_time")
+
+ with app.app_context():
+ with patch(PROBE, side_effect=AssertionError("probe must not run")):
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ )
+
+ assert sql.count("event_time >=") == 1
+
+
+def test_a_filter_on_an_unmapped_column_mirrors_nothing(app: Flask) -> None:
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, side_effect=AssertionError("probe must not run")):
+ sql = _query(
+ table,
+ filter=[
+ {"col": "country", "op": FilterOperator.EQUALS.value, "val": "US"}
+ ],
+ )
+
+ assert "dt_epoch" not in sql
+
+
+def test_the_probe_receives_timezone_adjusted_bounds(app: Flask) -> None:
+ """
+ ``get_time_filter`` shifts the bounds by the dataset's timezone before
+ building the clause. Probing the *raw* bounds would produce epoch bounds
+ describing a different instant than the timestamp bounds they mirror --
+ wrong by exactly the offset, silently.
+
+ The bounds reach the probe as `datetime` objects here because the mapped
+ column declares no ``python_date_format``, so that *is* its stored
+ representation. See the sibling tests for a column where it is not.
+ """
+ table = _table()
+ table.extra = '{"timezone": "Europe/Berlin"}'
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1, 2]) as probe:
+ _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 9),
+ to_dttm=datetime(2026, 1, 10),
+ )
+
+ # Berlin is UTC+1 in January, so local midnight is 23:00 the day before.
+ assert probe.call_args.args[-1] == [
+ datetime(2026, 1, 8, 23, 0),
+ datetime(2026, 1, 9, 23, 0),
+ ]
+
+
+def test_the_probe_receives_hour_offset_adjusted_bounds(app: Flask) -> None:
+ """The legacy ``offset`` field shifts bounds too, and must reach the probe."""
+ table = _table()
+ table.offset = 5
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1, 2]) as probe:
+ _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 9, 12),
+ to_dttm=datetime(2026, 1, 10, 12),
+ )
+
+ assert probe.call_args.args[-1] == [
+ datetime(2026, 1, 9, 7),
+ datetime(2026, 1, 10, 7),
+ ]
+
+
+def test_the_probe_receives_an_epoch_column_s_own_representation(
+ app: Flask,
+) -> None:
+ """
+ The real predicate compares the column against `dttm_sql_literal`, which
+ for a column declaring an epoch ``python_date_format`` renders an integer.
+ So on such a column the transform is a function of an integer -- probing it
+ with a `datetime` evaluates something unrelated to the partition keys, or
+ raises, and a raise costs the dataset its pruning silently.
+ """
+ table = _table(mapped_column="event_epoch", main_dttm_col="event_epoch")
+ table.columns.append(
+ TableColumn(
+ column_name="event_epoch",
+ is_dttm=True,
+ type="BIGINT",
+ python_date_format="epoch_s",
+ )
+ )
+ table.columns[-1].partition_value_transform = "to_date(:value)"
+ table.columns[-1].partition_transform_is_monotonic = True
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1, 2]) as probe:
+ _query(
+ table,
+ granularity="event_epoch",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ )
+
+ assert probe.call_args.args[-1] == [1767225600, 1769904000]
+
+
+def test_the_probe_honours_a_per_column_date_format_from_db_extra(
+ app: Flask,
+) -> None:
+ """
+ `dttm_sql_literal` falls back to ``python_date_format_by_column_name`` in
+ the database's extra, so the probe has to read the same fallback -- on a
+ column where that fallback is actually reached. `event_epoch` is a BIGINT,
+ so SQLite's `convert_dttm` answers nothing and the format decides the
+ literal.
+
+ Its sibling below is the same configuration on a column where the engine
+ *does* answer, which is the case this test used to assert by accident.
+ """
+ table = _table(mapped_column="event_epoch", main_dttm_col="event_epoch")
+ table.columns.append(
+ TableColumn(column_name="event_epoch", is_dttm=True, type="BIGINT")
+ )
+ table.columns[-1].partition_value_transform = "to_date(:value)"
+ table.columns[-1].partition_transform_is_monotonic = True
+ table.database.extra = json.dumps(
+ {"python_date_format_by_column_name": {"event_epoch": "%Y%m%d"}}
+ )
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1, 2]) as probe:
+ _query(
+ table,
+ granularity="event_epoch",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ )
+
+ assert probe.call_args.args[-1] == ["20260101", "20260201"]
+
+
+def test_a_date_format_the_engine_literal_preempts_is_not_probed(
+ app: Flask,
+) -> None:
+ """
+ `dttm_sql_literal` asks `convert_dttm` first and reaches the format only if
+ the engine answers nothing. `event_time` is a TIMESTAMP, so SQLite answers
+ `'2026-01-01 00:00:00'` and the `%Y%m%d` format never applies to the real
+ predicate -- but the probe applied it anyway.
+
+ The mirror therefore described a different bound from the filter it stands
+ in for: `event_time >= '2026-01-01 00:00:00'` became
+ `dt_epoch >= '20260101'`, and a January 15 row keyed `2026-01-15` sorts
+ below that string, so the chart dropped a row the filter keeps.
+
+ The `datetime` goes to the probe unchanged, which is what already happens
+ for every temporal column carrying no format -- `_engine_literal_resolution`
+ then widens the bound for whatever the engine's own literal throws away.
+ """
+ table = _table()
+ table.database.extra = json.dumps(
+ {"python_date_format_by_column_name": {"event_time": "%Y%m%d"}}
+ )
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1, 2]) as probe:
+ _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ )
+
+ assert probe.call_args.args[-1] == [datetime(2026, 1, 1), datetime(2026, 2, 1)]
+
+
+def test_the_probe_rounds_outward_when_the_engine_drops_subseconds(
+ app: Flask,
+) -> None:
+ """
+ SQLite renders a timestamp with ``timespec="seconds"``, so the real lower
+ bound is floored while the probe was handed the full precision. That makes
+ the mirror *narrower* than the predicate it stands in for, and narrower
+ means it drops rows the filter keeps -- a row at ``.250000`` matches
+ ``event_time >= '2026-01-01 00:00:00'`` but not a mirror derived from
+ ``.500000``.
+
+ Rounding outward is never narrower. What it moves is the *value* the probe
+ is handed, which is what the assertion below pins -- every mirrored upper
+ bound is inclusive either way, see `mirror_operator`.
+ """
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1, 2]) as probe:
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1, 0, 0, 0, 500000),
+ to_dttm=datetime(2026, 2, 1, 0, 0, 0, 500000),
+ )
+
+ assert probe.call_args.args[-1] == [
+ datetime(2026, 1, 1, 0, 0, 0),
+ datetime(2026, 2, 1, 0, 0, 1),
+ ]
+ assert "dt_epoch <= 2" in sql
+
+
+def test_the_probe_rounds_outward_on_a_date_column_too(app: Flask) -> None:
+ """
+ The truncation test cannot be "does this render the same as the bound
+ truncated to the second". SQLite renders a DATE column at exactly midnight
+ as a bare date, so truncating a `.500000` bound crosses a *formatting*
+ boundary as well as a precision one: the two texts differ for a reason that
+ has nothing to do with precision, and the truncation that is really
+ happening goes unnoticed. Two probes that both carry a sub-second part see
+ it.
+ """
+ table = _table(mapped_column="event_date", main_dttm_col="event_date")
+ table.columns.append(
+ TableColumn(column_name="event_date", is_dttm=True, type="DATE")
+ )
+ table.columns[-1].partition_value_transform = "unix_timestamp(:value)"
+ table.columns[-1].partition_transform_is_monotonic = True
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1, 2]) as probe:
+ _query(
+ table,
+ granularity="event_date",
+ from_dttm=datetime(2026, 1, 1, 0, 0, 0, 500000),
+ to_dttm=datetime(2026, 2, 1, 0, 0, 0, 500000),
+ )
+
+ assert probe.call_args.args[-1] == [
+ datetime(2026, 1, 1, 0, 0, 0),
+ datetime(2026, 2, 1, 0, 0, 1),
+ ]
+
+
+def test_the_probe_widens_to_the_day_when_the_engine_drops_the_time(
+ app: Flask,
+) -> None:
+ """
+ Presto, Trino, BigQuery and some two dozen other specs render a DATE bound
+ as `dttm.date().isoformat()`, so a 10:00 lower bound reaches the engine as
+ `DATE '2026-01-01'` while the probe was handed 10:00. A Jan-1 row then has
+ `dt_epoch = T(DATE '2026-01-01')`, which satisfies the real predicate and
+ *fails* the mirror -- the whole first day is dropped.
+
+ Rounding to the second cannot fix this: there is no sub-second part to
+ floor, and flooring one would leave 10:00 exactly where it was.
+ """
+ table = _table(mapped_column="event_date", main_dttm_col="event_date")
+ table.columns.append(
+ TableColumn(column_name="event_date", is_dttm=True, type="DATE")
+ )
+ table.columns[-1].partition_value_transform = "unix_timestamp(:value)"
+ table.columns[-1].partition_transform_is_monotonic = True
+
+ with app.app_context():
+ with _rendering_dates_like_presto(table):
+ with patch(PROBE, return_value=[1, 2]) as probe:
+ sql = _query(
+ table,
+ granularity="event_date",
+ from_dttm=datetime(2026, 1, 1, 10, 0),
+ to_dttm=datetime(2026, 1, 2, 10, 0),
+ )
+
+ assert probe.call_args.args[-1] == [
+ datetime(2026, 1, 1, 0, 0),
+ datetime(2026, 1, 3, 0, 0),
+ ]
+ assert "dt_epoch <= 2" in sql
+
+
+def test_the_probe_widens_to_the_day_on_a_date_column_not_flagged_temporal(
+ app: Flask,
+) -> None:
+ """
+ `get_time_filter` renders a bound through `convert_dttm` for a DATE column
+ whether or not the owner ticked "Is temporal", so an unflagged DATE column
+ still compares `DATE '2026-01-01'` for a 10:00 bound. Keying the resolution
+ check on `is_dttm` alone handed the probe 10:00 there, and the mirror
+ dropped the first day.
+ """
+ table = _table(mapped_column="event_date", main_dttm_col="event_date")
+ table.columns.append(
+ TableColumn(column_name="event_date", is_dttm=False, type="DATE")
+ )
+ table.columns[-1].partition_value_transform = "unix_timestamp(:value)"
+ table.columns[-1].partition_transform_is_monotonic = True
+
+ with app.app_context():
+ with _rendering_dates_like_presto(table):
+ with patch(PROBE, return_value=[1, 2]) as probe:
+ _query(
+ table,
+ granularity="event_date",
+ from_dttm=datetime(2026, 1, 1, 10, 0),
+ to_dttm=datetime(2026, 1, 2, 10, 0),
+ )
+
+ assert probe.call_args.args[-1] == [
+ datetime(2026, 1, 1, 0, 0),
+ datetime(2026, 1, 3, 0, 0),
+ ]
+
+
+def test_a_day_resolution_bound_already_at_midnight_is_left_alone(
+ app: Flask,
+) -> None:
+ """
+ Widening is outward-only, so a bound that already sits on the day boundary
+ needs nothing done to it -- and the upper bound must not be pushed out a
+ whole extra day for no reason.
+ """
+ table = _table(mapped_column="event_date", main_dttm_col="event_date")
+ table.columns.append(
+ TableColumn(column_name="event_date", is_dttm=True, type="DATE")
+ )
+ table.columns[-1].partition_value_transform = "unix_timestamp(:value)"
+ table.columns[-1].partition_transform_is_monotonic = True
+
+ with app.app_context():
+ with _rendering_dates_like_presto(table):
+ with patch(PROBE, return_value=[1, 2]) as probe:
+ _query(
+ table,
+ granularity="event_date",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ )
+
+ assert probe.call_args.args[-1] == [
+ datetime(2026, 1, 1, 0, 0),
+ datetime(2026, 2, 1, 0, 0),
+ ]
+
+
+def test_an_equality_is_not_mirrored_when_the_engine_drops_the_time(
+ app: Flask,
+) -> None:
+ """
+ An ungrained temporal equality -- what drill-to-detail builds -- compares
+ `event_date = DATE '2026-01-01'` on such an engine, so a mirror probed with
+ 10:00 asks for a key no row holds. These entries are AND-ed onto the query,
+ so unlike a range there is nowhere to widen to: the only safe answer is to
+ emit no mirror and lose the pruning.
+ """
+ table = _table(mapped_column="event_date", main_dttm_col="event_date")
+ table.columns.append(
+ TableColumn(column_name="event_date", is_dttm=True, type="DATE")
+ )
+ table.columns[-1].partition_value_transform = "unix_timestamp(:value)"
+ table.columns[-1].partition_transform_is_monotonic = True
+
+ with app.app_context():
+ with _rendering_dates_like_presto(table):
+ with patch(PROBE, return_value=[1]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_date",
+ "op": FilterOperator.EQUALS.value,
+ "val": datetime(2026, 1, 1, 10, 0),
+ }
+ ],
+ )
+
+ probe.assert_not_called()
+ assert "dt_epoch" not in sql
+
+
+def test_an_equality_at_midnight_still_mirrors_on_a_date_column(
+ app: Flask,
+) -> None:
+ """
+ The guard above is about *lost* precision, not about DATE columns: at
+ midnight the engine's literal and the probe's value agree, so the mirror is
+ exact and the pruning is kept.
+ """
+ table = _table(mapped_column="event_date", main_dttm_col="event_date")
+ table.columns.append(
+ TableColumn(column_name="event_date", is_dttm=True, type="DATE")
+ )
+ table.columns[-1].partition_value_transform = "unix_timestamp(:value)"
+ table.columns[-1].partition_transform_is_monotonic = True
+
+ with app.app_context():
+ with _rendering_dates_like_presto(table):
+ with patch(PROBE, return_value=[1767225600]):
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_date",
+ "op": FilterOperator.EQUALS.value,
+ "val": datetime(2026, 1, 1),
+ }
+ ],
+ )
+
+ assert "dt_epoch = 1767225600" in sql
+
+
+def test_the_probe_keeps_full_precision_on_an_engine_that_does_not_truncate(
+ app: Flask,
+) -> None:
+ """
+ The widening is detected, not enumerated per engine: an engine whose
+ literal carries the sub-second part needs no rounding, and rounding anyway
+ would scan partitions for no reason.
+ """
+ table = _table()
+
+ with app.app_context():
+ with patch.object(
+ table.database.db_engine_spec,
+ "convert_dttm",
+ classmethod(lambda cls, target_type, dttm, db_extra=None: repr(dttm)),
+ ):
+ with patch(PROBE, return_value=[1, 2]) as probe:
+ _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1, 0, 0, 0, 500000),
+ to_dttm=datetime(2026, 2, 1, 0, 0, 0, 500000),
+ )
+
+ assert probe.call_args.args[-1] == [
+ datetime(2026, 1, 1, 0, 0, 0, 500000),
+ datetime(2026, 2, 1, 0, 0, 0, 500000),
+ ]
+
+
+# ---------------------------------------------------------------------------
+# The value the engine actually compares
+# ---------------------------------------------------------------------------
+
+
+def test_a_string_equality_carrying_a_time_does_not_mirror_on_a_date_column(
+ app: Flask,
+) -> None:
+ """
+ A simple filter arrives as the text the chart author typed, not as a
+ `datetime`: `filter_values_handler` rewrites only an all-digit value, which
+ it reads as epoch milliseconds. On a DATE column the engine compares that
+ text on its date part alone, so the filter keeps the whole of 2026-01-01
+ while a mirror probed at 10:00 asks for a key no row holds.
+
+ The `datetime` form of this has been covered since the day resolution was
+ detected at all -- see
+ `test_an_equality_is_not_mirrored_when_the_engine_drops_the_time`. The
+ string form is the one a user can actually produce, and it was the one that
+ dropped rows.
+ """
+ table = _mapped_date_table()
+
+ with app.app_context():
+ with _rendering_dates_like_presto(table):
+ with patch(PROBE, return_value=[1]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_date",
+ "op": FilterOperator.EQUALS.value,
+ "val": "2026-01-01 10:00:00",
+ }
+ ],
+ )
+
+ probe.assert_not_called()
+ assert "dt_epoch" not in sql
+ assert "event_date = '2026-01-01 10:00:00'" in sql
+
+
+@pytest.mark.parametrize(
+ "values",
+ [
+ ["2026-01-01 10:00:00", "2026-01-02 09:00:00"],
+ ["2026-01-01", "2026-01-02 09:00:00"],
+ ],
+ ids=["every-member-coarse", "one-member-coarse"],
+)
+def test_a_string_in_list_declines_entire_when_any_member_carries_a_time(
+ app: Flask, values: list[str]
+) -> None:
+ """
+ An `IN` list is mirrored as one predicate, so a member the engine compares
+ more coarsely than the mirror can be built from is the whole list's
+ problem. Mirroring only the members that do work would be *narrower* than
+ the filter -- the same narrowing the `None`-member guard refuses -- so the
+ list declines entire.
+ """
+ table = _mapped_date_table()
+
+ with app.app_context():
+ with _rendering_dates_like_presto(table):
+ with patch(PROBE, return_value=[1, 2]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_date",
+ "op": FilterOperator.IN.value,
+ "val": values,
+ }
+ ],
+ )
+
+ probe.assert_not_called()
+ assert "dt_epoch" not in sql
+
+
+def test_a_string_in_list_of_dates_mirrors_element_wise(app: Flask) -> None:
+ """
+ The guard above is about a *time of day*, not about `IN` on a DATE column:
+ every member at the start of its day is compared in full, so the list
+ mirrors and the pruning is kept.
+ """
+ table = _mapped_date_table()
+
+ with app.app_context():
+ with _rendering_dates_like_presto(table):
+ with patch(PROBE, return_value=[1767225600, 1767312000]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_date",
+ "op": FilterOperator.IN.value,
+ "val": ["2026-01-01", "2026-01-02"],
+ }
+ ],
+ )
+
+ assert probe.call_args.args[-1] == ["2026-01-01", "2026-01-02"]
+ assert "dt_epoch IN (1767225600, 1767312000)" in sql
+
+
+def test_a_string_lower_bound_rounds_outward_on_a_date_column(app: Flask) -> None:
+ """
+ A bound has somewhere to widen to where an equality does not. The engine
+ compares `event_date >= DATE '2026-01-05'`, so every row on 2026-01-05
+ satisfies the filter and the mirror has to admit that whole day -- which is
+ what moving the bound back to midnight does.
+ """
+ table = _mapped_date_table()
+
+ with app.app_context():
+ with _rendering_dates_like_presto(table):
+ with patch(PROBE, return_value=[1767571200]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_date",
+ "op": FilterOperator.GREATER_THAN_OR_EQUALS.value,
+ "val": "2026-01-05 10:00:00",
+ }
+ ],
+ )
+
+ assert probe.call_args.args[-1] == [datetime(2026, 1, 5, 0, 0)]
+ assert "dt_epoch >= 1767571200" in sql
+
+
+def test_a_string_upper_bound_rounds_outward_on_a_date_column(app: Flask) -> None:
+ """
+ The upper bound moves the other way, and by a whole day: the engine compares
+ `event_date < DATE '2026-01-20'`, and the mirror must not exclude the
+ partition the boundary rows live in.
+ """
+ table = _mapped_date_table()
+
+ with app.app_context():
+ with _rendering_dates_like_presto(table):
+ with patch(PROBE, return_value=[1768953600]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_date",
+ "op": FilterOperator.LESS_THAN.value,
+ "val": "2026-01-20 10:00:00",
+ }
+ ],
+ )
+
+ assert probe.call_args.args[-1] == [datetime(2026, 1, 21, 0, 0)]
+ assert "dt_epoch <= 1768953600" in sql
+
+
+def test_a_date_only_string_equality_still_mirrors_unchanged(app: Flask) -> None:
+ """
+ A value the engine compares in full is left exactly as it arrived, down to
+ the type the probe binds: reading the string back into an instant would
+ change the bind type and the probe's cache key on a query that was already
+ correct, for no gain at all.
+ """
+ table = _mapped_date_table()
+
+ with app.app_context():
+ with _rendering_dates_like_presto(table):
+ with patch(PROBE, return_value=[1767225600]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_date",
+ "op": FilterOperator.EQUALS.value,
+ "val": "2026-01-01",
+ }
+ ],
+ )
+
+ assert probe.call_args.args[-1] == ["2026-01-01"]
+ assert "dt_epoch = 1767225600" in sql
+
+
+def test_a_datetime_lower_bound_rounds_outward_instead_of_declining(
+ app: Flask,
+) -> None:
+ """
+ A `datetime` bound used to reach the same guard an equality does and
+ decline, which left a string and the `datetime` denoting the same instant
+ mirroring differently -- the asymmetry that let the string case above go
+ unnoticed. A bound widens whichever shape it arrived in.
+ """
+ table = _mapped_date_table()
+
+ with app.app_context():
+ with _rendering_dates_like_presto(table):
+ with patch(PROBE, return_value=[1767571200]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_date",
+ "op": FilterOperator.GREATER_THAN_OR_EQUALS.value,
+ "val": datetime(2026, 1, 5, 10, 0),
+ }
+ ],
+ )
+
+ assert probe.call_args.args[-1] == [datetime(2026, 1, 5, 0, 0)]
+ assert "dt_epoch >= 1767571200" in sql
+
+
+def test_a_string_filter_value_is_untouched_on_a_full_precision_engine(
+ app: Flask,
+) -> None:
+ """
+ The widening is detected, not enumerated per engine. An engine whose
+ literal carries the whole value needs none of this, and substituting an
+ instant for the text would move the probe off the cache entry every
+ already-correct query shares.
+ """
+ table = _table()
+
+ with app.app_context():
+ with patch.object(
+ table.database.db_engine_spec,
+ "convert_dttm",
+ classmethod(lambda cls, target_type, dttm, db_extra=None: repr(dttm)),
+ ):
+ with patch(PROBE, return_value=[1]) as probe:
+ _query(
+ table,
+ filter=[
+ {
+ "col": "event_time",
+ "op": FilterOperator.GREATER_THAN_OR_EQUALS.value,
+ "val": "2026-01-05 10:00:00",
+ }
+ ],
+ )
+
+ assert probe.call_args.args[-1] == ["2026-01-05 10:00:00"]
+
+
+def test_a_string_in_list_is_untouched_on_a_full_precision_engine(
+ app: Flask,
+) -> None:
+ """The `IN` counterpart: the new element-wise routing disturbs nothing."""
+ table = _table()
+
+ with app.app_context():
+ with patch.object(
+ table.database.db_engine_spec,
+ "convert_dttm",
+ classmethod(lambda cls, target_type, dttm, db_extra=None: repr(dttm)),
+ ):
+ with patch(PROBE, return_value=[1, 2]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_time",
+ "op": FilterOperator.IN.value,
+ "val": ["2026-01-01 10:00:00", "2026-01-02 09:00:00"],
+ }
+ ],
+ )
+
+ assert probe.call_args.args[-1] == [
+ "2026-01-01 10:00:00",
+ "2026-01-02 09:00:00",
+ ]
+ assert "dt_epoch IN (1, 2)" in sql
+
+
+@pytest.mark.parametrize(
+ "operator, value",
+ [
+ (FilterOperator.EQUALS.value, "07/06/2026 10:08:11"),
+ (FilterOperator.EQUALS.value, "2026/07/06 10:08:11"),
+ (FilterOperator.EQUALS.value, "July 6 2026 10:08:11"),
+ (FilterOperator.GREATER_THAN_OR_EQUALS.value, "07/05/2026 10:00:00"),
+ (FilterOperator.LESS_THAN.value, "07/20/2026"),
+ # The date-only form, which mirrored correctly by luck -- it denotes
+ # midnight, so probing the whole instant and probing the date agreed.
+ # It declines with the rest, because telling July 6 from June 7 is the
+ # guess that started this.
+ (FilterOperator.EQUALS.value, "06/07/2026"),
+ ],
+ ids=[
+ "us-equality",
+ "ymd-slashes",
+ "month-name",
+ "lower-bound",
+ "upper-bound",
+ "date-only",
+ ],
+)
+def test_an_unreadable_string_does_not_mirror_on_a_date_column(
+ app: Flask, operator: str, value: str
+) -> None:
+ """
+ Only ISO 8601 is read, because it is the one format whose meaning is not a
+ guess: ``'06/07/2026'`` as July 6 or as June 7 is a coin flip, and a mirror
+ derived from the wrong one is the silent narrowing all of this is here to
+ prevent.
+
+ Passing such a value through to the probe was the same narrowing by another
+ door. Postgres casts ``'07/06/2026 10:08:11'`` to a DATE and keeps the whole
+ of July 6, while the probe evaluated the transform at 10:08:11 and asked for
+ ``day_epoch = 1783332491`` -- a key no row holds. The chart returned 0 rows
+ where the filter matched 13, with no error and the pruning glyph still
+ showing.
+
+ A bound declines too, where a readable one widens: rounding outward needs an
+ instant to round, and there is none.
+ """
+ table = _mapped_date_table()
+
+ with app.app_context():
+ with _rendering_dates_like_presto(table):
+ with patch(PROBE, return_value=[1]) as probe:
+ sql = _query(
+ table,
+ filter=[{"col": "event_date", "op": operator, "val": value}],
+ )
+
+ probe.assert_not_called()
+ assert "dt_epoch" not in sql
+ # The filter the author wrote is still there, so the query is correct and
+ # merely unpruned -- the one failure this feature is allowed.
+ assert f"'{value}'" in sql
+
+
+def test_an_unreadable_member_declines_an_in_list_on_a_date_column(
+ app: Flask,
+) -> None:
+ """
+ One member the server cannot place is the whole list's problem, exactly as
+ one carrying a time of day is: dropping just that member mirrors a narrower
+ list than the filter and loses the rows it named.
+ """
+ table = _mapped_date_table()
+
+ with app.app_context():
+ with _rendering_dates_like_presto(table):
+ with patch(PROBE, return_value=[1, 2]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_date",
+ "op": FilterOperator.IN.value,
+ "val": ["2026-07-06", "07/07/2026 09:00:00"],
+ }
+ ],
+ )
+
+ probe.assert_not_called()
+ assert "dt_epoch" not in sql
+
+
+def test_an_unreadable_string_is_left_alone_on_a_full_precision_engine(
+ app: Flask,
+) -> None:
+ """
+ The decline belongs to the coarseness, not to the format. On a TIMESTAMP
+ column the engine compares the whole string the chart author typed, so there
+ is nothing for the server to resolve and the probe is handed the text as it
+ arrived -- which is what keeps the same non-ISO filter working on a
+ timestamp mapped column while it declines on a DATE one.
+ """
+ table = _table()
+
+ with app.app_context():
+ with patch.object(
+ table.database.db_engine_spec,
+ "convert_dttm",
+ classmethod(lambda cls, target_type, dttm, db_extra=None: repr(dttm)),
+ ):
+ with patch(PROBE, return_value=[1783332491]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_time",
+ "op": FilterOperator.EQUALS.value,
+ "val": "07/06/2026 10:08:11",
+ }
+ ],
+ )
+
+ assert probe.call_args.args[-1] == ["07/06/2026 10:08:11"]
+ assert "dt_epoch = 1783332491" in sql
+
+
+def _on_postgres(table: SqlaTable) -> SqlaTable:
+ """
+ Re-point the dataset at Postgres, whose driver over-escapes a backslash.
+
+ SQLAlchemy only learns whether the server honours a backslash escape when
+ the dialect connects, which the probe's dialect never does, so it renders
+ ``a\\b`` as ``'a\\\\b'`` and a server with the standard setting reads four
+ characters. A real backend rather than a patched helper, so the test is
+ tied to what the installed driver actually emits.
+ """
+ table.database.sqlalchemy_uri = "postgresql://user@host/db"
+ return table
+
+
+def test_a_value_the_engine_cannot_read_back_declines_rather_than_mirroring(
+ app: Flask,
+) -> None:
+ """
+ The probe evaluates the transform at a literal, so a value the driver and
+ the engine spell differently would be probed as something nobody filtered
+ on -- and the mirror would ask for a partition key holding none of the rows
+ the filter keeps. Declining costs the query its pruning and nothing else.
+ """
+ table = _on_postgres(
+ _table(
+ transform="lower(:value)",
+ monotonic=False,
+ mapped_column="country",
+ partition_mapped_column="country",
+ partition_column="region_key",
+ )
+ )
+
+ with app.app_context():
+ with patch(PROBE, return_value=["a\\b"]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "country",
+ "op": FilterOperator.EQUALS.value,
+ "val": "a\\b",
+ }
+ ],
+ )
+
+ probe.assert_not_called()
+ assert "region_key" not in sql
+ # The filter the author wrote is untouched, so the query is correct and
+ # merely unpruned.
+ assert "country = 'a" in sql
+
+
+def test_a_member_the_dialect_cannot_write_faithfully_declines_the_whole_list(
+ app: Flask,
+) -> None:
+ """
+ One member is the whole list's problem, exactly as one carrying a UTC
+ offset is: mirroring the rest would be narrower than the filter and would
+ lose the rows it named.
+ """
+ table = _on_postgres(
+ _table(
+ transform="lower(:value)",
+ monotonic=False,
+ mapped_column="country",
+ partition_mapped_column="country",
+ partition_column="region_key",
+ )
+ )
+
+ with app.app_context():
+ with patch(PROBE, return_value=["us", "a\\b"]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "country",
+ "op": FilterOperator.IN.value,
+ "val": ["US", "a\\b"],
+ }
+ ],
+ )
+
+ probe.assert_not_called()
+ assert "region_key" not in sql
+
+
+def test_a_quote_bearing_value_still_mirrors_where_the_engine_reads_it_back(
+ app: Flask,
+) -> None:
+ """
+ And the gate is not a blanket refusal of the character. On SQLite the
+ driver's doubling is the engine's own escape, so the probe asks about the
+ value the filter compares and the mirror stands.
+ """
+ table = _table(
+ transform="lower(:value)",
+ monotonic=False,
+ mapped_column="country",
+ partition_mapped_column="country",
+ partition_column="region_key",
+ )
+
+ with app.app_context():
+ with patch(PROBE, return_value=["o'brien"]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "country",
+ "op": FilterOperator.EQUALS.value,
+ "val": "O'Brien",
+ }
+ ],
+ )
+
+ probe.assert_called_once()
+ assert "region_key = 'o''brien'" in sql
+
+
+def test_an_offset_bearing_bound_declines_rather_than_narrowing(app: Flask) -> None:
+ """
+ Rounding an offset-bearing bound outward would first have to place it in the
+ frame the partition column was written in, and guessing that frame is how a
+ mirror ends up a whole offset narrower than the filter. Declining costs the
+ query its pruning and nothing else.
+ """
+ table = _mapped_date_table()
+
+ with app.app_context():
+ with _rendering_dates_like_presto(table):
+ with patch(PROBE, return_value=[1]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_date",
+ "op": FilterOperator.GREATER_THAN_OR_EQUALS.value,
+ "val": "2026-01-05T10:00:00+02:00",
+ }
+ ],
+ )
+
+ probe.assert_not_called()
+ assert "dt_epoch" not in sql
+
+
+@pytest.mark.parametrize(
+ "operator",
+ [FilterOperator.EQUALS, FilterOperator.GREATER_THAN_OR_EQUALS],
+)
+def test_an_offset_bearing_string_declines_on_a_full_resolution_column(
+ app: Flask, operator: FilterOperator
+) -> None:
+ """
+ An engine that compares the whole instant still does not help a transform
+ that drops the offset. On a TIMESTAMPTZ column with
+ `extract(epoch from CAST(:value AS TIMESTAMP))`, a row at
+ `2026-01-01 00:00:00Z` matches `event_time = '2026-01-01T01:00:00+01:00'`,
+ but the cast discards the `+01:00` and the probe asks for the key an hour
+ later -- so the mirror would exclude the row. Declined like any other
+ offset-bearing value.
+ """
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1767229200]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_time",
+ "op": operator.value,
+ "val": "2026-01-01T01:00:00+01:00",
+ }
+ ],
+ )
+
+ probe.assert_not_called()
+ assert "dt_epoch" not in sql
+
+
+@pytest.mark.parametrize(
+ "native_type, filter_value, probed",
+ [
+ # The engine compares `n = '1.0'` numerically and keeps the row holding
+ # 1, so the probe has to see the 1 the row holds, not the 1.0 typed.
+ ("INTEGER", "1.0", [1]),
+ ("INTEGER", 1.0, [1]),
+ # A non-integral value matches no integer row; nothing to protect.
+ ("INTEGER", 1.5, [1.5]),
+ # A REAL column is left alone: PostgreSQL renders the column's own
+ # value as `'1'` but the literal `1.0` as `'1.0'`, so coercing would
+ # mirror onto a key no matching row holds.
+ ("REAL", 1, [1]),
+ # A DECIMAL's text depends on a scale the spec does not expose.
+ ("DECIMAL", 1, [1]),
+ ],
+)
+def test_a_numeric_equality_is_probed_in_the_column_s_number_type(
+ app: Flask, native_type: str, filter_value: Any, probed: list[Any]
+) -> None:
+ """
+ A transform such as `CAST(:value AS TEXT)` answers differently for `1` and
+ `1.0`, so probing at the number the filter happened to carry -- rather than
+ the one the column stores -- mirrors onto a partition key no matching row
+ holds.
+ """
+ table = _table(partition_column="region_key", mapped_column="n")
+ table.columns.append(TableColumn(column_name="n", type=native_type))
+ table.partition_mapped_column = "n"
+ table.columns[-1].partition_value_transform = "CAST(:value AS TEXT)"
+ table.columns[-1].partition_transform_is_monotonic = False
+
+ with app.app_context():
+ with patch(PROBE, return_value=["1"]) as probe:
+ _query(
+ table,
+ filter=[
+ {
+ "col": "n",
+ "op": FilterOperator.EQUALS.value,
+ "val": filter_value,
+ }
+ ],
+ )
+
+ assert probe.call_args.args[-1] == probed
+ assert [type(value) for value in probe.call_args.args[-1]] == [
+ type(value) for value in probed
+ ]
+
+
+def test_a_non_temporal_string_equality_is_unaffected(app: Flask) -> None:
+ """
+ Every string value is now offered to an ISO parse, so the text mapping most
+ of this file exercises has to come out the other side unchanged: `'US'` does
+ not parse, and a VARCHAR column's `convert_dttm` answers nothing either way.
+ """
+ table = _mapped_country_table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=["us"]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {"col": "country", "op": FilterOperator.EQUALS.value, "val": "US"}
+ ],
+ )
+
+ assert probe.call_args.args[-1] == ["US"]
+ assert "region_key = 'us'" in sql
+
+
+def test_a_rounded_string_bound_dedupes_against_the_time_filter(app: Flask) -> None:
+ """
+ Rounding a string bound outward lands it on the same instant the chart's own
+ time filter already contributed, so the two collapse into one request --
+ which is what the dedupe in `_build_partition_mirror_predicates` promises
+ and what a reader of "View query" expects to see.
+ """
+ table = _mapped_date_table()
+
+ with app.app_context():
+ with _rendering_dates_like_presto(table):
+ with patch(PROBE, return_value=[1767571200, 1768953600]):
+ sql = _query(
+ table,
+ granularity="event_date",
+ from_dttm=datetime(2026, 1, 5),
+ to_dttm=datetime(2026, 1, 20),
+ filter=[
+ {
+ "col": "event_date",
+ "op": FilterOperator.GREATER_THAN_OR_EQUALS.value,
+ "val": "2026-01-05 10:00:00",
+ }
+ ],
+ )
+
+ assert sql.count("dt_epoch >=") == 1
+
+
+def test_one_probe_round_trip_per_query(app: Flask) -> None:
+ """Mirror requests are collected and resolved together, not one at a time."""
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1767225600, 1769904000]) as probe:
+ _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ filter=[
+ {
+ "col": "event_time",
+ "op": FilterOperator.TEMPORAL_RANGE.value,
+ "val": "2026-01-01 : 2026-02-01",
+ }
+ ],
+ )
+
+ probe.assert_called_once()
+
+
+def test_mirrored_predicates_reach_the_series_limit_subquery(app: Flask) -> None:
+ """
+ The mirrored predicate is appended to ``where_clause_and``, which the
+ series-limit subquery reuses -- so pruning applies there too.
+ """
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1767225600, 1769904000]):
+ sql = _query(
+ table,
+ columns=["country"],
+ metrics=["hits"],
+ granularity="event_time",
+ is_timeseries=True,
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ timeseries_limit=5,
+ timeseries_limit_metric="hits",
+ )
+
+ assert sql.count("dt_epoch >= 1767225600") >= 2
+
+
+def _split_series_limit(sql: str) -> tuple[str, str]:
+ """The ranking subquery and the outer query, as separate text."""
+ _, marker, rest = sql.partition("JOIN (SELECT")
+ assert marker, "expected a series-limit subquery"
+ subquery, _, outer = rest.partition(") AS series_limit")
+ return subquery, outer
+
+
+def test_the_series_limit_subquery_mirrors_the_inner_time_window(
+ app: Flask,
+) -> None:
+ """
+ The ranking subquery filters the *inner* window, not the outer one. On a
+ time comparison `processing_time_offsets` shifts `from_dttm`/`to_dttm` to
+ the comparison period and leaves `inner_*` on the original, so an
+ outer-window mirror in the subquery demands partition keys from a period
+ the subquery's own time filter excludes: the ranking comes back empty and
+ the join drops the comparison series entirely.
+ """
+ table = _table()
+ epochs = {
+ datetime(2025, 1, 1): 1735689600,
+ datetime(2025, 2, 1): 1738368000,
+ datetime(2026, 1, 1): 1767225600,
+ datetime(2026, 2, 1): 1769904000,
+ }
+
+ with app.app_context():
+ with patch(
+ PROBE, side_effect=lambda *args, **kwargs: [epochs[v] for v in args[-1]]
+ ):
+ sql = _query(
+ table,
+ columns=["country"],
+ metrics=["hits"],
+ granularity="event_time",
+ is_timeseries=True,
+ from_dttm=datetime(2025, 1, 1),
+ to_dttm=datetime(2025, 2, 1),
+ inner_from_dttm=datetime(2026, 1, 1),
+ inner_to_dttm=datetime(2026, 2, 1),
+ timeseries_limit=5,
+ timeseries_limit_metric="hits",
+ )
+
+ subquery, outer = _split_series_limit(sql)
+
+ # The subquery asks for the window its own time filter describes.
+ assert "dt_epoch >= 1767225600" in subquery
+ assert "dt_epoch >= 1735689600" not in subquery
+
+ # The outer query still asks for the window it was given.
+ assert "dt_epoch >= 1735689600" in outer
+ assert "dt_epoch >= 1767225600" not in outer
+
+
+def test_the_series_limit_prequery_mirrors_the_inner_window(app: Flask) -> None:
+ """
+ The other series-limit branch is already right, for a different reason: it
+ re-enters `query()` with `inner_from_dttm or from_dttm` as its own
+ `from_dttm`, so the mirrors are recomputed for the inner window rather than
+ inherited. Pinned so a future refactor cannot quietly break the half that
+ works.
+ """
+ table = _table()
+ captured: list[dict[str, Any]] = []
+
+ def _capture(query_obj: dict[str, Any]) -> Any:
+ captured.append(query_obj)
+ return MagicMock(df=pd.DataFrame({"country": []}))
+
+ with app.app_context():
+ with patch.object(table.database.db_engine_spec, "allows_joins", False):
+ with patch(PROBE, return_value=[1767225600, 1769904000]):
+ with patch.object(type(table), "query", side_effect=_capture):
+ _query(
+ table,
+ columns=["country"],
+ metrics=["hits"],
+ granularity="event_time",
+ is_timeseries=True,
+ from_dttm=datetime(2025, 1, 1),
+ to_dttm=datetime(2025, 2, 1),
+ inner_from_dttm=datetime(2026, 1, 1),
+ inner_to_dttm=datetime(2026, 2, 1),
+ timeseries_limit=5,
+ timeseries_limit_metric="hits",
+ )
+
+ assert captured, "expected a prequery"
+ assert captured[0]["from_dttm"] == datetime(2026, 1, 1)
+ assert captured[0]["to_dttm"] == datetime(2026, 2, 1)
+
+
+def test_one_probe_round_trip_when_both_windows_match(app: Flask) -> None:
+ """
+ The inner sink is collected unconditionally, but building its predicates a
+ second time would cost a second probe round trip. Every query that is not a
+ time comparison asks for the same thing twice, so the result is reused.
+ """
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1767225600, 1769904000]) as probe:
+ _query(
+ table,
+ columns=["country"],
+ metrics=["hits"],
+ granularity="event_time",
+ is_timeseries=True,
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ timeseries_limit=5,
+ timeseries_limit_metric="hits",
+ )
+
+ probe.assert_called_once()
+
+
+def test_the_series_limit_subquery_keeps_row_level_security(app: Flask) -> None:
+ """
+ The subquery takes a snapshot of `where_clause_and` from before the mirrors
+ are appended. That snapshot has to be taken *after* row level security and
+ the extras `where` go on, or swapping the mirrors would quietly drop them
+ from the ranking subquery -- which for row level security would be a
+ security bug, not a pruning one.
+ """
+ table = _table()
+
+ with app.app_context():
+ with patch.object(
+ type(table),
+ "get_sqla_row_level_filters",
+ return_value=[sa.text("country = 'US'")],
+ ):
+ with patch(PROBE, return_value=[1767225600, 1769904000]):
+ sql = _query(
+ table,
+ columns=["country"],
+ metrics=["hits"],
+ granularity="event_time",
+ is_timeseries=True,
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ timeseries_limit=5,
+ timeseries_limit_metric="hits",
+ extras={"where": "region_key <> 'x'"},
+ )
+
+ subquery, _ = _split_series_limit(sql)
+ assert "country = 'US'" in subquery
+ assert "region_key <> 'x'" in subquery
+
+
+def _mapped_country_table() -> SqlaTable:
+ """A string-column mapping: ``country`` onto ``region_key``."""
+ return _table(
+ transform="lower(:value)",
+ monotonic=False,
+ mapped_column="country",
+ partition_mapped_column="country",
+ partition_column="region_key",
+ )
+
+
+def test_string_equality_does_not_mirror_on_a_case_insensitive_engine(
+ app: Flask,
+) -> None:
+ """
+ `col = v` mirrors onto `partition_col = T(v)` on the strength of `col = v`
+ implying `T(col) = T(v)` -- true of value equality, false of SQL equality
+ under any comparison that is not byte-exact. With a case-insensitive
+ collation a stored `country` of `'us'` satisfies a filter for `'US'` while
+ the mirror `region_key = 'us'` is derived from `'US'` and excludes the row,
+ so the chart loses it with nothing to indicate why.
+ """
+ table = _mapped_country_table()
+
+ with app.app_context():
+ with patch.object(
+ table.database.db_engine_spec, "binary_string_comparison", False
+ ):
+ with patch(PROBE, return_value=["us"]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "country",
+ "op": FilterOperator.EQUALS.value,
+ "val": "US",
+ }
+ ],
+ )
+
+ assert "region_key" not in sql
+ assert "country = 'US'" in sql
+ probe.assert_not_called()
+
+
+def test_string_equality_still_mirrors_on_a_byte_exact_engine(app: Flask) -> None:
+ """
+ The gate must not cost the feature its second canonical mapping on the
+ engines it exists for, all of which compare text byte-exactly.
+ """
+ table = _mapped_country_table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=["us"]):
+ sql = _query(
+ table,
+ filter=[
+ {"col": "country", "op": FilterOperator.EQUALS.value, "val": "US"}
+ ],
+ )
+
+ assert "region_key = 'us'" in sql
+
+
+def test_a_numeric_mapped_column_is_unaffected_by_the_collation_gate(
+ app: Flask,
+) -> None:
+ """Numeric comparison is exact on every engine."""
+ table = _table(
+ transform="CAST(:value AS STRING)",
+ monotonic=False,
+ mapped_column="dt_epoch",
+ partition_mapped_column="dt_epoch",
+ partition_column="region_key",
+ )
+
+ with app.app_context():
+ with patch.object(
+ table.database.db_engine_spec, "binary_string_comparison", False
+ ):
+ with patch(PROBE, return_value=["17"]):
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "dt_epoch",
+ "op": FilterOperator.EQUALS.value,
+ "val": 17,
+ }
+ ],
+ )
+
+ assert "region_key = '17'" in sql
+
+
+def test_the_summary_withdraws_the_operators_the_query_path_withdraws(
+ app: Flask,
+) -> None:
+ """
+ The glyph reads `mirrorable_operators` off this summary, so the gate has to
+ reach it or Explore would mark a filter chip as pruned while the generated
+ SQL carries no partition predicate -- which is the whole class of bug the
+ indicator work has been closing.
+ """
+ table = _mapped_country_table()
+
+ with app.app_context():
+ with patch.object(
+ table.database.db_engine_spec, "binary_string_comparison", False
+ ):
+ summary = table.partition_filter_mapping_summary
+
+ assert summary is not None
+ assert summary["mirrorable_operators"] == []
+
+ unguarded = table.partition_filter_mapping_summary
+
+ assert unguarded is not None
+ assert unguarded["mirrorable_operators"] == ["==", "IN"]
+
+
+def test_extra_cache_keys_include_the_mapping(app: Flask) -> None:
+ """
+ The mapping changes the SQL a cached chart result came from, so it has to
+ participate in the chart-data cache key or a mapping fix leaves stale pruned
+ results behind.
+ """
+ table = _table()
+
+ with app.app_context():
+ keys = table.get_extra_cache_keys({})
+
+ assert any("dt_epoch" in str(key) for key in keys)
Review Comment:
This only asserts that some key mentions `dt_epoch`, so dropping `mapping.value_transform` and `mapping.is_monotonic` from the `partition_filter_mapping` tuple in `get_extra_cache_keys` leaves it green. If the monotonic declaration flips without the key changing, a cached chart keeps the old pruned-vs-unpruned SQL result. Could this build the same table twice, flipping only `partition_transform_is_monotonic` (and separately only the transform text), and assert the key changes each time while an unchanged table stays stable?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4341450065
##########
superset/datasets/schemas.py:
##########
@@ -504,6 +542,8 @@ def validate_unique_child_uuids(self, data: dict[str, Any], **kwargs: Any) -> No
external_url = fields.String(allow_none=True)
normalize_columns = fields.Boolean(load_default=False)
always_filter_main_dttm = fields.Boolean(load_default=False)
+ partition_column = fields.String(allow_none=True)
Review Comment:
These two import fields have no length limit, while the POST/PUT schemas cap the same fields at 250 and both model columns are `String(250)`. A v1 bundle with a 251-character `partition_column` passes schema validation and then fails at persistence on a database that enforces `VARCHAR(250)`, so the import surfaces as a server error instead of a field-level validation message. Can these use the same `Length(0, 250)` validator?
##########
superset/models/helpers.py:
##########
@@ -4449,36 +4558,777 @@ def dttm_sql_literal(self, dttm: datetime, col: "TableColumn") -> str:
return f"""'{dttm.strftime("%Y-%m-%d %H:%M:%S.%f")}'"""
- def get_time_filter( # pylint: disable=too-many-arguments # noqa: C901
+ def _mirror_probe_value(self, dttm: datetime, col: Optional["TableColumn"]) -> Any:
+ """
+ ``dttm`` in the mapped column's own stored representation.
+
+ The predicate this mirror stands in for compares the column against
+ `dttm_sql_literal(dttm, col)`, so the transform has to be probed with
+ the same value. On a column stored as an epoch integer, ``T`` is a
+ function of an integer: probing it with a `datetime` either returns
+ something unrelated to the partition keys or raises, and a raise costs
+ the dataset its pruning silently.
+
+ Only the ``python_date_format`` branches of `dttm_sql_literal` are
+ reproduced, because only those produce a *value*. `convert_dttm` yields
+ engine-specific SQL text, which cannot be bound as a parameter; its own
+ divergence from the probe is handled by widening the bounds instead
+ (`_engine_literal_resolution`).
+
+ In `dttm_sql_literal`'s own order, though: it asks ``convert_dttm``
+ first and reaches the format only when the engine answers nothing. A
+ column can carry both -- a TIMESTAMP with a ``%Y%m%d``
+ ``python_date_format``, or an entry in
+ ``python_date_format_by_column_name`` -- and applying the format
+ unconditionally probed a value the real predicate never compares.
+ ``event_time >= '2026-01-01 00:00:00'`` mirrored as
+ ``partition_col >= '20260101'``, and a January 15 row keyed
+ ``2026-01-15`` sorts below that string, so the chart lost a row the
+ filter keeps.
+
+ Where the engine does answer, the `datetime` is returned unchanged and
+ the widening path takes over -- which is exactly what already happens
+ for every temporal column that carries no format at all.
+ """
+ if col is None:
+ return dttm
+
+ if col.type and self.db_engine_spec.convert_dttm(
+ col.type, dttm, db_extra=self.db_extra
+ ):
+ # The format is unreachable in `dttm_sql_literal` for this column,
+ # so reproducing it here would describe a different bound.
+ return dttm
+
+ tf = col.python_date_format
+ if not tf and self.db_extra:
+ tf = self.db_extra.get("python_date_format_by_column_name", {}).get(
+ col.column_name
+ )
+ if not tf:
+ return dttm
+
+ if tf in EPOCH_FORMATS:
+ dttm_tz_aware = dttm
+ if dttm_tz_aware.tzinfo is None:
+ dttm_tz_aware = dttm_tz_aware.replace(tzinfo=timezone.utc)
+ return int(dttm_tz_aware.timestamp()) * EPOCH_FORMATS[tf]
+ return dttm.strftime(tf)
+
+ def _engine_literal_resolution(
+ self, dttm: datetime, col: Optional["TableColumn"]
+ ) -> LiteralResolution:
+ """
+ How much of ``dttm`` survives into this engine's literal for ``col``.
+
+ The real predicate compares `dttm_sql_literal(dttm, col)`, so whatever
+ that literal throws away is a bound the engine never sees. A mirror
+ derived from the full precision then describes a *narrower* range than
+ the predicate it stands in for -- and narrower means it drops rows the
+ filter keeps.
+
+ Two things get thrown away in practice:
+
+ - the sub-second part. SQLite renders a timestamp with
+ ``timespec="seconds"``.
+ - the time of day entirely. Every engine spec with a ``types.Date``
+ branch renders ``dttm.date().isoformat()``, so Presto, Trino,
+ BigQuery and some two dozen others answer `DATE '2026-01-01'` for a
+ bound of 10:00 -- and `T(DATE '2026-01-01')` is below the mirror's
+ own lower bound, so the whole first day is dropped.
+
+ Detected rather than enumerated per engine, because the branch depends
+ on the column's type as well as the spec: instants differing only in the
+ part under test render as the same text exactly when the engine has
+ thrown that part away.
+
+ The day test uses two fixed times of day rather than ``dttm`` and one
+ alternative, so a bound that happens to sit on the hour the alternative
+ uses cannot read as "no time at all". Neither probe sits at midnight on
+ purpose: SQLite renders a DATE column at exactly midnight as a bare
+ date, so a midnight probe would differ from its alternative for a
+ reason that has nothing to do with resolution.
+
+ Likewise both sub-second probes carry a non-zero remainder. Comparing
+ against ``dttm`` truncated to the second looks like the obvious test and
+ is wrong for the same formatting-boundary reason.
+
+ A non-temporal column has no answer here, and asking anyway gets a wrong
+ one. SQLite's ``convert_dttm`` renders for ``types.String`` as well as
+ for the date types, so a ``VARCHAR`` mapped column reads as
+ second-resolution -- and a filter value that happens to *look* like an
+ instant then has its bound rounded as though the engine had truncated
+ it. On a VARCHAR ``code`` mapped onto a VARCHAR ``p`` by ``:value``,
+ ``code < '2026-07-06T10:08:11.500000'`` was mirrored as
+ ``p <= '2026-07-06 10:08:12.000000'``; a space sorts before ``T``, so a
+ row holding ``2026-07-06T09:00:00`` fell outside the mirror while
+ matching the filter.
+
+ The guard lives here rather than in each caller so this and
+ `_column_literal_resolution` cannot disagree about which column is
+ coarse -- which is the same reason that helper delegates to this one.
+
+ "Temporal" is the column's generic type, not just its ``is_dttm`` flag.
+ `get_time_filter` renders a bound through ``convert_dttm`` for any
+ ``DATE`` column, flagged or not, so a ``DATE`` column left unflagged
+ still compares a bare day -- and skipping the resolution check there
+ would hand the probe 10:00 for a bound the engine reads as midnight.
+ """
+ if col is None or not col.type or col.type_generic != GenericDataType.TEMPORAL:
+ return LiteralResolution.FULL
+
+ def render(moment: datetime) -> Optional[str]:
+ return self.db_engine_spec.convert_dttm(
+ col.type, moment, db_extra=self.db_extra
+ )
+
+ try:
+ early = render(dttm.replace(hour=1, minute=2, second=3, microsecond=444444))
+ late = render(
+ dttm.replace(hour=22, minute=33, second=44, microsecond=555555)
+ )
+ if early is not None and early == late:
+ return LiteralResolution.DAY
+
+ # Flooring to the second is a no-op on a bound that has no
+ # sub-second part, so there is nothing to detect.
+ if not dttm.microsecond:
+ return LiteralResolution.FULL
+
+ first = render(dttm.replace(microsecond=111111))
+ second = render(dttm.replace(microsecond=222222))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return LiteralResolution.FULL
+
+ if first is not None and first == second:
+ return LiteralResolution.SECOND
+ return LiteralResolution.FULL
+
+ def _round_bounds_outward(
self,
- time_col: "TableColumn",
+ start_dttm: Optional[datetime],
+ end_dttm: Optional[datetime],
+ col: Optional["TableColumn"],
+ ) -> tuple[Optional[datetime], Optional[datetime]]:
+ """
+ The bounds widened to whatever the engine's literal actually resolves to.
+
+ Rounding outward is never narrower than the predicate being mirrored,
+ which is the only property the mirror has to hold.
+ """
+ resolutions = {
+ self._engine_literal_resolution(bound, col)
+ for bound in (start_dttm, end_dttm)
+ if bound is not None
+ }
+
+ if LiteralResolution.DAY in resolutions:
+ # The engine compares a bare date, so the real predicate's lower
+ # bound is the start of that day and its upper bound admits the
+ # whole of the day before. Anything finer excludes rows it keeps.
+ if start_dttm is not None:
+ start_dttm = start_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ )
+ if end_dttm is not None and end_dttm != end_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ ):
+ end_dttm = end_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ ) + timedelta(days=1)
+ elif LiteralResolution.SECOND in resolutions:
+ if start_dttm is not None:
+ start_dttm = start_dttm.replace(microsecond=0)
+ if end_dttm is not None and end_dttm.microsecond:
+ end_dttm = end_dttm.replace(microsecond=0) + timedelta(seconds=1)
+
+ return start_dttm, end_dttm
+
+ def _literal_is_coarser_than(
+ self, dttm: datetime, col: Optional["TableColumn"]
+ ) -> bool:
+ """
+ Whether the engine's literal for ``dttm`` throws away part of it.
+
+ Unlike a range, an equality cannot be widened outward, so the only safe
+ answer when the engine compares less than the full value is to decline
+ the mirror.
+ """
+ resolution = self._engine_literal_resolution(dttm, col)
+ if resolution is LiteralResolution.DAY:
+ return dttm != dttm.replace(hour=0, minute=0, second=0, microsecond=0)
+ if resolution is LiteralResolution.SECOND:
+ return bool(dttm.microsecond)
+ return False
+
+ def _column_literal_resolution(
+ self, col: Optional["TableColumn"]
+ ) -> LiteralResolution:
+ """
+ How much of *any* value this engine compares on ``col``.
+
+ `_engine_literal_resolution` answers about a particular instant, which
+ is what a mirror derived from one needs. Two callers have no instant to
+ ask about -- the summary the Explore glyph reads, and a filter value
+ `_instant_from_filter_value` cannot read as an instant at all -- and
+ both need the column's own answer. Through one helper so that the glyph
+ and the query path cannot disagree about which column is coarse, which
+ is the same reason `mirrorable_operators` is computed once.
+
+ A non-temporal column has no answer, and asking anyway gets a wrong one:
+ SQLite's ``convert_dttm`` renders for ``types.String`` as well as for the
+ date types, so a reference instant makes a ``VARCHAR`` mapped column look
+ second-resolution -- and ``country = 'US'``, the text half of this
+ feature, reads as a value the engine compares coarsely.
+
+ That guard is `_engine_literal_resolution`'s, not this function's. It
+ used to be here, on the belief that the per-instant callers never met
+ the case because they arrive only with a value that parsed as an
+ instant -- which is untrue of a text column holding ISO-shaped text,
+ where the value parses and the column is still not temporal.
+ """
+ return self._engine_literal_resolution(_RESOLUTION_REFERENCE_INSTANT, col)
+
+ def _round_bound_outward(
+ self,
+ instant: datetime,
+ col: Optional["TableColumn"],
+ *,
+ is_upper: bool,
+ ) -> datetime:
+ """
+ One bound widened to whatever the engine resolves ``col`` to.
+
+ `_round_bounds_outward` answers for a since/until pair, because a time
+ range is the shape it was written for. A single comparison is one end of
+ such a pair with the other end absent, and the widening is per-end
+ already -- a lower bound moves back, an upper bound forward.
+
+ Narrowing the return type is the other half of the point: a bound handed
+ in non-`None` comes back non-`None`, and saying so here saves every
+ caller from re-establishing it.
+ """
+ start_dttm, end_dttm = self._round_bounds_outward(
+ None if is_upper else instant,
+ instant if is_upper else None,
+ col,
+ )
+ rounded = end_dttm if is_upper else start_dttm
+ return rounded if rounded is not None else instant
+
+ def _in_column_number_type(self, value: Any, col: Optional["TableColumn"]) -> Any:
+ """
+ A numeric ``value`` in the number type the mapped column stores.
+
+ The engine compares a number against the column in the column's own
+ domain, so ``n = '1.0'`` on an integer ``n`` matches the row holding
+ ``1``. `filter_values_handler` hands over ``1.0``, though, and a
+ transform whose output depends on the representation --
+ ``CAST(:value AS TEXT)`` answers ``'1.0'`` where the row's key is
+ ``'1'`` -- then mirrors to a partition value no matching row holds.
+ Probing at the value the column would hold keeps ``T(col) = T(v)``.
+
+ Integer columns only. A non-integral value on an integer column is
+ returned unchanged -- it matches no row, so its mirror cannot drop one.
+
+ Nothing is converted for an approximate or exact decimal column, even
+ though ``1`` and ``1.0`` are the same number to a ``REAL``. What the
+ transform sees is the *literal*, and how an engine renders one is not
+ something the engine spec exposes: on PostgreSQL ``CAST(1.0 AS TEXT)``
+ is ``'1.0'`` while the ``REAL`` column holding that value renders as
+ ``'1'``, so coercing the value to ``float`` mirrored onto a partition
+ key no matching row holds -- the same failure this helper exists to
+ stop, in the other direction. A ``DECIMAL`` column says it louder,
+ since its text also depends on a scale the spec does not carry. For
+ both, the rendering stays the owner's assumption, like
+ ``p = T(mapped_col)`` itself.
+ """
+ if (
+ col is None
+ or not col.type
+ or isinstance(value, bool)
+ or not isinstance(value, (int, float, Decimal))
+ ):
+ return value
+ try:
+ column_spec = self.db_engine_spec.get_column_spec(
+ col.type, db_extra=self.db_extra
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return value
+ if column_spec is None:
+ return value
+ sqla_type = column_spec.sqla_type
+ type_class = sqla_type if isinstance(sqla_type, type) else type(sqla_type)
+ if issubclass(type_class, sa.Integer):
+ if isinstance(value, int):
+ return value
+ try:
+ return int(value) if value == int(value) else value
+ except (OverflowError, ValueError):
+ # Infinity and NaN have no integer, and match no integer row.
+ return value
+ return value
+
+ def _mirror_probe_input(
+ self,
+ operator: utils.FilterOperator,
+ value: Any,
+ col: Optional["TableColumn"],
+ ) -> Any:
+ """
+ ``value`` in the representation the mirror may probe the transform at.
+
+ A simple filter on a temporal column carries a *string*.
+ `filter_values_handler` rewrites only an all-digit value, which it reads
+ as epoch milliseconds, so ``'2026-07-06 10:08:11'`` reaches here exactly
+ as the chart author typed it and is bound as text. The engine compares
+ that text against the column under its own cast, and on a ``DATE``
+ column the cast drops the time of day: the filter keeps the whole of
+ 2026-07-06 while a mirror probed at 10:08:11 keeps one instant of it,
+ which is narrower than the predicate it stands in for.
+
+ So the text is read back into the instant it denotes -- the only way
+ `_engine_literal_resolution`, which answers about a `datetime`, reaches
+ a filter value at all -- and where the engine compares less of that
+ instant than the filter carries, what to do about it is a property of
+ the *operator*:
+
+ * a bound rounds outward, through the helper the range collector uses.
+ Reading one extra bucket at the edge is the trade this feature makes
+ everywhere else too -- see `mirror_operator` -- and the original
+ predicate is still in the query to exclude the rows that bucket adds.
+ * an equality, or one member of an ``IN`` list, has nowhere to widen to.
+ These entries are ``AND``-ed onto the query, so "or the day either
+ side" is not something this sink can express, and the request is
+ declined with `_UNMIRRORABLE`. The query is then correct and unpruned,
+ which is the one failure mode this feature is allowed.
+
+ An instant carrying a UTC offset is declined for every operator, a
+ bound included. Rounding one outward would first have to place it in the
+ frame the partition column was written in, and guessing that frame is
+ how a mirror ends up a whole offset narrower than the filter -- see the
+ load-bearing assumption in
+ `superset.connectors.sqla.partition_mapping`.
+
+ A *string* `_instant_from_filter_value` cannot read at all is declined on
+ the same terms, and for the same reason one more step back: there is no
+ instant to round. ``'07/06/2026 10:08:11'`` is not ISO 8601, so the
+ parser leaves it alone -- and Postgres casts that same text to a DATE and
+ keeps the whole of July 6 while the probe, handed the string verbatim,
+ evaluates the transform at 10:08:11 and asks for a partition key no row
+ holds. That is exactly the narrowing the ISO-only parser was written to
+ prevent, reached through a value it declines to read, so the decline has
+ to travel with it. Which costs a non-ISO *date* its pruning too, because
+ telling July 6 from June 7 is the guess that started this.
+
+ Only a string. `_as_probe_input` has already run, so the engine SQL
+ `filter_values_handler` returns for an epoch-millisecond bound arrives
+ here as a `RawProbeValue` rather than text -- and that literal was
+ rendered by the engine at the engine's own resolution, so it is the one
+ thing on this path with nothing left to resolve. The escaping gate has
+ run too, on the value as it arrived; a string this method *returns* is a
+ fresh one, which is why `evaluate_transform` asks again.
+
+ Where the engine compares the whole instant, a string is returned
+ exactly as it arrived -- down to the type the probe binds and the cache
+ key it lands on, because every query that was already correct has to
+ stay byte-for-byte correct. A `datetime` is still converted, which it
+ has always needed: on a column stored as an epoch integer the transform
+ is a function of an integer, and a `datetime` is not the value the real
+ predicate compares.
+ """
+ value = self._in_column_number_type(value, col)
+ parsed = _instant_from_filter_value(value)
+ if parsed is None:
+ if (
+ isinstance(value, str)
+ and self._column_literal_resolution(col) is not LiteralResolution.FULL
+ ):
+ return _UNMIRRORABLE
+ return value
+
+ # Ahead of the full-resolution return: a transform such as
+ # `CAST(:value AS TIMESTAMP)` drops the offset, so even an engine that
+ # compares the whole instant would probe it in the wrong frame. Its own
+ # reason, because mapping a column the engine compares in full -- the
+ # advice the resolution decline carries -- does not help here.
+ if parsed.tzinfo is not None:
+ return _UNMIRRORABLE_OFFSET
+
+ if self._engine_literal_resolution(parsed, col) is LiteralResolution.FULL:
+ return (
+ self._mirror_probe_value(parsed, col)
+ if isinstance(value, datetime)
+ else value
Review Comment:
On an engine that compares the whole instant, a string comparator is probed exactly as it arrived, but the stored column value is rendered in the engine's own spelling. With `t TIMESTAMP`, `p TEXT` and the transform `CAST(:value AS TEXT)`, a row with `t = '2026-07-06 10:08:11'` and `p = '2026-07-06 10:08:11'` matches `t == '2026-07-06T10:08:11'`, but the probe evaluates the cast on the `T` spelling, so the mirror becomes `p = '2026-07-06T10:08:11' OR p IS NULL` and drops that row. Postgres accepts the `T` form on input but prints a space. Should this string go through the same parse-and-reformat as the `datetime` branch, or decline when the transform's result depends on the spelling?
##########
superset-frontend/src/dashboard/components/nativeFilters/FiltersConfigModal/FiltersConfigForm/FiltersConfigForm.tsx:
##########
@@ -1029,6 +1034,41 @@ const FiltersConfigForm = (
};
}, [datasetId, datasourceType]);
+ // A partition-mapped dataset can be large enough that listing a filter's
+ // values without a time range -- a scan of every partition -- times out, so
+ // a new filter starts with a time range on the mapped column, which is
+ // mirrored onto the partition column (see `partitionedTimeRangeColumn` for
+ // when). Applied once per dataset, so an owner who clears it is not
+ // overruled.
+ const partitionDefaultAppliedFor = useRef<number | undefined>();
+ const [partitionTimeRangeDefaulted, setPartitionTimeRangeDefaulted] =
+ useState(false);
+ useEffect(() => {
+ const mappedColumn = partitionedTimeRangeColumn(datasetDetails);
+ if (
+ filterToEdit ||
+ isChartCustomization ||
+ !hasAdditionalFilters ||
+ !datasetId ||
+ !mappedColumn ||
+ partitionDefaultAppliedFor.current === datasetId ||
+ formFilter?.time_range ||
Review Comment:
The seeded `Last week` range is only skipped when `time_range` or `granularity_sqla` is already set, and nothing ties the seeded values to the dataset that produced them. Create a filter on mapped dataset A (it gets `Last week` plus A's time column), then switch to dataset B: the time column is cleared by the column select, but `time_range` stays. This guard then refuses to seed B, and the saved filter has a range with no temporal column, so its value list neither applies the range nor gets a partition predicate (or, for an unmapped B, silently hides older values). Should the seeded range and column be reset when the dataset binding changes?
##########
docs/admin_docs/configuration/partition-filter-mapping.mdx:
##########
@@ -0,0 +1,359 @@
+---
+title: Partition Filter Mapping
+hide_title: true
+sidebar_position: 15
+version: 1
+---
+
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+
+# Partition Filter Mapping
+
+Tables on Hadoop-family engines are often partitioned on a *technical* column — an epoch
+integer, a lowercased region key — that no analyst would ever filter on. Unless a query
+carries a predicate on that column, the engine scans every partition.
+
+Partition filter mapping makes this a dataset setting instead of a per-chart chore. A
+dataset owner names the partition column, the business column whose filters should be
+mirrored onto it, and a value transform. Superset then appends an equivalent predicate on
+the partition column to every query. Chart authors change nothing; queries prune.
+
+:::caution Experimental
+This feature is behind the `PARTITION_FILTER_MAPPING` feature flag and is off by default.
+:::
+
+## Enabling it
+
+```python
+FEATURE_FLAGS = {
+ "PARTITION_FILTER_MAPPING": True,
+}
+```
+
+Configure it as a **static boolean**. A callable placed in `FEATURE_FLAGS` is *not*
+evaluated: `FeatureFlagManager` stores the configured values unchanged, so
+`"PARTITION_FILTER_MAPPING": lambda: False` resolves to a truthy function object and turns
+the feature **on**. Per-request resolution comes only from `GET_FEATURE_FLAGS_FUNC` and
+`IS_FEATURE_ENABLED_FUNC`, and for this flag both must return the same answer for every
+user: a flag that resolves differently per user or tenant would let a user with the feature
+off read a cached chart result that was produced from pruned SQL by a user with it on.
+
+## Configuring a mapping
+
+In the dataset editor's **Columns** tab, under *Default Column Settings*, pick a
+**Partition column**. By default the mapping follows the dataset's default datetime column,
+so re-pointing that column moves the mapping with it; set an explicit override if you want it
+pinned to a different column.
+
+Expand the mapped column's row in *Column Settings* and set the **value transform**: a SQL
+expression containing a `:value` placeholder, which stands for the filter value being
+mirrored. The **Transform preserves ordering** checkbox sits directly beneath it.
+
+| Mapped column | Partition column | Transform |
+|---|---|---|
+| `event_time` (`TIMESTAMP`) | `dt_epoch` (`BIGINT`) | `unix_timestamp(:value)` |
+| `country` (`VARCHAR`) | `region_key` (`VARCHAR`) | `lower(:value)` |
+
+A filter of `event_time >= '2026-01-01'` then adds `dt_epoch >= 1767225600` to the query.
+The added predicate is an ordinary `WHERE` clause and shows up in **View query**.
+
+### Transform preserves ordering
+
+Range filters — including the Explore time range, the most important case — are only
+mirrored when you check **Transform preserves ordering**.
+
+Monotonicity is a property of the *transform*, not of the column's data type.
+`unix_timestamp(:value)` preserves ordering. `hour(:value)`,
+`date_format(:value, 'dd')` and `dayofweek(:value)` are all perfectly reasonable
+partition transforms on a `TIMESTAMP` column and none of them do: `hour('2026-01-01 23:00')`
+is greater than `hour('2026-01-02 01:00')` even though the first instant is earlier. Mirroring
+a range through one of those would silently return wrong numbers, so Superset asks you to
+declare it rather than guessing.
+
+A *bucketing* transform preserves ordering and is the common case rather than
+an exception: `to_char(:value, 'YYYYMMDD')`, `date(:value)` and
+`cast(unix_timestamp(:value) / 86400 as bigint)` each map a whole day onto one
+partition key, which is exactly what a daily-partitioned table wants. Check the
+box for these.
+
+One caveat if your partition column is **temporal** and the transform answers with *text*: a
+mirror such as `part_date = '20260115'` compares a date column against a string, which is an
+implicit coercion the database has to actually have. **PostgreSQL and Redshift** do, in both
+the ISO and unseparated spellings, so a text day key mirrors there. Trino has no
+varchar-to-date comparison at all, BigQuery coerces only a canonical `YYYY-MM-DD` *literal*,
+and Snowflake reads an all-digit string as epoch seconds — on those the predicate would fail
+the whole query rather than merely lose its pruning, so Superset declines it and the preview
+says why. Any other engine declines too, until it is confirmed and declared.
+
+If your partition column is temporal and your transform returns text, the robust answer is
+to make the transform's return type match the column: `date(:value)` or
+`cast(... as date)` rather than `to_char(...)`. A *numeric* partition column — the
+`unix_timestamp(:value)` / epoch shape — is unaffected by any of this.
+
+When the box is unchecked, `=` and `IN` filters still mirror; ranges do not.
+
+## What is and isn't mirrored
+
+| Filter | Mirrored |
+|---|---|
+| `=`, `IN` | Always, except on a text column whose engine does not compare text exactly, or when the engine compares less of the value than the filter carries |
+| `>`, `>=`, `<`, `<=`, time ranges | Only when the transform preserves ordering — and a strict bound mirrors non-strictly |
+| `!=`, `NOT IN`, `LIKE`, `ILIKE`, `IS NULL`, `IS TRUE` | Never |
+
+**Strict bounds.** Preserving ordering means non-decreasing, not strictly
+increasing, so `event_time < '2026-07-06 12:00'` mirrors to
+`day_key <= '20260706'` rather than `day_key < '20260706'`. Under a day key both
+sides of a mid-day boundary share a key, and the strict form would prune away
+the partition the boundary rows live in. The mirror reads one extra partition
+and keeps every row the filter keeps.
+
+Negations are never safe. A transform need not be injective: `lower(:value)` with
+`country != 'US'` would mirror to `region_key != 'us'`, which excludes rows whose `country`
+is already lowercase `'us'` — rows the original filter *keeps*.
+
+**Text comparison.** Mirroring `col = v` onto `partition_col = T(v)` assumes the engine
+compares `col` the way the transform was written against. Under a case-insensitive collation
+it does not: a stored `country` of `'us'` satisfies a filter for `'US'`, while the mirror is
+derived from `'US'` and excludes the row. So `=` and `IN` on a **text** mapped column only
+mirror on engines whose default text comparison is exact — Hive, Impala, Trino, Presto,
+Spark, Databricks, PostgreSQL, Snowflake, BigQuery and SQLite. On MySQL, SQL Server and
+Redshift, whose default comparisons ignore case or trailing blanks, a text mapping is stored
+and shown but no `=` or `IN` filter mirrors through it; map a numeric or temporal column
+instead. Numeric and temporal comparison is exact everywhere, and ranges are unaffected
+either way — checking **Transform preserves ordering** is already a statement about the
+column's own ordering.
+
+A **fixed-width** character type is its own case, on every engine: `CHAR(2)`, `CHARACTER(2)`
+and PostgreSQL's `bpchar` compare without their trailing blanks, so a stored `'US'` matches a
+filter for `'US '` while `lower('US ')` does not match the partition key. Mapping such a
+column stores and shows, and `=` and `IN` do not mirror through it. `VARCHAR` and `CHARACTER
+VARYING` are unaffected.
+
+One case Superset cannot check for you: a column that declares its own collation, such as
+`country COLLATE NOCASE`, on an engine that is otherwise exact. Nothing in the metadata
+exposes that, so it falls under the same pipeline assumption as the partition key itself.
+
+**Value resolution.** Mirroring also assumes the engine compares the value your filter
+carries. It does not always. On a `DATE` mapped column, `event_date = '2026-07-06 10:08:11'`
+is compared on the date part alone — Postgres casts the string, Presto and Trino render
+`DATE '2026-07-06'` — so the filter keeps the whole of July 6 while a mirror derived from
+10:08:11 keeps one instant of it. Superset detects what your engine drops, from the column's
+type rather than from a list of engines, and responds by operator: a range **widens** to the
+day, so `event_date >= '2026-07-05 10:00'` mirrors as if the bound were `'2026-07-05 00:00'`
+— one extra partition read, every row the filter keeps — while `=` and `IN` have nowhere to
+widen to and do **not** mirror at all. A `=` or `IN` whose value carries no time of day,
+such as `'2026-07-06'` or a date picked in the filter popover, mirrors normally. The same
+applies one grain finer on engines that compare timestamps only to the second.
+
+Reading the value is what makes all of that possible, and Superset reads **ISO 8601 only** —
+`2026-07-06`, `2026-07-06 10:08:11`, `2026-07-06T10:08:11`. It is the one format whose
+meaning is not a guess: `06/07/2026` is July 6 to a US reader and June 7 to most of the
+world, and a mirror built from the wrong one drops rows silently. So on a column the engine
+compares coarsely, a datetime typed in any other format — `07/06/2026 10:08:11`,
+`2026/07/06 10:08:11`, `July 6 2026 10:08:11` — does not mirror, for any operator, and no
+pruning indicator appears. The filter itself is unaffected; the query is correct and simply
+reads the whole table. Write the bound in ISO 8601, or pick it from the filter popover, and
+the mirror comes back. Most of this stops applying where the engine compares the whole
+value: on a `TIMESTAMP` column any format your database accepts mirrors, because there is
+nothing left for Superset to resolve.
+
+**One exception on every column: a UTC offset.** A bound written as
+`2026-01-01T01:00:00+01:00` does not mirror, on a `TIMESTAMP` column as much as on a `DATE`
+one, and no pruning indicator appears. Your transform is evaluated by the database in its
+own time frame — `CAST(:value AS TIMESTAMP)` discards the offset rather than converting
+through it — so a mirror built from the offset-bearing value could ask for a partition the
+matching rows are not in. Write the bound without an offset, in the frame the column is
+stored in, and it mirrors. The preview says so in those words when a sample carries one.
+
+**One exception on some databases: a quote or a backslash.** A value is written into the
+probe as a literal, and on some databases the driver that writes it and the engine that reads
+it disagree about what a quote or a backslash inside it means -- Hive and Spark honour a
+backslash escape and not a doubled apostrophe, which is the other way round from the driver.
+Superset checks each value rather than assuming either spelling, so where the two disagree a
+filter value carrying one of those characters does not mirror, for any operator, and no
+pruning indicator appears. The query is unaffected and simply reads more partitions. Values
+carrying neither still mirror everywhere, and which of the two is affected depends on the
+database: Hive and Spark decline both, Postgres declines only a backslash, and MySQL, SQLite
+and Trino decline neither. The preview says so in those words when a sample carries one.
+
+If `=` and `IN` on a date column matter to you, map a `TIMESTAMP` column instead: the engine
+then compares the whole value and every operator mirrors.
+
+**Time grains.** A filter that carries a time grain — drill-to-detail, mostly — compares the
+*truncated* column, so the raw bounds it carries do not describe the rows it keeps: a row in
+the final partial bucket satisfies `DATE_TRUNC(...) < until` while `col < until` excludes it.
+Grained *ranges* still mirror, with both bounds widened by one bucket so the mirror stays no
+narrower than the real filter. A `P1D` drill therefore reads three days of partitions rather
+than one, instead of scanning the table. Grained `=` and `IN` filters do not mirror.
+
+Widening is only applied to grains whose bucket width Superset knows, which means the
+built-in ones. A grain you added through `TIME_GRAIN_ADDONS`, or a built-in grain whose SQL
+you replaced through `TIME_GRAIN_ADDON_EXPRESSIONS`, has no width Superset can rely on and
+simply does not mirror.
+
+Known gaps, all of which are out of scope rather than bugs:
+
+- **Filter-value dropdowns do not prune.** Populating a filter's value list runs its own
Review Comment:
This says filter-value dropdowns do not prune because there is no filter to mirror, but `FiltersConfigForm` now seeds new eligible native filters with a `Last week` pre-filter on the mapped column, which does get mirrored. An admin reading this would not know the new default exists, or that a value present only in older partitions will be missing from the dropdown until the pre-filter is cleared. Could this bullet describe the default and how to get all-time values?
##########
tests/unit_tests/datasets/commands/importers/v1/import_test.py:
##########
@@ -3392,3 +3394,586 @@ def test_load_data_bounds_gzip_download_before_decompression(
mock_gzip_open.assert_called_once_with(bounded_raw)
# ...and the decompressed output is bounded again before parsing.
assert mock_read_bounded.call_args_list[1].args[0] is decompressed
+
+
+@with_feature_flags(PARTITION_FILTER_MAPPING=True)
+def test_import_drops_a_transform_the_mapping_does_not_mirror(
+ mocker: MockerFixture, session: Session
+) -> None:
+ """
+ An import is a writer like any other, and it bypasses the editor entirely.
+
+ A bundle carrying a transform on a column the mapping does not mirror would
+ otherwise land a value nothing renders and nothing can edit, waiting for the
+ mapped column to resolve back to it.
+ """
+ mocker.patch.object(security_manager, "can_access", return_value=True)
+
+ engine = db.session.get_bind()
+ SqlaTable.metadata.create_all(engine) # pylint: disable=no-member
+ database = Database(database_name="pfm_import_db", sqlalchemy_uri="sqlite://")
+ db.session.add(database)
+ db.session.flush()
+
+ config: dict[str, Any] = {
+ "table_name": "pfm_import_table",
+ "main_dttm_col": "event_time",
+ "schema": "main",
+ "sql": None,
+ "uuid": uuid.uuid4(),
+ "metrics": [],
+ "partition_column": "dt_epoch",
+ "partition_mapped_column": "event_time2",
+ "columns": [
+ {
+ "column_name": "event_time",
+ "is_dttm": True,
+ "partition_value_transform": "unix_timestamp(:value)",
+ "partition_transform_is_monotonic": True,
+ },
+ {
+ "column_name": "event_time2",
+ "is_dttm": True,
+ "partition_value_transform": "to_unixtime(:value)",
+ "partition_transform_is_monotonic": True,
+ },
+ {"column_name": "dt_epoch"},
+ ],
+ "database_uuid": database.uuid,
+ "database_id": database.id,
+ }
+
+ dataset = import_dataset(config)
+ db.session.flush()
+
+ transforms = {c.column_name: c.partition_value_transform for c in dataset.columns}
+ assert transforms == {
+ "event_time": None,
+ "event_time2": "to_unixtime(:value)",
+ "dt_epoch": None,
+ }
+
+
+@with_feature_flags(PARTITION_FILTER_MAPPING=False)
+def test_import_with_the_flag_off_drops_a_transform_it_cannot_mirror(
+ mocker: MockerFixture, session: Session
+) -> None:
+ """
+ The flag-off half of its sibling above, and the window the leftover
+ actually arrives through.
+
+ `DatasetDAO.clear_unmapped_partition_transforms` runs on both sides of the
+ import, but it is gated on the feature flag -- rightly, since it discards
+ stored configuration and with the feature off that is pure loss. So a
+ bundle imported while the flag was off parked its transform in the metadata
+ database fully armed, waiting for an operator to turn the flag on, and then
+ a filter on the newly-resolved mapped column started mirroring an
+ expression nobody authored.
+
+ What is dropped here is a value this bundle is asking to write, which is a
+ different question from the flag's.
+ """
+ mocker.patch.object(security_manager, "can_access", return_value=True)
+
+ engine = db.session.get_bind()
+ SqlaTable.metadata.create_all(engine) # pylint: disable=no-member
+ database = Database(database_name="pfm_import_off_db", sqlalchemy_uri="sqlite://")
+ db.session.add(database)
+ db.session.flush()
+
+ config: dict[str, Any] = {
+ "table_name": "pfm_import_off_table",
+ "main_dttm_col": "event_time",
+ "schema": "main",
+ "sql": None,
+ "uuid": uuid.uuid4(),
+ "metrics": [],
+ "partition_column": "dt_epoch",
+ "partition_mapped_column": None,
+ "columns": [
+ {
+ "column_name": "event_time",
+ "is_dttm": True,
+ "partition_value_transform": "unix_timestamp(:value)",
+ "partition_transform_is_monotonic": True,
+ },
+ {
+ "column_name": "event_time2",
+ "is_dttm": True,
+ "partition_value_transform": "to_unixtime(:value)",
+ "partition_transform_is_monotonic": True,
+ },
+ {"column_name": "dt_epoch"},
+ ],
+ "database_uuid": database.uuid,
+ "database_id": database.id,
+ }
+
+ dataset = import_dataset(config)
+ db.session.flush()
+
+ transforms = {c.column_name: c.partition_value_transform for c in dataset.columns}
+ # The mapped column is `main_dttm_col`, there being no override, so
+ # `event_time` keeps what the bundle wrote for it and `event_time2` -- one
+ # re-pointing of the default datetime column away from being live -- does
+ # not.
+ assert transforms == {
+ "event_time": "unix_timestamp(:value)",
+ "event_time2": None,
+ "dt_epoch": None,
+ }
+
+
+@with_feature_flags(PARTITION_FILTER_MAPPING=True)
+def test_overwrite_import_disarms_a_transform_parked_on_the_old_mapping(
+ mocker: MockerFixture,
+ session: Session,
+) -> None:
+ """
+ Omitted column fields keep their stored values, so a bundle that clears the
+ mapped-column override makes whatever `main_dttm_col` names the effective
+ column. A cleanup that only runs *after* the new references land resolves
+ the new mapping, finds that column effective and skips it -- so a transform
+ parked on it, invisible until now, goes live under a mapping nobody in the
+ bundle authored.
+
+ `DatasetDAO.update` is immune because it clears under the old resolution
+ too, before applying the request.
+ """
+ mocker.patch.object(security_manager, "can_access", return_value=True)
+
+ engine = db.session.get_bind()
+ SqlaTable.metadata.create_all(engine) # pylint: disable=no-member
+ database = Database(database_name="pfm_parked_db", sqlalchemy_uri="sqlite://")
+ db.session.add(database)
+ db.session.flush()
+
+ dataset_uuid = uuid.uuid4()
+ base: dict[str, Any] = {
+ "table_name": "pfm_parked",
+ "main_dttm_col": "event_time",
+ "schema": "main",
+ "sql": None,
+ "uuid": dataset_uuid,
+ "metrics": [],
+ "partition_column": "dt_epoch",
+ "partition_mapped_column": "event_time2",
+ "columns": [
+ {"column_name": "event_time", "is_dttm": True},
+ {
+ "column_name": "event_time2",
+ "is_dttm": True,
+ "partition_value_transform": "to_unixtime(:value)",
+ "partition_transform_is_monotonic": True,
+ },
+ {"column_name": "dt_epoch"},
+ ],
+ "database_uuid": database.uuid,
+ "database_id": database.id,
+ }
+ dataset = import_dataset(copy.deepcopy(base))
+ db.session.flush()
+
+ # Park a transform on the default datetime column, which the override
+ # currently hides. This is the state the editor can produce and the state
+ # the post-import cleanup is meant to leave unreachable.
+ for column in dataset.columns:
+ if column.column_name == "event_time":
+ column.partition_value_transform = "unix_timestamp(:value)"
+ column.partition_transform_is_monotonic = True
+ db.session.flush()
+
+ # Now clear the override, so `main_dttm_col` -- and the parked transform --
+ # becomes the effective mapping. The bundle says nothing about either
+ # column's transform.
+ overwrite = copy.deepcopy(base)
+ overwrite["partition_mapped_column"] = None
+ for column in overwrite["columns"]:
+ column.pop("partition_value_transform", None)
+ column.pop("partition_transform_is_monotonic", None)
+
+ dataset = import_dataset(overwrite, overwrite=True)
+ db.session.flush()
+
+ transforms = {c.column_name: c.partition_value_transform for c in dataset.columns}
+ assert transforms["event_time"] is None
+
+
+@with_feature_flags(PARTITION_FILTER_MAPPING=True)
+def test_import_clears_a_mapping_whose_column_the_sync_removed(
+ mocker: MockerFixture,
+ session: Session,
+) -> None:
+ """
+ An overwrite import syncs columns, so it can delete the column
+ `partition_column` names. Left dangling, the reference fails
+ `UpdateDatasetCommand`'s validation on every later edit -- including a
+ description-only PUT, which carries no columns payload and so cannot reach
+ the branch that forgives a stored-only dangle.
+ """
+ mocker.patch.object(security_manager, "can_access", return_value=True)
+
+ engine = db.session.get_bind()
+ SqlaTable.metadata.create_all(engine) # pylint: disable=no-member
+ database = Database(database_name="pfm_dangle_db", sqlalchemy_uri="sqlite://")
+ db.session.add(database)
+ db.session.flush()
+
+ base: dict[str, Any] = {
+ "table_name": "pfm_dangle",
+ "main_dttm_col": "event_time",
+ "schema": "main",
+ "sql": None,
+ "uuid": uuid.uuid4(),
+ "metrics": [],
+ "partition_column": "dt_epoch",
+ "partition_mapped_column": "event_time",
+ "columns": [
+ {
+ "column_name": "event_time",
+ "is_dttm": True,
+ "partition_value_transform": "unix_timestamp(:value)",
+ "partition_transform_is_monotonic": True,
+ },
+ {"column_name": "dt_epoch"},
+ ],
+ "database_uuid": database.uuid,
+ "database_id": database.id,
+ }
+ import_dataset(copy.deepcopy(base))
+ db.session.flush()
+
+ without_partition_column = copy.deepcopy(base)
+ without_partition_column["columns"] = [
+ column
+ for column in without_partition_column["columns"]
+ if column["column_name"] != "dt_epoch"
+ ]
+
+ dataset = import_dataset(without_partition_column, overwrite=True)
+ db.session.flush()
+
+ assert dataset.partition_column is None
+ assert dataset.partition_mapped_column is None
+
+
+def test_import_clears_a_mapping_that_names_the_partition_column_itself(
+ mocker: MockerFixture,
+ session: Session,
+) -> None:
+ """
+ A dangling reference is not the only mapping `UpdateDatasetCommand` refuses.
+ An *explicit* self-mapping -- `partition_mapped_column` equal to
+ `partition_column` -- is blocking there too, so a bundle setting both to
+ `event_time` imported happily and then failed every later edit, including a
+ description-only PUT, until someone repaired the mapping by hand.
+
+ Cleared rather than refused, which is the bargain the rest of the importer
+ strikes. Only the override goes, leaving the mapping following
+ `main_dttm_col` -- the state a bundle omitting the field would have given.
+ """
+ mocker.patch.object(security_manager, "can_access", return_value=True)
+
+ engine = db.session.get_bind()
+ SqlaTable.metadata.create_all(engine) # pylint: disable=no-member
+ database = Database(database_name="pfm_self_db", sqlalchemy_uri="sqlite://")
+ db.session.add(database)
+ db.session.flush()
+
+ config: dict[str, Any] = {
+ "table_name": "pfm_self",
+ "main_dttm_col": "event_time",
+ "schema": "main",
+ "sql": None,
+ "uuid": uuid.uuid4(),
+ "metrics": [],
+ "partition_column": "event_time",
+ "partition_mapped_column": "event_time",
+ "columns": [
+ {"column_name": "event_time", "is_dttm": True},
+ {"column_name": "dt_epoch"},
+ ],
+ "database_uuid": database.uuid,
+ "database_id": database.id,
+ }
+
+ dataset = import_dataset(config)
+ db.session.flush()
+
+ # The dataset imported, and the reference no later save would accept is gone.
+ assert dataset.partition_mapped_column is None
+ assert dataset.partition_column == "event_time"
+
+
+def _partition_mapping_config(database_id: int, transform: str) -> dict[str, Any]:
+ return {
+ "table_name": "web_events",
+ "uuid": uuid.uuid4(),
+ "database_id": database_id,
+ "main_dttm_col": "event_time",
+ "partition_column": "dt_epoch",
+ "partition_mapped_column": "event_time",
+ "columns": [
+ {
+ "column_name": "event_time",
+ "is_dttm": True,
+ "partition_value_transform": transform,
+ "partition_transform_is_monotonic": True,
+ },
+ {"column_name": "dt_epoch"},
+ ],
+ "metrics": [],
+ }
+
+
+@with_feature_flags(PARTITION_FILTER_MAPPING=True)
+@pytest.mark.parametrize(
+ "transform",
+ ["unix_timestamp({{ current_username() }})", "rand() + 0 * :value"],
+ ids=["jinja", "non-deterministic"],
+)
+def test_import_drops_a_transform_the_save_path_would_reject(
+ session: Session, transform: str
+) -> None:
+ """
+ Import is the one door into this field that does not go through
+ `UpdateDatasetCommand`, so a bundle can carry a transform that will never
+ mirror a filter. Dropping it leaves a state an owner can see and fix rather
+ than a stored expression that looks configured and is not.
+ """
+ engine = db.session.get_bind()
+ SqlaTable.metadata.create_all(engine) # pylint: disable=no-member
+ database = Database(database_name="hive_db", sqlalchemy_uri="hive://localhost/db")
+ db.session.add(database)
+ db.session.flush()
+
+ config = _partition_mapping_config(database.id, transform)
+ drop_unusable_partition_transforms(config)
+
+ assert config["columns"][0]["partition_value_transform"] is None
+ assert config["columns"][0]["partition_transform_is_monotonic"] is False
+
+
+@with_feature_flags(PARTITION_FILTER_MAPPING=True)
+def test_import_defaults_an_omitted_monotonic_declaration_to_false(
+ session: Session,
+) -> None:
+ """
+ `ImportV1ColumnSchema` gives the declaration a `load_default` of False, but
+ the importer applies the raw config and throws `schema.load()`'s output
+ away, so the default never reaches storage. On an overwrite that leaves a
+ stored True standing next to a *replacement* transform -- and a
+ non-monotonic transform declared monotonic enables range mirrors that
+ exclude rows the filter keeps.
+ """
+ engine = db.session.get_bind()
+ SqlaTable.metadata.create_all(engine) # pylint: disable=no-member
+ database = Database(database_name="hive_db", sqlalchemy_uri="hive://localhost/db")
+ db.session.add(database)
+ db.session.flush()
+
+ config = _partition_mapping_config(database.id, "hour(:value)")
+ del config["columns"][0]["partition_transform_is_monotonic"]
+
+ drop_unusable_partition_transforms(config)
+
+ assert config["columns"][0]["partition_value_transform"] == "hour(:value)"
+ assert config["columns"][0]["partition_transform_is_monotonic"] is False
+
+
+@with_feature_flags(PARTITION_FILTER_MAPPING=True)
+def test_import_leaves_a_declared_monotonic_transform_declared(
+ session: Session,
+) -> None:
+ """
+ Only an *omitted* declaration is defaulted. A bundle that says True still
+ means it, or export-then-import would downgrade every range mirror to
+ equality-only.
+ """
+ engine = db.session.get_bind()
+ SqlaTable.metadata.create_all(engine) # pylint: disable=no-member
+ database = Database(database_name="hive_db", sqlalchemy_uri="hive://localhost/db")
+ db.session.add(database)
+ db.session.flush()
+
+ config = _partition_mapping_config(database.id, "unix_timestamp(:value)")
+ drop_unusable_partition_transforms(config)
+
+ assert config["columns"][0]["partition_transform_is_monotonic"] is True
+
+
+@with_feature_flags(PARTITION_FILTER_MAPPING=True)
+def test_import_keeps_a_usable_transform(session: Session) -> None:
+ engine = db.session.get_bind()
+ SqlaTable.metadata.create_all(engine) # pylint: disable=no-member
+ database = Database(database_name="hive_db", sqlalchemy_uri="hive://localhost/db")
+ db.session.add(database)
+ db.session.flush()
+
+ config = _partition_mapping_config(database.id, "unix_timestamp(:value)")
+ drop_unusable_partition_transforms(config)
+
+ assert config["columns"][0]["partition_value_transform"] == "unix_timestamp(:value)"
+ assert config["columns"][0]["partition_transform_is_monotonic"] is True
+
+
+@with_feature_flags(PARTITION_FILTER_MAPPING=False)
+def test_import_leaves_transforms_alone_while_the_feature_is_off(
+ session: Session,
+) -> None:
+ """
+ No *usability* check runs with the flag off: nothing mirrors, so there is
+ only stored configuration to lose. The structural check still runs, and
+ Jinja passes it -- balanced blocks are substituted out before parsing.
+ """
+ engine = db.session.get_bind()
+ SqlaTable.metadata.create_all(engine) # pylint: disable=no-member
+ database = Database(database_name="hive_db", sqlalchemy_uri="hive://localhost/db")
+ db.session.add(database)
+ db.session.flush()
+
+ config = _partition_mapping_config(
+ database.id, "unix_timestamp({{ current_username() }})"
+ )
+ drop_unusable_partition_transforms(config)
+
+ assert (
+ config["columns"][0]["partition_value_transform"]
+ == "unix_timestamp({{ current_username() }})"
+ )
+
+
+#: Expressions the save path refuses outright, rather than ones that merely
+#: never mirror. The probe splices a transform into SQL and runs it, so a
+#: bundle carrying one of these is a way to execute arbitrary SQL without the
+#: `sql_lab` role.
+UNSTORABLE_TRANSFORMS = pytest.mark.parametrize(
+ "transform",
+ [
+ "(SELECT password FROM ab_user LIMIT 1) || :value",
+ "unix_timestamp(:value) UNION ALL SELECT password FROM ab_user",
+ "unix_timestamp(:value); DROP TABLE ab_user",
+ "password || :value FROM ab_user",
+ ],
+ ids=["subquery", "set-operation", "multi-statement", "bare-from"],
+)
+
+
+def _assert_import_drops(transform: str) -> None:
+ engine = db.session.get_bind()
+ SqlaTable.metadata.create_all(engine) # pylint: disable=no-member
+ database = Database(database_name="hive_db", sqlalchemy_uri="hive://localhost/db")
+ db.session.add(database)
+ db.session.flush()
+
+ config = _partition_mapping_config(database.id, transform)
+ drop_unusable_partition_transforms(config)
+
+ assert config["columns"][0]["partition_value_transform"] is None
+ assert config["columns"][0]["partition_transform_is_monotonic"] is False
+
+
+@with_feature_flags(PARTITION_FILTER_MAPPING=True)
+@UNSTORABLE_TRANSFORMS
+def test_import_drops_a_transform_that_is_not_a_storable_expression(
+ session: Session, transform: str
+) -> None:
+ _assert_import_drops(transform)
+
+
+@with_feature_flags(PARTITION_FILTER_MAPPING=False)
+@UNSTORABLE_TRANSFORMS
+def test_import_drops_an_unstorable_transform_even_with_the_feature_off(
+ session: Session, transform: str
+) -> None:
+ """
+ The one check the flag does not switch off.
+
+ Everything else here asks whether a transform will mirror, which is a
+ question about a live feature. This asks whether the expression is one the
+ product stores at all, and a bundle imported with the flag off would
+ otherwise sit in the metadata DB fully armed, waiting for an operator to
+ turn the flag on.
+ """
+ _assert_import_drops(transform)
+
+
+#: A transform a PUT accepts and parks inactive, rather than one it refuses.
+#: `validate_transform` classifies an unparseable transform as a Tier-2 issue:
+#: the mapping saves and stays inactive until the owner finishes typing it.
+UNFINISHED_TRANSFORMS = pytest.mark.parametrize(
+ "transform",
+ ["unix_timestamp(:value", "unix_timestamp(:value))", "unix_timestamp(:value) +"],
+ ids=["unclosed", "extra-paren", "trailing-operator"],
+)
+
+
+def _assert_import_keeps(transform: str) -> None:
+ engine = db.session.get_bind()
+ SqlaTable.metadata.create_all(engine) # pylint: disable=no-member
+ database = Database(database_name="hive_db", sqlalchemy_uri="hive://localhost/db")
+ db.session.add(database)
+ db.session.flush()
+
+ config = _partition_mapping_config(database.id, transform)
+ drop_unusable_partition_transforms(config)
+
+ assert config["columns"][0]["partition_value_transform"] == transform
+
+
+@with_feature_flags(PARTITION_FILTER_MAPPING=True)
+@UNFINISHED_TRANSFORMS
+def test_import_keeps_an_unfinished_transform_a_put_would_park(
+ session: Session, transform: str
+) -> None:
+ """
+ `stored_expression_error` fails closed on a transform that does not parse,
+ which is right for the probe and wrong here: a PUT saves the same transform
+ and reports it inactive, so nulling it on import means an export cannot
+ round-trip the dataset it was taken from. `UpdateDatasetCommand` puts the
+ same parseability condition in front of the same gate.
+ """
+ _assert_import_keeps(transform)
+
+
+@with_feature_flags(PARTITION_FILTER_MAPPING=False)
+@UNFINISHED_TRANSFORMS
+def test_import_keeps_an_unfinished_transform_with_the_feature_off(
+ session: Session, transform: str
+) -> None:
+ """With the flag off there is only stored configuration to lose."""
+ _assert_import_keeps(transform)
+
+
+@with_feature_flags(PARTITION_FILTER_MAPPING=True)
+def test_an_unfinished_transform_survives_the_export_import_round_trip(
+ session: Session,
+) -> None:
+ """
+ The test that would have caught this. An owner mid-edit saves, exports, and
+ imports the bundle back: the transform has to come out the way it went in,
+ inactive but intact.
+ """
+ engine = db.session.get_bind()
+ SqlaTable.metadata.create_all(engine) # pylint: disable=no-member
+ database = Database(database_name="hive_db", sqlalchemy_uri="hive://localhost/db")
+ db.session.add(database)
+ db.session.flush()
+
+ transform = "unix_timestamp(:value"
+ stored = TableColumn(column_name="event_time", is_dttm=True)
+ stored.partition_value_transform = transform
+
+ # What export writes, from a column a PUT accepted and parked inactive.
+ exported = {
+ "column_name": stored.column_name,
+ "partition_value_transform": stored.partition_value_transform,
+ "partition_transform_is_monotonic": None,
+ }
+ loaded = ImportV1ColumnSchema().load(exported)
Review Comment:
This is named and documented as the export/import round trip, but it builds the `exported` dict by hand and then runs only the column schema and `drop_unusable_partition_transforms`; no dataset is persisted, exported, or imported. If the real exporter or the importer dropped an unfinished transform such as `unix_timestamp(:value`, this would still pass. Could it save a mapped dataset, export its YAML, import it back, and compare the stored transform and monotonic flag?
##########
tests/unit_tests/models/partition_mirroring_test.py:
##########
@@ -0,0 +1,3205 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mirroring inside ``ExploreMixin.get_sqla_query``.
+
+The probe that resolves ``T(v)`` against the engine is stubbed throughout; what
+these tests pin down is *which* predicates get mirrored and with what values,
+which is where the correctness argument lives.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from typing import Any
+from unittest.mock import MagicMock, patch
+
+import pandas as pd
+import pytest
+import sqlalchemy as sa
+from flask import Flask
+
+from superset.connectors.sqla.models import SqlaTable, SqlMetric, TableColumn
+from superset.connectors.sqla.partition_mapping import RawProbeValue
+from superset.db_engine_specs.clickhouse import ClickHouseEngineSpec
+from superset.db_engine_specs.presto import PrestoEngineSpec
+from superset.db_engine_specs.sqlite import SqliteEngineSpec
+from superset.models.core import Database
+from superset.superset_typing import QueryObjectDict
+from superset.utils import json
+from superset.utils.core import FilterOperator
+
+PROBE = "superset.connectors.sqla.partition_mapping.evaluate_transform"
+
+
+@pytest.fixture(autouse=True)
+def enable_partition_filter_mapping(app: Flask) -> Any:
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = True
+ yield
+ del app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"]
+
+
+def _table(
+ *,
+ transform: str = "unix_timestamp(:value)",
+ monotonic: bool = True,
+ partition_column: str | None = "dt_epoch",
+ mapped_column: str = "event_time",
+ partition_mapped_column: str | None = None,
+ main_dttm_col: str | None = "event_time",
+) -> SqlaTable:
+ database = Database(database_name="test_db", sqlalchemy_uri="sqlite://")
+ columns = [
+ TableColumn(column_name="event_time", is_dttm=True, type="TIMESTAMP"),
+ TableColumn(column_name="other_time", is_dttm=True, type="TIMESTAMP"),
+ TableColumn(column_name="dt_epoch", type="BIGINT"),
+ TableColumn(column_name="country", type="VARCHAR"),
+ TableColumn(column_name="region_key", type="VARCHAR"),
+ ]
+ table = SqlaTable(
+ table_name="web_events",
+ database=database,
+ schema=None,
+ main_dttm_col=main_dttm_col,
+ columns=columns,
+ metrics=[SqlMetric(metric_name="hits", expression="COUNT(*)")],
+ )
+ table.partition_column = partition_column
+ table.partition_mapped_column = partition_mapped_column
+ for column in columns:
+ if column.column_name == mapped_column:
+ column.partition_value_transform = transform
+ column.partition_transform_is_monotonic = monotonic
+ return table
+
+
+def _mapped_date_table() -> SqlaTable:
+ """
+ A dataset whose mapped column is a ``DATE``.
+
+ That is the type whose literal an engine resolves to a bare day, which is
+ what the resolution reasoning is about; `_rendering_dates_like_presto` is
+ what makes this table's spec answer that way.
+ """
+ table = _table(mapped_column="event_date", main_dttm_col="event_date")
+ table.columns.append(
+ TableColumn(column_name="event_date", is_dttm=True, type="DATE")
+ )
+ table.columns[-1].partition_value_transform = "unix_timestamp(:value)"
+ table.columns[-1].partition_transform_is_monotonic = True
+ return table
+
+
+def _rendering_dates_like_presto(table: SqlaTable) -> Any:
+ """
+ Make the dataset's engine spec render a bound the way Presto does.
+
+ `Database.db_engine_spec` is a derived property, so the spec cannot be
+ swapped wholesale; delegating `convert_dttm` keeps the test tied to the real
+ spec rather than to a hand-copied format string. Presto's DATE branch is
+ `DATE '{dttm.date().isoformat()}'`, which Trino, BigQuery and some two dozen
+ others share.
+ """
+ return patch.object(
+ table.database.db_engine_spec,
+ "convert_dttm",
+ classmethod(
+ lambda cls, target_type, dttm, db_extra=None: PrestoEngineSpec.convert_dttm(
+ target_type, dttm, db_extra=db_extra
+ )
+ ),
+ )
+
+
+def _query(table: SqlaTable, **kwargs: Any) -> str:
+ defaults: dict[str, Any] = {
+ "columns": ["country"],
+ "metrics": [],
+ "orderby": [],
+ "extras": {},
+ "filter": [],
+ "granularity": None,
+ "is_timeseries": False,
+ }
+ defaults.update(kwargs)
+ result = table.get_sqla_query(**defaults)
+ return str(
+ result.sqla_query.compile(compile_kwargs={"literal_binds": True})
+ ).replace("\n", " ")
+
+
+# ---------------------------------------------------------------------------
+# The safe operators
+# ---------------------------------------------------------------------------
+
+
+def test_equality_filter_mirrors_onto_the_partition_column(app: Flask) -> None:
+ table = _table(
+ transform="lower(:value)",
+ monotonic=False,
+ mapped_column="country",
+ partition_mapped_column="country",
+ partition_column="region_key",
+ )
+
+ with app.app_context():
+ with patch(PROBE, return_value=["us"]):
+ sql = _query(
+ table,
+ filter=[
+ {"col": "country", "op": FilterOperator.EQUALS.value, "val": "US"}
+ ],
+ )
+
+ assert "region_key = 'us'" in sql
+ assert "country = 'US'" in sql
+
+
+def _with_date_partition_column(table: SqlaTable) -> SqlaTable:
+ """Re-point the mapping's partition column at a ``DATE`` column."""
+ table.columns.append(
+ TableColumn(column_name="part_date", is_dttm=True, type="DATE")
+ )
+ table.partition_column = "part_date"
+ return table
+
+
+def test_ordinary_text_does_not_mirror_onto_a_temporal_partition_column(
+ app: Flask,
+) -> None:
+ """
+ `lower(:value)` on a `VARCHAR` mapped column answers with text, and a
+ temporal partition column admits text -- a day key is legitimately text.
+ But it admitted *any* text: `country = 'US'` probed to `'us'` and emitted
+ `part_date = 'us'`, which PostgreSQL refuses as a date. By then the mirror
+ is in the statement, so a chart that worked before the mapping returned an
+ error rather than losing its pruning. The preview called it valid.
+ """
+ table = _with_date_partition_column(
+ _table(
+ transform="lower(:value)",
+ monotonic=False,
+ mapped_column="country",
+ partition_mapped_column="country",
+ )
+ )
+
+ with app.app_context():
+ with patch(PROBE, return_value=["us"]):
+ sql = _query(
+ table,
+ filter=[
+ {"col": "country", "op": FilterOperator.EQUALS.value, "val": "US"}
+ ],
+ )
+
+ assert "part_date" not in sql
+ assert "country = 'US'" in sql
+
+
+def test_a_text_column_s_bound_is_not_rounded_as_though_it_were_temporal(
+ app: Flask,
+) -> None:
+ """
+ SQLite's `convert_dttm` renders for `types.String` as well as the date
+ types, so a VARCHAR mapped column read as second-resolution -- and a filter
+ value that merely *looks* like an instant had its bound rounded as though
+ the engine had truncated it.
+
+ On a VARCHAR `country` mapped onto VARCHAR `region_key` by `:value`,
+ `country < '2026-07-06T10:08:11.500000'` was mirrored as
+ `region_key <= '2026-07-06 10:08:12.000000'`. A space sorts before `T`, so a
+ row holding `2026-07-06T09:00:00` -- which the filter keeps -- fell outside
+ the mirror and was dropped.
+
+ `_column_literal_resolution` already guarded on `is_dttm` and said in its
+ docstring that the per-instant callers never met this case. They do: the
+ value parses as an instant while the column is still text.
+ """
+ table = _table(
+ transform=":value",
+ monotonic=True,
+ mapped_column="country",
+ partition_mapped_column="country",
+ partition_column="region_key",
+ )
+
+ with app.app_context():
+ with patch(PROBE, return_value=["2026-07-06T10:08:11.500000"]) as probe:
+ _query(
+ table,
+ filter=[
+ {
+ "col": "country",
+ "op": FilterOperator.LESS_THAN.value,
+ "val": "2026-07-06T10:08:11.500000",
+ }
+ ],
+ )
+
+ # Handed through untouched: no rounding, and no seconds-shaped rewrite.
+ assert probe.call_args.args[-1] == ["2026-07-06T10:08:11.500000"]
+
+
+def test_a_day_key_still_mirrors_onto_a_temporal_partition_column(
+ app: Flask,
+) -> None:
+ """
+ The narrowing above must not cost the case the text admission exists for:
+ `to_char(:value, 'YYYYMMDD')` answers with a day key, which PostgreSQL
+ reads as a date and so declares in `temporal_literal_formats`.
+
+ Its sibling `test_a_day_key_still_mirrors_onto_a_text_partition_column`
+ covers the same transform onto a *text* key, which is the other axis --
+ that one is about `GenericDataType.STRING` and never reached this gate.
+ """
+ table = _with_date_partition_column(
+ _table(
+ transform="to_char(:value, 'YYYYMMDD')",
+ monotonic=False,
+ mapped_column="country",
+ partition_mapped_column="country",
+ )
+ )
+
+ with app.app_context():
+ with patch.object(SqliteEngineSpec, "temporal_literal_formats", ("%Y%m%d",)):
+ with patch(PROBE, return_value=["20260101"]):
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "country",
+ "op": FilterOperator.EQUALS.value,
+ "val": "US",
+ }
+ ],
+ )
+
+ assert "part_date = '20260101'" in sql
+
+
+def test_a_day_key_declines_where_the_engine_has_not_claimed_it(
+ app: Flask,
+) -> None:
+ """
+ BigQuery coerces a STRING literal to `DATE` only in the canonical
+ `YYYY-MM-DD` form and Trino wants an explicit cast, so `part_date =
+ '20260101'` fails the whole chart there rather than merely losing its
+ pruning. An engine that has not declared the format declines instead.
+ """
+ table = _with_date_partition_column(
+ _table(
+ transform="to_char(:value, 'YYYYMMDD')",
+ monotonic=False,
+ mapped_column="country",
+ partition_mapped_column="country",
+ )
+ )
+
+ assert SqliteEngineSpec.temporal_literal_formats == ()
+
+ with app.app_context():
+ with patch(PROBE, return_value=["20260101"]):
+ sql = _query(
+ table,
+ filter=[
+ {"col": "country", "op": FilterOperator.EQUALS.value, "val": "US"}
+ ],
+ )
+
+ assert "part_date" not in sql
+
+
+def test_in_filter_mirrors_element_wise(app: Flask) -> None:
+ table = _table(
+ transform="lower(:value)",
+ monotonic=False,
+ mapped_column="country",
+ partition_mapped_column="country",
+ partition_column="region_key",
+ )
+
+ with app.app_context():
+ with patch(PROBE, return_value=["us", "ca"]):
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "country",
+ "op": FilterOperator.IN.value,
+ "val": ["US", "CA"],
+ }
+ ],
+ )
+
+ assert "region_key IN ('us', 'ca')" in sql
+
+
+def test_time_range_mirrors_both_bounds(app: Flask) -> None:
+ """
+ The Explore time range is the most important operator in the feature, and it
+ is a range operator -- so it only mirrors on a declared-monotonic transform.
+ """
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1767225600, 1769904000]):
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ )
+
+ assert "dt_epoch >= 1767225600" in sql
+ assert "dt_epoch <= 1769904000" in sql
+
+
+def test_temporal_range_filter_mirrors_both_bounds(app: Flask) -> None:
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1767225600, 1769904000]):
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_time",
+ "op": FilterOperator.TEMPORAL_RANGE.value,
+ "val": "2026-01-01 : 2026-02-01",
+ }
+ ],
+ )
+
+ assert "dt_epoch >= 1767225600" in sql
+ assert "dt_epoch <= 1769904000" in sql
+
+
+@pytest.mark.parametrize(
+ "operator,expected",
+ [
+ (FilterOperator.GREATER_THAN, "dt_epoch >= 1767225600"),
+ (FilterOperator.GREATER_THAN_OR_EQUALS, "dt_epoch >= 1767225600"),
+ (FilterOperator.LESS_THAN, "dt_epoch <= 1767225600"),
+ (FilterOperator.LESS_THAN_OR_EQUALS, "dt_epoch <= 1767225600"),
+ ],
+)
+def test_strict_range_operators_mirror_non_strictly(
+ app: Flask, operator: FilterOperator, expected: str
+) -> None:
+ """
+ The direction is preserved; the strictness is not. "Preserves ordering"
+ means non-decreasing, so `col < v` only implies `T(col) <= T(v)` -- a
+ strict mirror would drop the rows a bucketing transform puts at the
+ boundary. The non-strict mirror reads one extra partition, and the original
+ filter is still there to exclude whatever it admits.
+ """
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1767225600]):
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_time",
+ "op": operator.value,
+ "val": "2026-01-01 00:00:00",
+ }
+ ],
+ )
+
+ assert expected in sql
+
+
+def test_a_bucketing_transform_keeps_the_boundary_bucket(app: Flask) -> None:
+ """
+ A day key is monotonic but not *strictly* so: every instant in a day
+ maps to one value, so an upper bound at `2026-07-06 12:00` and a row at
+ `2026-07-06 06:00` share the bucket `20260706`. Mirroring that bound
+ strictly prunes the bucket the row is in and drops it from the chart --
+ silently, with the pruning glyph still promising only a speed-up.
+ """
+ table = _table(
+ transform="to_char(:value, 'YYYYMMDD')",
+ partition_column="region_key",
+ )
+
+ with app.app_context():
+ with patch(PROBE, return_value=["20260705", "20260706"]):
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 7, 5),
+ to_dttm=datetime(2026, 7, 6, 12, 0),
+ )
+
+ assert "region_key >= '20260705'" in sql
+ assert "region_key <= '20260706'" in sql
+
+
+def test_an_intraday_strict_pair_does_not_mirror_to_an_empty_range(
+ app: Flask,
+) -> None:
+ """
+ The zero-instead-of-nine case. `event_time > '2026-07-05 06:00'` plus
+ `event_time < '2026-07-06 00:00'` is an ordinary pair of ad-hoc filters, and
+ under a day key the bounds land in adjacent buckets. Mirrored strictly it
+ reads `day_key > '20260705' AND day_key < '20260706'`, which is empty by
+ construction whatever the table holds -- so the chart returns nothing while
+ SQL Lab returns the real rows.
+ """
+ table = _table(
+ transform="to_char(:value, 'YYYYMMDD')",
+ partition_column="region_key",
+ )
+
+ with app.app_context():
+ with patch(PROBE, return_value=["20260705", "20260706"]):
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_time",
+ "op": FilterOperator.GREATER_THAN.value,
+ "val": "2026-07-05 06:00:00",
+ },
+ {
+ "col": "event_time",
+ "op": FilterOperator.LESS_THAN.value,
+ "val": "2026-07-06 00:00:00",
+ },
+ ],
+ )
+
+ assert "region_key >= '20260705'" in sql
+ assert "region_key <= '20260706'" in sql
+
+
+def test_an_integer_bucket_key_is_mirrored_non_strictly_too(app: Flask) -> None:
+ """
+ The same loss was measured on a day *number* as well as a day string, so it
+ is a property of any many-to-one transform rather than of text keys or of
+ the formatting function used to build them.
+ """
+ table = _table(transform="cast(unix_timestamp(:value) / 86400 as bigint)")
+
+ with app.app_context():
+ with patch(PROBE, return_value=[20638, 20639]):
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 7, 5),
+ to_dttm=datetime(2026, 7, 6, 12, 0),
+ )
+
+ assert "dt_epoch >= 20638" in sql
+ assert "dt_epoch <= 20639" in sql
+
+
+# ---------------------------------------------------------------------------
+# The unsafe operators — nothing is emitted
+# ---------------------------------------------------------------------------
+
+
+@pytest.mark.parametrize(
+ "flt",
+ [
+ {"col": "country", "op": FilterOperator.NOT_EQUALS.value, "val": "US"},
+ {"col": "country", "op": FilterOperator.NOT_IN.value, "val": ["US"]},
+ {"col": "country", "op": FilterOperator.LIKE.value, "val": "U%"},
+ {"col": "country", "op": FilterOperator.ILIKE.value, "val": "U%"},
+ {"col": "country", "op": FilterOperator.NOT_LIKE.value, "val": "U%"},
+ {"col": "country", "op": FilterOperator.IS_NULL.value},
+ {"col": "country", "op": FilterOperator.IS_NOT_NULL.value},
+ ],
+)
+def test_unsafe_operators_emit_nothing(app: Flask, flt: dict[str, Any]) -> None:
+ """
+ ``T`` need not be injective, so ``country != 'US'`` does not imply
+ ``region_key != 'us'`` -- mirroring it would drop rows whose ``country`` is
+ already lowercase, rows the original filter keeps.
+ """
+ table = _table(
+ transform="lower(:value)",
+ monotonic=False,
+ mapped_column="country",
+ partition_mapped_column="country",
+ partition_column="region_key",
+ )
+
+ with app.app_context():
+ with patch(PROBE, side_effect=AssertionError("probe must not run")):
+ sql = _query(table, filter=[flt])
+
+ assert "region_key" not in sql
+
+
+def test_ranges_do_not_mirror_when_the_transform_is_not_order_preserving(
+ app: Flask,
+) -> None:
+ """
+ ``hour(:value)`` is a perfectly reasonable partition transform on a
+ ``TIMESTAMP`` column and it is not monotonic, so a time range must not
+ mirror through it.
+ """
+ table = _table(transform="hour(:value)", monotonic=False)
+
+ with app.app_context():
+ with patch(PROBE, side_effect=AssertionError("probe must not run")):
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ )
+
+ assert "dt_epoch" not in sql
+
+
+def test_equality_still_mirrors_when_the_transform_is_not_order_preserving(
+ app: Flask,
+) -> None:
+ table = _table(transform="hour(:value)", monotonic=False)
+
+ with app.app_context():
+ with patch(PROBE, return_value=[13]):
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_time",
+ "op": FilterOperator.EQUALS.value,
+ "val": "2026-01-01 13:00:00",
+ }
+ ],
+ )
+
+ assert "dt_epoch = 13" in sql
+
+
+# ---------------------------------------------------------------------------
+# Bail-outs and edge cases
+# ---------------------------------------------------------------------------
+
+
+def test_nothing_mirrors_when_the_feature_flag_is_off(app: Flask) -> None:
+ table = _table()
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = False
+
+ with app.app_context():
+ with patch(PROBE, side_effect=AssertionError("probe must not run")):
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ )
+
+ assert "dt_epoch" not in sql
+
+
+def test_an_open_ended_range_mirrors_only_the_bound_it_has(app: Flask) -> None:
+ """``from_dttm``/``to_dttm`` are ``None`` for open-ended ranges."""
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1767225600]) as probe:
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=None,
+ )
+
+ assert probe.call_args.args[-1] == [datetime(2026, 1, 1)]
+ assert "dt_epoch >= 1767225600" in sql
+ assert "dt_epoch <" not in sql
+
+
+def test_no_filter_range_mirrors_nothing(app: Flask) -> None:
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, side_effect=AssertionError("probe must not run")):
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=None,
+ to_dttm=None,
+ )
+
+ assert "dt_epoch" not in sql
+
+
+def test_the_same_bound_is_not_mirrored_twice(app: Flask) -> None:
+ """
+ A ``granularity`` time filter *and* a ``TEMPORAL_RANGE`` ad-hoc filter on the
+ same column is a routine Explore configuration. Emitting the predicate twice
+ is harmless SQL but makes "View query" surprising.
+ """
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1767225600, 1769904000]):
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ filter=[
+ {
+ "col": "event_time",
+ "op": FilterOperator.TEMPORAL_RANGE.value,
+ "val": "2026-01-01 : 2026-02-01",
+ }
+ ],
+ )
+
+ assert sql.count("dt_epoch >= 1767225600") == 1
+ assert sql.count("dt_epoch <= 1769904000") == 1
+
+
+def test_always_filter_main_dttm_mirrors_the_main_column_too(app: Flask) -> None:
+ """
+ With ``always_filter_main_dttm`` the query also filters ``main_dttm_col``,
+ which is a *different* column from the one the chart grouped by. That filter
+ is the one the mapping tracks, so it has to mirror.
+ """
+ table = _table()
+ table.always_filter_main_dttm = True
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1767225600, 1769904000]):
+ sql = _query(
+ table,
+ granularity="other_time",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ )
+
+ assert "dt_epoch >= 1767225600" in sql
+ assert "dt_epoch <= 1769904000" in sql
+
+
+def test_a_failing_probe_leaves_the_query_correct_and_unpruned(app: Flask) -> None:
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=None):
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ )
+
+ assert "dt_epoch" not in sql
+ assert "event_time" in sql
+
+
+def test_a_probe_result_the_partition_column_cannot_hold_emits_nothing(
+ app: Flask,
+) -> None:
+ """
+ `cast(:value as text) || 'x'` evaluates perfectly and answers with a string,
+ and `dt_epoch` is a BIGINT. The predicate used to go out as
+ `dt_epoch >= '2026-01-01 00:00:00x'`, which Postgres refuses -- and by then
+ the mirror is in the statement, so the chart returned a 400 rather than
+ losing its pruning.
+ """
+ table = _table(transform="cast(:value as text) || 'x'")
+
+ with app.app_context():
+ probed = ["2026-01-01 00:00:00x", "2026-02-01 00:00:00x"]
+ with patch(PROBE, return_value=probed):
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ )
+
+ assert "dt_epoch" not in sql
+ assert "event_time" in sql
+
+
+def test_a_numeric_probe_result_still_mirrors_onto_a_numeric_key(
+ app: Flask,
+) -> None:
+ """The other side of the gate: the ordinary case is untouched."""
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1767225600, 1769904000]):
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ )
+
+ assert "dt_epoch >= 1767225600" in sql
+
+
+def test_a_day_key_still_mirrors_onto_a_text_partition_column(app: Flask) -> None:
+ """
+ A `to_char(:value, 'YYYYMMDD')`-style transform answers with text, and a
+ text partition column holds text. Refusing that would break the commonest
+ bucketing mapping there is.
+ """
+ table = _table(
+ transform="to_char(:value, 'YYYYMMDD')", partition_column="region_key"
+ )
+
+ with app.app_context():
+ with patch(PROBE, return_value=["20260101", "20260201"]):
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ )
+
+ assert "region_key >= '20260101'" in sql
+
+
+def test_an_inverted_transform_emits_nothing(app: Flask) -> None:
+ """
+ ``T(lower) <= T(upper)`` is a nearly-free runtime backstop for the
+ monotonicity *declaration*: it catches inverted transforms, and catches
+ ``hour()`` on any range spanning a day boundary. Necessary, not sufficient.
+ """
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1769904000, 1767225600]):
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ )
+
+ assert "dt_epoch" not in sql
+
+
+def test_incomparable_probe_results_emit_nothing(app: Flask) -> None:
+ """Probe results come back as pandas scalars; not every pair compares."""
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=[object(), object()]):
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ )
+
+ assert "dt_epoch" not in sql
+
+
+def test_self_mapping_is_skipped_defensively(app: Flask) -> None:
+ """Save-time validation rejects this, but older rows can carry it."""
+ table = _table(partition_column="event_time")
+
+ with app.app_context():
+ with patch(PROBE, side_effect=AssertionError("probe must not run")):
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ )
+
+ assert sql.count("event_time >=") == 1
+
+
+def test_a_filter_on_an_unmapped_column_mirrors_nothing(app: Flask) -> None:
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, side_effect=AssertionError("probe must not run")):
+ sql = _query(
+ table,
+ filter=[
+ {"col": "country", "op": FilterOperator.EQUALS.value, "val": "US"}
+ ],
+ )
+
+ assert "dt_epoch" not in sql
+
+
+def test_the_probe_receives_timezone_adjusted_bounds(app: Flask) -> None:
+ """
+ ``get_time_filter`` shifts the bounds by the dataset's timezone before
+ building the clause. Probing the *raw* bounds would produce epoch bounds
+ describing a different instant than the timestamp bounds they mirror --
+ wrong by exactly the offset, silently.
+
+ The bounds reach the probe as `datetime` objects here because the mapped
+ column declares no ``python_date_format``, so that *is* its stored
+ representation. See the sibling tests for a column where it is not.
+ """
+ table = _table()
+ table.extra = '{"timezone": "Europe/Berlin"}'
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1, 2]) as probe:
+ _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 9),
+ to_dttm=datetime(2026, 1, 10),
+ )
+
+ # Berlin is UTC+1 in January, so local midnight is 23:00 the day before.
+ assert probe.call_args.args[-1] == [
+ datetime(2026, 1, 8, 23, 0),
+ datetime(2026, 1, 9, 23, 0),
+ ]
+
+
+def test_the_probe_receives_hour_offset_adjusted_bounds(app: Flask) -> None:
+ """The legacy ``offset`` field shifts bounds too, and must reach the probe."""
+ table = _table()
+ table.offset = 5
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1, 2]) as probe:
+ _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 9, 12),
+ to_dttm=datetime(2026, 1, 10, 12),
+ )
+
+ assert probe.call_args.args[-1] == [
+ datetime(2026, 1, 9, 7),
+ datetime(2026, 1, 10, 7),
+ ]
+
+
+def test_the_probe_receives_an_epoch_column_s_own_representation(
+ app: Flask,
+) -> None:
+ """
+ The real predicate compares the column against `dttm_sql_literal`, which
+ for a column declaring an epoch ``python_date_format`` renders an integer.
+ So on such a column the transform is a function of an integer -- probing it
+ with a `datetime` evaluates something unrelated to the partition keys, or
+ raises, and a raise costs the dataset its pruning silently.
+ """
+ table = _table(mapped_column="event_epoch", main_dttm_col="event_epoch")
+ table.columns.append(
+ TableColumn(
+ column_name="event_epoch",
+ is_dttm=True,
+ type="BIGINT",
+ python_date_format="epoch_s",
+ )
+ )
+ table.columns[-1].partition_value_transform = "to_date(:value)"
+ table.columns[-1].partition_transform_is_monotonic = True
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1, 2]) as probe:
+ _query(
+ table,
+ granularity="event_epoch",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ )
+
+ assert probe.call_args.args[-1] == [1767225600, 1769904000]
+
+
+def test_the_probe_honours_a_per_column_date_format_from_db_extra(
+ app: Flask,
+) -> None:
+ """
+ `dttm_sql_literal` falls back to ``python_date_format_by_column_name`` in
+ the database's extra, so the probe has to read the same fallback -- on a
+ column where that fallback is actually reached. `event_epoch` is a BIGINT,
+ so SQLite's `convert_dttm` answers nothing and the format decides the
+ literal.
+
+ Its sibling below is the same configuration on a column where the engine
+ *does* answer, which is the case this test used to assert by accident.
+ """
+ table = _table(mapped_column="event_epoch", main_dttm_col="event_epoch")
+ table.columns.append(
+ TableColumn(column_name="event_epoch", is_dttm=True, type="BIGINT")
+ )
+ table.columns[-1].partition_value_transform = "to_date(:value)"
+ table.columns[-1].partition_transform_is_monotonic = True
+ table.database.extra = json.dumps(
+ {"python_date_format_by_column_name": {"event_epoch": "%Y%m%d"}}
+ )
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1, 2]) as probe:
+ _query(
+ table,
+ granularity="event_epoch",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ )
+
+ assert probe.call_args.args[-1] == ["20260101", "20260201"]
+
+
+def test_a_date_format_the_engine_literal_preempts_is_not_probed(
+ app: Flask,
+) -> None:
+ """
+ `dttm_sql_literal` asks `convert_dttm` first and reaches the format only if
+ the engine answers nothing. `event_time` is a TIMESTAMP, so SQLite answers
+ `'2026-01-01 00:00:00'` and the `%Y%m%d` format never applies to the real
+ predicate -- but the probe applied it anyway.
+
+ The mirror therefore described a different bound from the filter it stands
+ in for: `event_time >= '2026-01-01 00:00:00'` became
+ `dt_epoch >= '20260101'`, and a January 15 row keyed `2026-01-15` sorts
+ below that string, so the chart dropped a row the filter keeps.
+
+ The `datetime` goes to the probe unchanged, which is what already happens
+ for every temporal column carrying no format -- `_engine_literal_resolution`
+ then widens the bound for whatever the engine's own literal throws away.
+ """
+ table = _table()
+ table.database.extra = json.dumps(
+ {"python_date_format_by_column_name": {"event_time": "%Y%m%d"}}
+ )
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1, 2]) as probe:
+ _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ )
+
+ assert probe.call_args.args[-1] == [datetime(2026, 1, 1), datetime(2026, 2, 1)]
+
+
+def test_the_probe_rounds_outward_when_the_engine_drops_subseconds(
+ app: Flask,
+) -> None:
+ """
+ SQLite renders a timestamp with ``timespec="seconds"``, so the real lower
+ bound is floored while the probe was handed the full precision. That makes
+ the mirror *narrower* than the predicate it stands in for, and narrower
+ means it drops rows the filter keeps -- a row at ``.250000`` matches
+ ``event_time >= '2026-01-01 00:00:00'`` but not a mirror derived from
+ ``.500000``.
+
+ Rounding outward is never narrower. What it moves is the *value* the probe
+ is handed, which is what the assertion below pins -- every mirrored upper
+ bound is inclusive either way, see `mirror_operator`.
+ """
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1, 2]) as probe:
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1, 0, 0, 0, 500000),
+ to_dttm=datetime(2026, 2, 1, 0, 0, 0, 500000),
+ )
+
+ assert probe.call_args.args[-1] == [
+ datetime(2026, 1, 1, 0, 0, 0),
+ datetime(2026, 2, 1, 0, 0, 1),
+ ]
+ assert "dt_epoch <= 2" in sql
+
+
+def test_the_probe_rounds_outward_on_a_date_column_too(app: Flask) -> None:
+ """
+ The truncation test cannot be "does this render the same as the bound
+ truncated to the second". SQLite renders a DATE column at exactly midnight
+ as a bare date, so truncating a `.500000` bound crosses a *formatting*
+ boundary as well as a precision one: the two texts differ for a reason that
+ has nothing to do with precision, and the truncation that is really
+ happening goes unnoticed. Two probes that both carry a sub-second part see
+ it.
+ """
+ table = _table(mapped_column="event_date", main_dttm_col="event_date")
+ table.columns.append(
+ TableColumn(column_name="event_date", is_dttm=True, type="DATE")
+ )
+ table.columns[-1].partition_value_transform = "unix_timestamp(:value)"
+ table.columns[-1].partition_transform_is_monotonic = True
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1, 2]) as probe:
+ _query(
+ table,
+ granularity="event_date",
+ from_dttm=datetime(2026, 1, 1, 0, 0, 0, 500000),
+ to_dttm=datetime(2026, 2, 1, 0, 0, 0, 500000),
+ )
+
+ assert probe.call_args.args[-1] == [
+ datetime(2026, 1, 1, 0, 0, 0),
+ datetime(2026, 2, 1, 0, 0, 1),
+ ]
+
+
+def test_the_probe_widens_to_the_day_when_the_engine_drops_the_time(
+ app: Flask,
+) -> None:
+ """
+ Presto, Trino, BigQuery and some two dozen other specs render a DATE bound
+ as `dttm.date().isoformat()`, so a 10:00 lower bound reaches the engine as
+ `DATE '2026-01-01'` while the probe was handed 10:00. A Jan-1 row then has
+ `dt_epoch = T(DATE '2026-01-01')`, which satisfies the real predicate and
+ *fails* the mirror -- the whole first day is dropped.
+
+ Rounding to the second cannot fix this: there is no sub-second part to
+ floor, and flooring one would leave 10:00 exactly where it was.
+ """
+ table = _table(mapped_column="event_date", main_dttm_col="event_date")
+ table.columns.append(
+ TableColumn(column_name="event_date", is_dttm=True, type="DATE")
+ )
+ table.columns[-1].partition_value_transform = "unix_timestamp(:value)"
+ table.columns[-1].partition_transform_is_monotonic = True
+
+ with app.app_context():
+ with _rendering_dates_like_presto(table):
+ with patch(PROBE, return_value=[1, 2]) as probe:
+ sql = _query(
+ table,
+ granularity="event_date",
+ from_dttm=datetime(2026, 1, 1, 10, 0),
+ to_dttm=datetime(2026, 1, 2, 10, 0),
+ )
+
+ assert probe.call_args.args[-1] == [
+ datetime(2026, 1, 1, 0, 0),
+ datetime(2026, 1, 3, 0, 0),
+ ]
+ assert "dt_epoch <= 2" in sql
+
+
+def test_the_probe_widens_to_the_day_on_a_date_column_not_flagged_temporal(
+ app: Flask,
+) -> None:
+ """
+ `get_time_filter` renders a bound through `convert_dttm` for a DATE column
+ whether or not the owner ticked "Is temporal", so an unflagged DATE column
+ still compares `DATE '2026-01-01'` for a 10:00 bound. Keying the resolution
+ check on `is_dttm` alone handed the probe 10:00 there, and the mirror
+ dropped the first day.
+ """
+ table = _table(mapped_column="event_date", main_dttm_col="event_date")
+ table.columns.append(
+ TableColumn(column_name="event_date", is_dttm=False, type="DATE")
+ )
+ table.columns[-1].partition_value_transform = "unix_timestamp(:value)"
+ table.columns[-1].partition_transform_is_monotonic = True
+
+ with app.app_context():
+ with _rendering_dates_like_presto(table):
+ with patch(PROBE, return_value=[1, 2]) as probe:
+ _query(
+ table,
+ granularity="event_date",
+ from_dttm=datetime(2026, 1, 1, 10, 0),
+ to_dttm=datetime(2026, 1, 2, 10, 0),
+ )
+
+ assert probe.call_args.args[-1] == [
+ datetime(2026, 1, 1, 0, 0),
+ datetime(2026, 1, 3, 0, 0),
+ ]
+
+
+def test_a_day_resolution_bound_already_at_midnight_is_left_alone(
+ app: Flask,
+) -> None:
+ """
+ Widening is outward-only, so a bound that already sits on the day boundary
+ needs nothing done to it -- and the upper bound must not be pushed out a
+ whole extra day for no reason.
+ """
+ table = _table(mapped_column="event_date", main_dttm_col="event_date")
+ table.columns.append(
+ TableColumn(column_name="event_date", is_dttm=True, type="DATE")
+ )
+ table.columns[-1].partition_value_transform = "unix_timestamp(:value)"
+ table.columns[-1].partition_transform_is_monotonic = True
+
+ with app.app_context():
+ with _rendering_dates_like_presto(table):
+ with patch(PROBE, return_value=[1, 2]) as probe:
+ _query(
+ table,
+ granularity="event_date",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ )
+
+ assert probe.call_args.args[-1] == [
+ datetime(2026, 1, 1, 0, 0),
+ datetime(2026, 2, 1, 0, 0),
+ ]
+
+
+def test_an_equality_is_not_mirrored_when_the_engine_drops_the_time(
+ app: Flask,
+) -> None:
+ """
+ An ungrained temporal equality -- what drill-to-detail builds -- compares
+ `event_date = DATE '2026-01-01'` on such an engine, so a mirror probed with
+ 10:00 asks for a key no row holds. These entries are AND-ed onto the query,
+ so unlike a range there is nowhere to widen to: the only safe answer is to
+ emit no mirror and lose the pruning.
+ """
+ table = _table(mapped_column="event_date", main_dttm_col="event_date")
+ table.columns.append(
+ TableColumn(column_name="event_date", is_dttm=True, type="DATE")
+ )
+ table.columns[-1].partition_value_transform = "unix_timestamp(:value)"
+ table.columns[-1].partition_transform_is_monotonic = True
+
+ with app.app_context():
+ with _rendering_dates_like_presto(table):
+ with patch(PROBE, return_value=[1]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_date",
+ "op": FilterOperator.EQUALS.value,
+ "val": datetime(2026, 1, 1, 10, 0),
+ }
+ ],
+ )
+
+ probe.assert_not_called()
+ assert "dt_epoch" not in sql
+
+
+def test_an_equality_at_midnight_still_mirrors_on_a_date_column(
+ app: Flask,
+) -> None:
+ """
+ The guard above is about *lost* precision, not about DATE columns: at
+ midnight the engine's literal and the probe's value agree, so the mirror is
+ exact and the pruning is kept.
+ """
+ table = _table(mapped_column="event_date", main_dttm_col="event_date")
+ table.columns.append(
+ TableColumn(column_name="event_date", is_dttm=True, type="DATE")
+ )
+ table.columns[-1].partition_value_transform = "unix_timestamp(:value)"
+ table.columns[-1].partition_transform_is_monotonic = True
+
+ with app.app_context():
+ with _rendering_dates_like_presto(table):
+ with patch(PROBE, return_value=[1767225600]):
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_date",
+ "op": FilterOperator.EQUALS.value,
+ "val": datetime(2026, 1, 1),
+ }
+ ],
+ )
+
+ assert "dt_epoch = 1767225600" in sql
+
+
+def test_the_probe_keeps_full_precision_on_an_engine_that_does_not_truncate(
+ app: Flask,
+) -> None:
+ """
+ The widening is detected, not enumerated per engine: an engine whose
+ literal carries the sub-second part needs no rounding, and rounding anyway
+ would scan partitions for no reason.
+ """
+ table = _table()
+
+ with app.app_context():
+ with patch.object(
+ table.database.db_engine_spec,
+ "convert_dttm",
+ classmethod(lambda cls, target_type, dttm, db_extra=None: repr(dttm)),
+ ):
+ with patch(PROBE, return_value=[1, 2]) as probe:
+ _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1, 0, 0, 0, 500000),
+ to_dttm=datetime(2026, 2, 1, 0, 0, 0, 500000),
+ )
+
+ assert probe.call_args.args[-1] == [
+ datetime(2026, 1, 1, 0, 0, 0, 500000),
+ datetime(2026, 2, 1, 0, 0, 0, 500000),
+ ]
+
+
+# ---------------------------------------------------------------------------
+# The value the engine actually compares
+# ---------------------------------------------------------------------------
+
+
+def test_a_string_equality_carrying_a_time_does_not_mirror_on_a_date_column(
+ app: Flask,
+) -> None:
+ """
+ A simple filter arrives as the text the chart author typed, not as a
+ `datetime`: `filter_values_handler` rewrites only an all-digit value, which
+ it reads as epoch milliseconds. On a DATE column the engine compares that
+ text on its date part alone, so the filter keeps the whole of 2026-01-01
+ while a mirror probed at 10:00 asks for a key no row holds.
+
+ The `datetime` form of this has been covered since the day resolution was
+ detected at all -- see
+ `test_an_equality_is_not_mirrored_when_the_engine_drops_the_time`. The
+ string form is the one a user can actually produce, and it was the one that
+ dropped rows.
+ """
+ table = _mapped_date_table()
+
+ with app.app_context():
+ with _rendering_dates_like_presto(table):
+ with patch(PROBE, return_value=[1]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_date",
+ "op": FilterOperator.EQUALS.value,
+ "val": "2026-01-01 10:00:00",
+ }
+ ],
+ )
+
+ probe.assert_not_called()
+ assert "dt_epoch" not in sql
+ assert "event_date = '2026-01-01 10:00:00'" in sql
+
+
+@pytest.mark.parametrize(
+ "values",
+ [
+ ["2026-01-01 10:00:00", "2026-01-02 09:00:00"],
+ ["2026-01-01", "2026-01-02 09:00:00"],
+ ],
+ ids=["every-member-coarse", "one-member-coarse"],
+)
+def test_a_string_in_list_declines_entire_when_any_member_carries_a_time(
+ app: Flask, values: list[str]
+) -> None:
+ """
+ An `IN` list is mirrored as one predicate, so a member the engine compares
+ more coarsely than the mirror can be built from is the whole list's
+ problem. Mirroring only the members that do work would be *narrower* than
+ the filter -- the same narrowing the `None`-member guard refuses -- so the
+ list declines entire.
+ """
+ table = _mapped_date_table()
+
+ with app.app_context():
+ with _rendering_dates_like_presto(table):
+ with patch(PROBE, return_value=[1, 2]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_date",
+ "op": FilterOperator.IN.value,
+ "val": values,
+ }
+ ],
+ )
+
+ probe.assert_not_called()
+ assert "dt_epoch" not in sql
+
+
+def test_a_string_in_list_of_dates_mirrors_element_wise(app: Flask) -> None:
+ """
+ The guard above is about a *time of day*, not about `IN` on a DATE column:
+ every member at the start of its day is compared in full, so the list
+ mirrors and the pruning is kept.
+ """
+ table = _mapped_date_table()
+
+ with app.app_context():
+ with _rendering_dates_like_presto(table):
+ with patch(PROBE, return_value=[1767225600, 1767312000]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_date",
+ "op": FilterOperator.IN.value,
+ "val": ["2026-01-01", "2026-01-02"],
+ }
+ ],
+ )
+
+ assert probe.call_args.args[-1] == ["2026-01-01", "2026-01-02"]
+ assert "dt_epoch IN (1767225600, 1767312000)" in sql
+
+
+def test_a_string_lower_bound_rounds_outward_on_a_date_column(app: Flask) -> None:
+ """
+ A bound has somewhere to widen to where an equality does not. The engine
+ compares `event_date >= DATE '2026-01-05'`, so every row on 2026-01-05
+ satisfies the filter and the mirror has to admit that whole day -- which is
+ what moving the bound back to midnight does.
+ """
+ table = _mapped_date_table()
+
+ with app.app_context():
+ with _rendering_dates_like_presto(table):
+ with patch(PROBE, return_value=[1767571200]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_date",
+ "op": FilterOperator.GREATER_THAN_OR_EQUALS.value,
+ "val": "2026-01-05 10:00:00",
+ }
+ ],
+ )
+
+ assert probe.call_args.args[-1] == [datetime(2026, 1, 5, 0, 0)]
+ assert "dt_epoch >= 1767571200" in sql
+
+
+def test_a_string_upper_bound_rounds_outward_on_a_date_column(app: Flask) -> None:
+ """
+ The upper bound moves the other way, and by a whole day: the engine compares
+ `event_date < DATE '2026-01-20'`, and the mirror must not exclude the
+ partition the boundary rows live in.
+ """
+ table = _mapped_date_table()
+
+ with app.app_context():
+ with _rendering_dates_like_presto(table):
+ with patch(PROBE, return_value=[1768953600]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_date",
+ "op": FilterOperator.LESS_THAN.value,
+ "val": "2026-01-20 10:00:00",
+ }
+ ],
+ )
+
+ assert probe.call_args.args[-1] == [datetime(2026, 1, 21, 0, 0)]
+ assert "dt_epoch <= 1768953600" in sql
+
+
+def test_a_date_only_string_equality_still_mirrors_unchanged(app: Flask) -> None:
+ """
+ A value the engine compares in full is left exactly as it arrived, down to
+ the type the probe binds: reading the string back into an instant would
+ change the bind type and the probe's cache key on a query that was already
+ correct, for no gain at all.
+ """
+ table = _mapped_date_table()
+
+ with app.app_context():
+ with _rendering_dates_like_presto(table):
+ with patch(PROBE, return_value=[1767225600]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_date",
+ "op": FilterOperator.EQUALS.value,
+ "val": "2026-01-01",
+ }
+ ],
+ )
+
+ assert probe.call_args.args[-1] == ["2026-01-01"]
+ assert "dt_epoch = 1767225600" in sql
+
+
+def test_a_datetime_lower_bound_rounds_outward_instead_of_declining(
+ app: Flask,
+) -> None:
+ """
+ A `datetime` bound used to reach the same guard an equality does and
+ decline, which left a string and the `datetime` denoting the same instant
+ mirroring differently -- the asymmetry that let the string case above go
+ unnoticed. A bound widens whichever shape it arrived in.
+ """
+ table = _mapped_date_table()
+
+ with app.app_context():
+ with _rendering_dates_like_presto(table):
+ with patch(PROBE, return_value=[1767571200]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_date",
+ "op": FilterOperator.GREATER_THAN_OR_EQUALS.value,
+ "val": datetime(2026, 1, 5, 10, 0),
+ }
+ ],
+ )
+
+ assert probe.call_args.args[-1] == [datetime(2026, 1, 5, 0, 0)]
+ assert "dt_epoch >= 1767571200" in sql
+
+
+def test_a_string_filter_value_is_untouched_on_a_full_precision_engine(
+ app: Flask,
+) -> None:
+ """
+ The widening is detected, not enumerated per engine. An engine whose
+ literal carries the whole value needs none of this, and substituting an
+ instant for the text would move the probe off the cache entry every
+ already-correct query shares.
+ """
+ table = _table()
+
+ with app.app_context():
+ with patch.object(
+ table.database.db_engine_spec,
+ "convert_dttm",
+ classmethod(lambda cls, target_type, dttm, db_extra=None: repr(dttm)),
+ ):
+ with patch(PROBE, return_value=[1]) as probe:
+ _query(
+ table,
+ filter=[
+ {
+ "col": "event_time",
+ "op": FilterOperator.GREATER_THAN_OR_EQUALS.value,
+ "val": "2026-01-05 10:00:00",
+ }
+ ],
+ )
+
+ assert probe.call_args.args[-1] == ["2026-01-05 10:00:00"]
+
+
+def test_a_string_in_list_is_untouched_on_a_full_precision_engine(
+ app: Flask,
+) -> None:
+ """The `IN` counterpart: the new element-wise routing disturbs nothing."""
+ table = _table()
+
+ with app.app_context():
+ with patch.object(
+ table.database.db_engine_spec,
+ "convert_dttm",
+ classmethod(lambda cls, target_type, dttm, db_extra=None: repr(dttm)),
+ ):
+ with patch(PROBE, return_value=[1, 2]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_time",
+ "op": FilterOperator.IN.value,
+ "val": ["2026-01-01 10:00:00", "2026-01-02 09:00:00"],
+ }
+ ],
+ )
+
+ assert probe.call_args.args[-1] == [
+ "2026-01-01 10:00:00",
+ "2026-01-02 09:00:00",
+ ]
+ assert "dt_epoch IN (1, 2)" in sql
+
+
+@pytest.mark.parametrize(
+ "operator, value",
+ [
+ (FilterOperator.EQUALS.value, "07/06/2026 10:08:11"),
+ (FilterOperator.EQUALS.value, "2026/07/06 10:08:11"),
+ (FilterOperator.EQUALS.value, "July 6 2026 10:08:11"),
+ (FilterOperator.GREATER_THAN_OR_EQUALS.value, "07/05/2026 10:00:00"),
+ (FilterOperator.LESS_THAN.value, "07/20/2026"),
+ # The date-only form, which mirrored correctly by luck -- it denotes
+ # midnight, so probing the whole instant and probing the date agreed.
+ # It declines with the rest, because telling July 6 from June 7 is the
+ # guess that started this.
+ (FilterOperator.EQUALS.value, "06/07/2026"),
+ ],
+ ids=[
+ "us-equality",
+ "ymd-slashes",
+ "month-name",
+ "lower-bound",
+ "upper-bound",
+ "date-only",
+ ],
+)
+def test_an_unreadable_string_does_not_mirror_on_a_date_column(
+ app: Flask, operator: str, value: str
+) -> None:
+ """
+ Only ISO 8601 is read, because it is the one format whose meaning is not a
+ guess: ``'06/07/2026'`` as July 6 or as June 7 is a coin flip, and a mirror
+ derived from the wrong one is the silent narrowing all of this is here to
+ prevent.
+
+ Passing such a value through to the probe was the same narrowing by another
+ door. Postgres casts ``'07/06/2026 10:08:11'`` to a DATE and keeps the whole
+ of July 6, while the probe evaluated the transform at 10:08:11 and asked for
+ ``day_epoch = 1783332491`` -- a key no row holds. The chart returned 0 rows
+ where the filter matched 13, with no error and the pruning glyph still
+ showing.
+
+ A bound declines too, where a readable one widens: rounding outward needs an
+ instant to round, and there is none.
+ """
+ table = _mapped_date_table()
+
+ with app.app_context():
+ with _rendering_dates_like_presto(table):
+ with patch(PROBE, return_value=[1]) as probe:
+ sql = _query(
+ table,
+ filter=[{"col": "event_date", "op": operator, "val": value}],
+ )
+
+ probe.assert_not_called()
+ assert "dt_epoch" not in sql
+ # The filter the author wrote is still there, so the query is correct and
+ # merely unpruned -- the one failure this feature is allowed.
+ assert f"'{value}'" in sql
+
+
+def test_an_unreadable_member_declines_an_in_list_on_a_date_column(
+ app: Flask,
+) -> None:
+ """
+ One member the server cannot place is the whole list's problem, exactly as
+ one carrying a time of day is: dropping just that member mirrors a narrower
+ list than the filter and loses the rows it named.
+ """
+ table = _mapped_date_table()
+
+ with app.app_context():
+ with _rendering_dates_like_presto(table):
+ with patch(PROBE, return_value=[1, 2]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_date",
+ "op": FilterOperator.IN.value,
+ "val": ["2026-07-06", "07/07/2026 09:00:00"],
+ }
+ ],
+ )
+
+ probe.assert_not_called()
+ assert "dt_epoch" not in sql
+
+
+def test_an_unreadable_string_is_left_alone_on_a_full_precision_engine(
+ app: Flask,
+) -> None:
+ """
+ The decline belongs to the coarseness, not to the format. On a TIMESTAMP
+ column the engine compares the whole string the chart author typed, so there
+ is nothing for the server to resolve and the probe is handed the text as it
+ arrived -- which is what keeps the same non-ISO filter working on a
+ timestamp mapped column while it declines on a DATE one.
+ """
+ table = _table()
+
+ with app.app_context():
+ with patch.object(
+ table.database.db_engine_spec,
+ "convert_dttm",
+ classmethod(lambda cls, target_type, dttm, db_extra=None: repr(dttm)),
+ ):
+ with patch(PROBE, return_value=[1783332491]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_time",
+ "op": FilterOperator.EQUALS.value,
+ "val": "07/06/2026 10:08:11",
+ }
+ ],
+ )
+
+ assert probe.call_args.args[-1] == ["07/06/2026 10:08:11"]
+ assert "dt_epoch = 1783332491" in sql
+
+
+def _on_postgres(table: SqlaTable) -> SqlaTable:
+ """
+ Re-point the dataset at Postgres, whose driver over-escapes a backslash.
+
+ SQLAlchemy only learns whether the server honours a backslash escape when
+ the dialect connects, which the probe's dialect never does, so it renders
+ ``a\\b`` as ``'a\\\\b'`` and a server with the standard setting reads four
+ characters. A real backend rather than a patched helper, so the test is
+ tied to what the installed driver actually emits.
+ """
+ table.database.sqlalchemy_uri = "postgresql://user@host/db"
+ return table
+
+
+def test_a_value_the_engine_cannot_read_back_declines_rather_than_mirroring(
+ app: Flask,
+) -> None:
+ """
+ The probe evaluates the transform at a literal, so a value the driver and
+ the engine spell differently would be probed as something nobody filtered
+ on -- and the mirror would ask for a partition key holding none of the rows
+ the filter keeps. Declining costs the query its pruning and nothing else.
+ """
+ table = _on_postgres(
+ _table(
+ transform="lower(:value)",
+ monotonic=False,
+ mapped_column="country",
+ partition_mapped_column="country",
+ partition_column="region_key",
+ )
+ )
+
+ with app.app_context():
+ with patch(PROBE, return_value=["a\\b"]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "country",
+ "op": FilterOperator.EQUALS.value,
+ "val": "a\\b",
+ }
+ ],
+ )
+
+ probe.assert_not_called()
+ assert "region_key" not in sql
+ # The filter the author wrote is untouched, so the query is correct and
+ # merely unpruned.
+ assert "country = 'a" in sql
+
+
+def test_a_member_the_dialect_cannot_write_faithfully_declines_the_whole_list(
+ app: Flask,
+) -> None:
+ """
+ One member is the whole list's problem, exactly as one carrying a UTC
+ offset is: mirroring the rest would be narrower than the filter and would
+ lose the rows it named.
+ """
+ table = _on_postgres(
+ _table(
+ transform="lower(:value)",
+ monotonic=False,
+ mapped_column="country",
+ partition_mapped_column="country",
+ partition_column="region_key",
+ )
+ )
+
+ with app.app_context():
+ with patch(PROBE, return_value=["us", "a\\b"]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "country",
+ "op": FilterOperator.IN.value,
+ "val": ["US", "a\\b"],
+ }
+ ],
+ )
+
+ probe.assert_not_called()
+ assert "region_key" not in sql
+
+
+def test_a_quote_bearing_value_still_mirrors_where_the_engine_reads_it_back(
+ app: Flask,
+) -> None:
+ """
+ And the gate is not a blanket refusal of the character. On SQLite the
+ driver's doubling is the engine's own escape, so the probe asks about the
+ value the filter compares and the mirror stands.
+ """
+ table = _table(
+ transform="lower(:value)",
+ monotonic=False,
+ mapped_column="country",
+ partition_mapped_column="country",
+ partition_column="region_key",
+ )
+
+ with app.app_context():
+ with patch(PROBE, return_value=["o'brien"]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "country",
+ "op": FilterOperator.EQUALS.value,
+ "val": "O'Brien",
+ }
+ ],
+ )
+
+ probe.assert_called_once()
+ assert "region_key = 'o''brien'" in sql
+
+
+def test_an_offset_bearing_bound_declines_rather_than_narrowing(app: Flask) -> None:
+ """
+ Rounding an offset-bearing bound outward would first have to place it in the
+ frame the partition column was written in, and guessing that frame is how a
+ mirror ends up a whole offset narrower than the filter. Declining costs the
+ query its pruning and nothing else.
+ """
+ table = _mapped_date_table()
+
+ with app.app_context():
+ with _rendering_dates_like_presto(table):
+ with patch(PROBE, return_value=[1]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_date",
+ "op": FilterOperator.GREATER_THAN_OR_EQUALS.value,
+ "val": "2026-01-05T10:00:00+02:00",
+ }
+ ],
+ )
+
+ probe.assert_not_called()
+ assert "dt_epoch" not in sql
+
+
+@pytest.mark.parametrize(
+ "operator",
+ [FilterOperator.EQUALS, FilterOperator.GREATER_THAN_OR_EQUALS],
+)
+def test_an_offset_bearing_string_declines_on_a_full_resolution_column(
+ app: Flask, operator: FilterOperator
+) -> None:
+ """
+ An engine that compares the whole instant still does not help a transform
+ that drops the offset. On a TIMESTAMPTZ column with
+ `extract(epoch from CAST(:value AS TIMESTAMP))`, a row at
+ `2026-01-01 00:00:00Z` matches `event_time = '2026-01-01T01:00:00+01:00'`,
+ but the cast discards the `+01:00` and the probe asks for the key an hour
+ later -- so the mirror would exclude the row. Declined like any other
+ offset-bearing value.
+ """
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1767229200]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_time",
+ "op": operator.value,
+ "val": "2026-01-01T01:00:00+01:00",
+ }
+ ],
+ )
+
+ probe.assert_not_called()
+ assert "dt_epoch" not in sql
+
+
+@pytest.mark.parametrize(
+ "native_type, filter_value, probed",
+ [
+ # The engine compares `n = '1.0'` numerically and keeps the row holding
+ # 1, so the probe has to see the 1 the row holds, not the 1.0 typed.
+ ("INTEGER", "1.0", [1]),
+ ("INTEGER", 1.0, [1]),
+ # A non-integral value matches no integer row; nothing to protect.
+ ("INTEGER", 1.5, [1.5]),
+ # A REAL column is left alone: PostgreSQL renders the column's own
+ # value as `'1'` but the literal `1.0` as `'1.0'`, so coercing would
+ # mirror onto a key no matching row holds.
+ ("REAL", 1, [1]),
+ # A DECIMAL's text depends on a scale the spec does not expose.
+ ("DECIMAL", 1, [1]),
+ ],
+)
+def test_a_numeric_equality_is_probed_in_the_column_s_number_type(
+ app: Flask, native_type: str, filter_value: Any, probed: list[Any]
+) -> None:
+ """
+ A transform such as `CAST(:value AS TEXT)` answers differently for `1` and
+ `1.0`, so probing at the number the filter happened to carry -- rather than
+ the one the column stores -- mirrors onto a partition key no matching row
+ holds.
+ """
+ table = _table(partition_column="region_key", mapped_column="n")
+ table.columns.append(TableColumn(column_name="n", type=native_type))
+ table.partition_mapped_column = "n"
+ table.columns[-1].partition_value_transform = "CAST(:value AS TEXT)"
+ table.columns[-1].partition_transform_is_monotonic = False
+
+ with app.app_context():
+ with patch(PROBE, return_value=["1"]) as probe:
+ _query(
+ table,
+ filter=[
+ {
+ "col": "n",
+ "op": FilterOperator.EQUALS.value,
+ "val": filter_value,
+ }
+ ],
+ )
+
+ assert probe.call_args.args[-1] == probed
+ assert [type(value) for value in probe.call_args.args[-1]] == [
+ type(value) for value in probed
+ ]
+
+
+def test_a_non_temporal_string_equality_is_unaffected(app: Flask) -> None:
+ """
+ Every string value is now offered to an ISO parse, so the text mapping most
+ of this file exercises has to come out the other side unchanged: `'US'` does
+ not parse, and a VARCHAR column's `convert_dttm` answers nothing either way.
+ """
+ table = _mapped_country_table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=["us"]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {"col": "country", "op": FilterOperator.EQUALS.value, "val": "US"}
+ ],
+ )
+
+ assert probe.call_args.args[-1] == ["US"]
+ assert "region_key = 'us'" in sql
+
+
+def test_a_rounded_string_bound_dedupes_against_the_time_filter(app: Flask) -> None:
+ """
+ Rounding a string bound outward lands it on the same instant the chart's own
+ time filter already contributed, so the two collapse into one request --
+ which is what the dedupe in `_build_partition_mirror_predicates` promises
+ and what a reader of "View query" expects to see.
+ """
+ table = _mapped_date_table()
+
+ with app.app_context():
+ with _rendering_dates_like_presto(table):
+ with patch(PROBE, return_value=[1767571200, 1768953600]):
+ sql = _query(
+ table,
+ granularity="event_date",
+ from_dttm=datetime(2026, 1, 5),
+ to_dttm=datetime(2026, 1, 20),
+ filter=[
+ {
+ "col": "event_date",
+ "op": FilterOperator.GREATER_THAN_OR_EQUALS.value,
+ "val": "2026-01-05 10:00:00",
+ }
+ ],
+ )
+
+ assert sql.count("dt_epoch >=") == 1
+
+
+def test_one_probe_round_trip_per_query(app: Flask) -> None:
+ """Mirror requests are collected and resolved together, not one at a time."""
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1767225600, 1769904000]) as probe:
+ _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ filter=[
+ {
+ "col": "event_time",
+ "op": FilterOperator.TEMPORAL_RANGE.value,
+ "val": "2026-01-01 : 2026-02-01",
+ }
+ ],
+ )
+
+ probe.assert_called_once()
+
+
+def test_mirrored_predicates_reach_the_series_limit_subquery(app: Flask) -> None:
+ """
+ The mirrored predicate is appended to ``where_clause_and``, which the
+ series-limit subquery reuses -- so pruning applies there too.
+ """
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1767225600, 1769904000]):
+ sql = _query(
+ table,
+ columns=["country"],
+ metrics=["hits"],
+ granularity="event_time",
+ is_timeseries=True,
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ timeseries_limit=5,
+ timeseries_limit_metric="hits",
+ )
+
+ assert sql.count("dt_epoch >= 1767225600") >= 2
+
+
+def _split_series_limit(sql: str) -> tuple[str, str]:
+ """The ranking subquery and the outer query, as separate text."""
+ _, marker, rest = sql.partition("JOIN (SELECT")
+ assert marker, "expected a series-limit subquery"
+ subquery, _, outer = rest.partition(") AS series_limit")
+ return subquery, outer
+
+
+def test_the_series_limit_subquery_mirrors_the_inner_time_window(
+ app: Flask,
+) -> None:
+ """
+ The ranking subquery filters the *inner* window, not the outer one. On a
+ time comparison `processing_time_offsets` shifts `from_dttm`/`to_dttm` to
+ the comparison period and leaves `inner_*` on the original, so an
+ outer-window mirror in the subquery demands partition keys from a period
+ the subquery's own time filter excludes: the ranking comes back empty and
+ the join drops the comparison series entirely.
+ """
+ table = _table()
+ epochs = {
+ datetime(2025, 1, 1): 1735689600,
+ datetime(2025, 2, 1): 1738368000,
+ datetime(2026, 1, 1): 1767225600,
+ datetime(2026, 2, 1): 1769904000,
+ }
+
+ with app.app_context():
+ with patch(
+ PROBE, side_effect=lambda *args, **kwargs: [epochs[v] for v in args[-1]]
+ ):
+ sql = _query(
+ table,
+ columns=["country"],
+ metrics=["hits"],
+ granularity="event_time",
+ is_timeseries=True,
+ from_dttm=datetime(2025, 1, 1),
+ to_dttm=datetime(2025, 2, 1),
+ inner_from_dttm=datetime(2026, 1, 1),
+ inner_to_dttm=datetime(2026, 2, 1),
+ timeseries_limit=5,
+ timeseries_limit_metric="hits",
+ )
+
+ subquery, outer = _split_series_limit(sql)
+
+ # The subquery asks for the window its own time filter describes.
+ assert "dt_epoch >= 1767225600" in subquery
+ assert "dt_epoch >= 1735689600" not in subquery
+
+ # The outer query still asks for the window it was given.
+ assert "dt_epoch >= 1735689600" in outer
+ assert "dt_epoch >= 1767225600" not in outer
+
+
+def test_the_series_limit_prequery_mirrors_the_inner_window(app: Flask) -> None:
+ """
+ The other series-limit branch is already right, for a different reason: it
+ re-enters `query()` with `inner_from_dttm or from_dttm` as its own
+ `from_dttm`, so the mirrors are recomputed for the inner window rather than
+ inherited. Pinned so a future refactor cannot quietly break the half that
+ works.
+ """
+ table = _table()
+ captured: list[dict[str, Any]] = []
+
+ def _capture(query_obj: dict[str, Any]) -> Any:
+ captured.append(query_obj)
+ return MagicMock(df=pd.DataFrame({"country": []}))
+
+ with app.app_context():
+ with patch.object(table.database.db_engine_spec, "allows_joins", False):
+ with patch(PROBE, return_value=[1767225600, 1769904000]):
+ with patch.object(type(table), "query", side_effect=_capture):
+ _query(
+ table,
+ columns=["country"],
+ metrics=["hits"],
+ granularity="event_time",
+ is_timeseries=True,
+ from_dttm=datetime(2025, 1, 1),
+ to_dttm=datetime(2025, 2, 1),
+ inner_from_dttm=datetime(2026, 1, 1),
+ inner_to_dttm=datetime(2026, 2, 1),
+ timeseries_limit=5,
+ timeseries_limit_metric="hits",
+ )
+
+ assert captured, "expected a prequery"
+ assert captured[0]["from_dttm"] == datetime(2026, 1, 1)
+ assert captured[0]["to_dttm"] == datetime(2026, 2, 1)
+
+
+def test_one_probe_round_trip_when_both_windows_match(app: Flask) -> None:
+ """
+ The inner sink is collected unconditionally, but building its predicates a
+ second time would cost a second probe round trip. Every query that is not a
+ time comparison asks for the same thing twice, so the result is reused.
+ """
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1767225600, 1769904000]) as probe:
+ _query(
+ table,
+ columns=["country"],
+ metrics=["hits"],
+ granularity="event_time",
+ is_timeseries=True,
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ timeseries_limit=5,
+ timeseries_limit_metric="hits",
+ )
+
+ probe.assert_called_once()
+
+
+def test_the_series_limit_subquery_keeps_row_level_security(app: Flask) -> None:
+ """
+ The subquery takes a snapshot of `where_clause_and` from before the mirrors
+ are appended. That snapshot has to be taken *after* row level security and
+ the extras `where` go on, or swapping the mirrors would quietly drop them
+ from the ranking subquery -- which for row level security would be a
+ security bug, not a pruning one.
+ """
+ table = _table()
+
+ with app.app_context():
+ with patch.object(
+ type(table),
+ "get_sqla_row_level_filters",
+ return_value=[sa.text("country = 'US'")],
+ ):
+ with patch(PROBE, return_value=[1767225600, 1769904000]):
+ sql = _query(
+ table,
+ columns=["country"],
+ metrics=["hits"],
+ granularity="event_time",
+ is_timeseries=True,
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ timeseries_limit=5,
+ timeseries_limit_metric="hits",
+ extras={"where": "region_key <> 'x'"},
+ )
+
+ subquery, _ = _split_series_limit(sql)
+ assert "country = 'US'" in subquery
+ assert "region_key <> 'x'" in subquery
+
+
+def _mapped_country_table() -> SqlaTable:
+ """A string-column mapping: ``country`` onto ``region_key``."""
+ return _table(
+ transform="lower(:value)",
+ monotonic=False,
+ mapped_column="country",
+ partition_mapped_column="country",
+ partition_column="region_key",
+ )
+
+
+def test_string_equality_does_not_mirror_on_a_case_insensitive_engine(
+ app: Flask,
+) -> None:
+ """
+ `col = v` mirrors onto `partition_col = T(v)` on the strength of `col = v`
+ implying `T(col) = T(v)` -- true of value equality, false of SQL equality
+ under any comparison that is not byte-exact. With a case-insensitive
+ collation a stored `country` of `'us'` satisfies a filter for `'US'` while
+ the mirror `region_key = 'us'` is derived from `'US'` and excludes the row,
+ so the chart loses it with nothing to indicate why.
+ """
+ table = _mapped_country_table()
+
+ with app.app_context():
+ with patch.object(
+ table.database.db_engine_spec, "binary_string_comparison", False
+ ):
+ with patch(PROBE, return_value=["us"]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "country",
+ "op": FilterOperator.EQUALS.value,
+ "val": "US",
+ }
+ ],
+ )
+
+ assert "region_key" not in sql
+ assert "country = 'US'" in sql
+ probe.assert_not_called()
+
+
+def test_string_equality_still_mirrors_on_a_byte_exact_engine(app: Flask) -> None:
+ """
+ The gate must not cost the feature its second canonical mapping on the
+ engines it exists for, all of which compare text byte-exactly.
+ """
+ table = _mapped_country_table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=["us"]):
+ sql = _query(
+ table,
+ filter=[
+ {"col": "country", "op": FilterOperator.EQUALS.value, "val": "US"}
+ ],
+ )
+
+ assert "region_key = 'us'" in sql
+
+
+def test_a_numeric_mapped_column_is_unaffected_by_the_collation_gate(
+ app: Flask,
+) -> None:
+ """Numeric comparison is exact on every engine."""
+ table = _table(
+ transform="CAST(:value AS STRING)",
+ monotonic=False,
+ mapped_column="dt_epoch",
+ partition_mapped_column="dt_epoch",
+ partition_column="region_key",
+ )
+
+ with app.app_context():
+ with patch.object(
+ table.database.db_engine_spec, "binary_string_comparison", False
+ ):
+ with patch(PROBE, return_value=["17"]):
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "dt_epoch",
+ "op": FilterOperator.EQUALS.value,
+ "val": 17,
+ }
+ ],
+ )
+
+ assert "region_key = '17'" in sql
+
+
+def test_the_summary_withdraws_the_operators_the_query_path_withdraws(
+ app: Flask,
+) -> None:
+ """
+ The glyph reads `mirrorable_operators` off this summary, so the gate has to
+ reach it or Explore would mark a filter chip as pruned while the generated
+ SQL carries no partition predicate -- which is the whole class of bug the
+ indicator work has been closing.
+ """
+ table = _mapped_country_table()
+
+ with app.app_context():
+ with patch.object(
+ table.database.db_engine_spec, "binary_string_comparison", False
+ ):
+ summary = table.partition_filter_mapping_summary
+
+ assert summary is not None
+ assert summary["mirrorable_operators"] == []
+
+ unguarded = table.partition_filter_mapping_summary
+
+ assert unguarded is not None
+ assert unguarded["mirrorable_operators"] == ["==", "IN"]
+
+
+def test_extra_cache_keys_include_the_mapping(app: Flask) -> None:
+ """
+ The mapping changes the SQL a cached chart result came from, so it has to
+ participate in the chart-data cache key or a mapping fix leaves stale pruned
+ results behind.
+ """
+ table = _table()
+
+ with app.app_context():
+ keys = table.get_extra_cache_keys({})
+
+ assert any("dt_epoch" in str(key) for key in keys)
+
+
+def _cache_key_query_obj() -> QueryObjectDict:
+ """A query object `get_extra_cache_keys` will actually build SQL from."""
+ return {
+ "columns": ["country"],
+ "metrics": [],
+ "granularity": "event_time",
+ "is_timeseries": False,
+ "from_dttm": datetime(2026, 1, 1),
+ "to_dttm": datetime(2026, 2, 1),
+ }
+
+
+def test_extra_cache_key_extraction_does_not_probe(app: Flask) -> None:
+ """
+ `get_extra_cache_keys` builds the whole query when the dataset uses a macro
+ like `current_username()`, and it runs unconditionally *before* the chart
+ cache is consulted -- so probing there meant a synchronous warehouse round
+ trip even on a cache hit. On a relative range the chart key is deliberately
+ stable as time passes while the probe key moves every second, so the probe
+ missed every single time.
+ """
+ table = _table()
+ table.sql = "SELECT * FROM t WHERE user = '{{ current_username() }}'"
+
+ with app.app_context():
+ with patch(PROBE) as probe:
+ table.get_extra_cache_keys(_cache_key_query_obj())
+
+ probe.assert_not_called()
+
+
+def test_suppressing_the_mirror_does_not_change_the_cache_key(app: Flask) -> None:
+ """
+ Skipping the probe during key extraction is only safe because the mirrors
+ contribute nothing to `extra_cache_keys` -- those come from the Jinja
+ template processor, and the mapping's own identity is appended separately.
+ """
+ table = _table()
+ table.sql = "SELECT * FROM t WHERE user = '{{ current_username() }}'"
+ # Spelled out rather than splatting `_cache_key_query_obj()`: that is a
+ # `QueryObjectDict`, which carries keys `get_sqla_query` does not accept.
+ bounds: dict[str, Any] = {
+ "columns": ["country"],
+ "metrics": [],
+ "granularity": "event_time",
+ "is_timeseries": False,
+ "from_dttm": datetime(2026, 1, 1),
+ "to_dttm": datetime(2026, 2, 1),
+ }
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1, 2]):
+ mirrored = table.get_sqla_query(**bounds, mirror_partition_filters=True)
+ plain = table.get_sqla_query(**bounds, mirror_partition_filters=False)
+
+ assert mirrored.extra_cache_keys == plain.extra_cache_keys
+ # And the suppression really did change the SQL, so the comparison above is
+ # not vacuous.
+ assert "dt_epoch" in str(
+ mirrored.sqla_query.compile(compile_kwargs={"literal_binds": True})
+ )
+ assert "dt_epoch" not in str(
+ plain.sqla_query.compile(compile_kwargs={"literal_binds": True})
+ )
+
+
+def test_extra_cache_keys_are_unchanged_without_a_mapping(app: Flask) -> None:
+ """Cache keys must not churn for the entire installed base."""
+ table = _table(partition_column=None)
+
+ with app.app_context():
+ assert table.get_extra_cache_keys({}) == []
+
+
+# ---------------------------------------------------------------------------
+# Time grains
+# ---------------------------------------------------------------------------
+
+
+def test_a_grain_bearing_equality_filter_does_not_mirror(app: Flask) -> None:
+ """
+ Drill-to-detail sends the clicked bucket as `==` plus the chart's grain, and
+ the real predicate compares the *truncated* column. Mirroring the raw bucket
+ start would keep only the rows at the bucket's first instant and silently
+ drop the rest of the bucket.
+
+ Deferred rather than unsafe: `==` on a bucket could become a two-sided
+ range, but that needs a monotonic transform -- `EQUALS` mirrors without one
+ today -- and a parse back into a datetime.
+ """
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1767225600]):
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_time",
+ "op": FilterOperator.EQUALS.value,
+ "val": "2026-01-05",
+ "grain": "P1W",
+ }
+ ],
+ )
+
+ assert "dt_epoch" not in sql
+
+
+def test_a_grain_bearing_temporal_range_widens_both_bounds(app: Flask) -> None:
+ """
+ A grained range compares the truncated column, so the raw bounds it carries
+ do not describe the rows it keeps. Widening both ends by one bucket is the
+ smallest range guaranteed to contain all of them -- both ends, because which
+ way a grain rounds is not knowable from its duration.
+ """
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1, 2]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_time",
+ "op": FilterOperator.TEMPORAL_RANGE.value,
+ "val": "2026-01-08 : 2026-02-01",
+ "grain": "P1D",
+ }
+ ],
+ )
+
+ assert probe.call_args.args[-1] == [
+ datetime(2026, 1, 7),
+ datetime(2026, 2, 2),
+ ]
+ assert "dt_epoch" in sql
+ # Every mirrored upper bound is inclusive, widened or not -- see
+ # `mirror_operator`. What this test pins is the widening of the *value*.
+ assert "dt_epoch <= 2" in sql
+ assert "dt_epoch >= 1" in sql
+
+
+def test_a_grain_bearing_range_widens_a_month_across_the_boundary(
+ app: Flask,
+) -> None:
+ """A month is not thirty days: the widening has to be calendar arithmetic."""
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1, 2]) as probe:
+ _query(
+ table,
+ filter=[
+ {
+ "col": "event_time",
+ "op": FilterOperator.TEMPORAL_RANGE.value,
+ "val": "2026-01-31 : 2026-03-31",
+ "grain": "P1M",
+ }
+ ],
+ )
+
+ assert probe.call_args.args[-1] == [
+ datetime(2025, 12, 31),
+ datetime(2026, 4, 30),
+ ]
+
+
+def test_a_forward_rounding_grain_still_mirrors(app: Flask) -> None:
+ """
+ ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and Presto, which is
+ exactly why the widening is symmetric: a floor-only version would drop up to
+ a week of rows off the bottom of the range.
+ """
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1, 2]) as probe:
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_time",
+ "op": FilterOperator.TEMPORAL_RANGE.value,
+ "val": "2026-01-08 : 2026-02-01",
+ "grain": "P1W/1970-01-03T00:00:00Z",
+ }
+ ],
+ )
+
+ assert probe.call_args.args[-1] == [
+ datetime(2026, 1, 1),
+ datetime(2026, 2, 8),
+ ]
+ assert "dt_epoch" in sql
+
+
+def test_an_addon_grain_still_does_not_mirror(app: Flask) -> None:
+ """An operator-supplied grain has no width Superset can claim to know."""
+ table = _table()
+
+ with app.app_context():
+ # An operator declares both halves: the label and the SQL that builds it.
+ app.config["TIME_GRAIN_ADDONS"] = {"PT2S": "2 second"}
+ app.config["TIME_GRAIN_ADDON_EXPRESSIONS"] = {
+ "sqlite": {"PT2S": "DATETIME({col}, 'start of day')"}
+ }
+ try:
+ with patch(PROBE, return_value=[1, 2]):
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_time",
+ "op": FilterOperator.TEMPORAL_RANGE.value,
+ "val": "2026-01-01 : 2026-02-01",
+ "grain": "PT2S",
+ }
+ ],
+ )
+ finally:
+ app.config["TIME_GRAIN_ADDONS"] = {}
+ app.config["TIME_GRAIN_ADDON_EXPRESSIONS"] = {}
+
+ assert "dt_epoch" not in sql
+
+
+def test_a_builtin_grain_an_operator_redefined_does_not_mirror(
+ app: Flask,
+) -> None:
+ """
+ ``TIME_GRAIN_ADDON_EXPRESSIONS`` can replace a built-in grain's SQL for one
+ engine, so ``P1D`` there may have nothing to do with a day. The duration
+ alone no longer bounds the displacement.
+ """
+ table = _table()
+
+ with app.app_context():
+ app.config["TIME_GRAIN_ADDON_EXPRESSIONS"] = {
+ "sqlite": {"P1D": "DATETIME({col}, 'start of year')"}
+ }
+ try:
+ with patch(PROBE, return_value=[1, 2]):
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_time",
+ "op": FilterOperator.TEMPORAL_RANGE.value,
+ "val": "2026-01-01 : 2026-02-01",
+ "grain": "P1D",
+ }
+ ],
+ )
+ finally:
+ app.config["TIME_GRAIN_ADDON_EXPRESSIONS"] = {}
+
+ assert "dt_epoch" not in sql
+
+
+def test_widening_is_applied_after_the_timezone_adjustment(app: Flask) -> None:
+ """
+ The grain truncation happens in the frame the column is *stored* in, so the
+ bucket width has to be added there too. Widening first and converting after
+ lands an hour out across a DST boundary.
+ """
+ table = _table()
+ table.extra = '{"timezone": "Europe/Berlin"}'
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1, 2]) as probe:
+ _query(
+ table,
+ filter=[
+ {
+ "col": "event_time",
+ "op": FilterOperator.TEMPORAL_RANGE.value,
+ "val": "2026-01-09 : 2026-01-10",
+ "grain": "P1D",
+ }
+ ],
+ )
+
+ # Berlin is UTC+1 in January: adjust to 23:00 the day before, then widen.
Review Comment:
This test is documented as guarding the order of timezone adjustment and widening across a DST boundary, but both bounds sit in January where Berlin is a constant UTC+1. Widening first and converting afterwards yields the same `23:00` bounds, so reversing the two steps in `models/helpers.py` leaves it green. Could it use a range that straddles the March transition (for example `2026-03-28 : 2026-03-29`) and assert the converted-then-widened bounds?
##########
superset/datasets/api.py:
##########
@@ -2078,6 +2179,134 @@ def get(self, id_or_uuid: str, **kwargs: Any) -> Response:
entity_concurrency_token(SqlaTable, table.id, table.uuid),
)
+ @expose("/<int:pk>/partition_mapping/preview/", methods=("POST",))
+ @protect()
+ @safe
+ @statsd_metrics
+ @event_logger.log_this_with_context(
+ action=lambda self, *args, **kwargs: (
+ f"{self.__class__.__name__}.partition_mapping_preview"
+ ),
+ log_to_statsd=False,
+ )
+ def partition_mapping_preview(self, pk: int) -> Response:
+ """Preview the predicate a partition value transform would emit.
+ ---
+ post:
+ summary: Preview a partition filter mapping
+ description: >-
+ Evaluate a partition value transform at sample values and return
+ the predicate that would be appended to queries. The predicate is
+ built by the same code the query path uses, so the preview cannot
+ drift from what a chart emits. Parse and denylist checks run
+ before anything reaches the engine, so an unparseable transform
+ costs no query.
+ parameters:
+ - in: path
+ schema:
+ type: integer
+ name: pk
+ description: The dataset ID
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/PartitionMappingPreviewSchema'
+ responses:
+ 200:
+ description: Preview result
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ result:
+ type: object
+ properties:
+ valid:
+ type: boolean
+ reason:
+ type: string
+ description: >-
+ Why the mapping is not valid. Absent when it is.
+ The editor branches on this to decide how to
+ present the failure.
+ enum:
+ - unconfigured
+ - validation
+ - parse
+ - operator
+ - resolution
+ - offset
+ - escaping
+ - transform_escaping
+ - engine
+ - type
+ sample_input:
+ type: string
+ emitted_predicate:
+ type: string
+ error:
+ type: string
+ 400:
+ $ref: '#/components/responses/400'
+ 401:
+ $ref: '#/components/responses/401'
+ 403:
+ $ref: '#/components/responses/403'
+ 404:
+ $ref: '#/components/responses/404'
+ 429:
+ description: Too many preview requests for this dataset
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ message:
+ type: string
+ 500:
+ $ref: '#/components/responses/500'
+ """
+ if not is_feature_enabled("PARTITION_FILTER_MAPPING"):
+ return self.response_404()
+
+ dataset = DatasetDAO.find_by_id(pk)
+ if not dataset:
+ return self.response_404()
+ try:
+ security_manager.raise_for_editorship(dataset)
+ except SupersetSecurityException:
+ return self.response_403()
+
+ try:
+ payload = PartitionMappingPreviewSchema().load(request.json)
Review Comment:
Unlike the other JSON-body endpoints in this file, this route has no `@requires_json`. An editor who POSTs without a body or with `Content-Type: text/plain` makes `request.json` raise `UnsupportedMediaType`, which is not a `ValidationError` and falls through to the generic `@safe` handler, so the caller gets a 500 instead of a 4xx. Can the route use the same JSON guard as its neighbours?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4339385277
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,3524 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Writing the value into the probe
+--------------------------------
+The probe evaluates the transform at a *literal*, because it runs with no bound
+parameters at all -- so every value is written into SQL text by the driver's
+literal renderer and read back by the engine's lexer, and the two do not always
+agree. SQLAlchemy's default renderer doubles apostrophes and leaves backslashes
+alone; Hive honours backslash escapes and not doubling, so ``'O''Brien'`` is
+read there as two adjacent literals and ``'x\\''`` ends four characters into a
+value the filter carries whole. A disagreement is either a mirror built from a
+value nobody filtered on -- dropping rows the filter keeps -- or, where the
+value closes its own quote, an expression of the filterer's choosing running in
+the probe.
+
+Which side is right is not knowable from the driver: it is a per-session server
+setting (``standard_conforming_strings``, ``NO_BACKSLASH_ESCAPES``,
+``spark.sql.parser.escapedStringLiterals``), and SQLAlchemy's own view of it is
+only correct on a dialect that has connected. So escaping is not what makes
+this safe. `literal_round_trips` renders the literal and reads it back in the
+engine's own dialect instead, and a value that does not survive the trip is not
+mirrored -- the usual trade, pruning for correctness. `probe_sql_is_evaluable`
+re-reads the finished statement behind it.
+
+The probe's *answers* make the same trip, in the other direction. The chart
+query is compiled with ``literal_binds``, so a probed partition key is rendered
+into its SQL by the same renderer and read by the same lexer -- and
+``concat(:value, chr(92), 'b')`` turns the unremarkable input ``a`` into the key
+``a\\b``, which Hive reads back as ``a`` followed by a backspace. So
+`_predicates_from_probe` asks `literal_round_trips` about each result too, and
+declines the request rather than emitting a predicate no row can satisfy: the
+mirror is ``AND``-ed onto the query, so a mirror that matches nothing costs the
+chart its rows rather than its pruning.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: The opening and closing delimiters of each kind of Jinja block. The probe
+#: would render these in a different context at a different time from the chart
+#: query, so a transform holding one is rejected at save time.
+JINJA_BLOCK_DELIMITERS = (("{{", "}}"), ("{%", "%}"), ("{#", "#}"))
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: A PostgreSQL Unicode-escaped identifier, ``U&"..."``.
+#:
+#: The second construct that breaks the premise above, and in the same way:
+#: ``U&"\\0071uery_to_xml"(...)`` parses as an anonymous function whose name is
+#: the *literal* ``\\0071uery_to_xml``, so the function denylist is matching a
+#: name the engine never sees -- PostgreSQL decodes the escape and runs
+#: ``query_to_xml``, handing a dataset owner rows from outside their RLS scope
+#: through the preview's ``emitted_predicate``.
+#:
+#: Normalizing the escapes and re-checking would be the other repair, and is
+#: worse: it means reimplementing one engine's identifier decoding well enough
+#: to be a security boundary. Refusing the construct is exact, and costs
+#: nothing real -- a transform is a scalar function of ``:value``, and there is
+#: no reason to name a function or column through an escape sequence.
+#:
+#: Refused on every engine, like the executable comment, so a transform stored
+#: on SQLite cannot detonate when the dataset is re-pointed at PostgreSQL. The
+#: ``&`` may be separated from the ``U`` by nothing at all, but whitespace or a
+#: comment between the prefix and the string is not accepted by PostgreSQL
+#: either, so the strict form is the whole surface.
+#:
+#: Matched in raw text, so the prefix is refused inside a string literal too.
+#: That is the same trade the executable comment makes and has the same
+#: justification: a gate whose contract is to fire *before* the parse cannot
+#: ask the parse whether the text was quoted. ``concat(:value, 'u&"x"')`` is
+#: refused, which costs an owner nothing anyone writes.
+UNICODE_ESCAPED_IDENTIFIER_RE = re.compile(r'\bU&"', re.IGNORECASE)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate: a transform such as
+#: ``datediff(day, :value, LOCALTIMESTAMP)`` for a relative partition key is
+#: evaluated once and then keeps emitting yesterday's answer, so the chart
+#: silently drops rows after midnight.
+#:
+#: Matched by SQL function name, so every engine's spelling of "now" has to be
+#: named -- the ANSI four were not enough. Listed rather than delegated to the
+#: engine specs because the risk is the same everywhere and a spec that had not
+#: got round to declaring its own would fail open; a name no engine has is
+#: inert, so over-listing costs nothing.
+NON_DETERMINISTIC_FUNCTIONS = {
+ # ANSI, and the engines that spell it this way.
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "LOCALTIME",
+ "LOCALTIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+ # PostgreSQL. `now()` is statement-stable; these two are not even that.
+ "CLOCK_TIMESTAMP",
+ "STATEMENT_TIMESTAMP",
+ "TIMEOFDAY",
+ # MySQL and MariaDB.
+ "CURDATE",
+ "CURTIME",
+ "SYSDATE",
+ "UTC_DATE",
+ "UTC_TIME",
+ "UTC_TIMESTAMP",
+ "UUID_SHORT",
+ # Oracle.
+ "SYSTIMESTAMP",
+ "SYS_GUID",
+ # SQL Server.
+ "GETDATE",
+ "GETUTCDATE",
+ "SYSDATETIME",
+ "SYSUTCDATETIME",
+ "SYSDATETIMEOFFSET",
+ "NEWID",
+ # BigQuery.
+ "CURRENT_DATETIME",
+ "GENERATE_UUID",
+ # Snowflake.
+ "RANDSTR",
+ "UUID_STRING",
+ # ClickHouse.
+ "NOW64",
+ "RANDCANONICAL",
+ "GENERATEUUIDV4",
+ # H2 and Derby, which the test fixtures use.
+ "RANDOM_UUID",
+}
+
+#: The wall-clock names an engine evaluates with no parentheses at all.
+#:
+#: These parse as *column references*, not functions, so the name-based walk
+#: below cannot see them: `datediff(UTC_DATE, :value)` on MySQL and
+#: `:value - SYSDATE` on Oracle both cleared the gate and froze probe time into
+#: a cached mirror.
+#:
+#: A subset of `NON_DETERMINISTIC_FUNCTIONS` rather than the whole of it,
+#: because refusing a bare name costs an owner a column genuinely called that.
+#: Only the names SQL lets you write without ``()`` are listed -- the datetime
+#: keywords -- so `rand`, `uuid` and `newid`, which always need parentheses and
+#: are plausible column names, stay out.
+BARE_WALL_CLOCK_KEYWORDS = frozenset(
+ {
+ "current_date",
+ "current_time",
+ "current_timestamp",
+ "localtime",
+ "localtimestamp",
+ "utc_date",
+ "utc_time",
+ "utc_timestamp",
+ "sysdate",
+ "systimestamp",
+ }
+)
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+class Unmirrorable:
+ """
+ A filter no mirror can stand in for, and why.
+
+ Returned by `ExploreMixin.mirror_probe_request` for a value the engine
+ compares more coarsely than the filter carries, one it cannot render as a
+ literal, one whose rendered literal the engine would not read back as the
+ same value, one in a time frame the transform would discard, or an ``IN``
+ list with a member of any of those kinds. An object rather than `None`,
+ because `None` is a filter value in its own right.
+
+ The reason rides along because the preview has to explain the decline to
+ the owner, and the two declines want different advice: "the engine compares
+ less of this value than you typed, so map a column it compares in full" is
+ sound guidance for a `DATE` column and actively misleading for an
+ offset-bearing bound on a `TIMESTAMP` one, which already is such a column.
+ Carried rather than re-derived so the preview's explanation cannot come
+ apart from the chart path's decision.
+
+ Lives here rather than beside that method so the preview can read it too:
+ `superset.models.helpers` imports this module, so these can only cross the
+ boundary in this direction. Both callers recognise the same instances -- a
+ preview that answered "valid" for a request the chart path declines is the
+ drift this is here to prevent.
+ """
+
+ __slots__ = ("reason",)
+
+ def __init__(self, reason: str) -> None:
+ self.reason = reason
+
+ def __repr__(self) -> str:
+ return f"<Unmirrorable {self.reason}>"
+
+
+#: The ordinary decline: whatever the mirror cannot be built from, with the
+#: engine's own comparison resolution as the reason an owner can act on.
+UNMIRRORABLE = Unmirrorable("resolution")
+
+#: A value carrying a UTC offset, declined whatever the column's resolution.
+#: A transform such as ``CAST(:value AS TIMESTAMP)`` drops the offset, so even
+#: an engine that compares the whole instant would be probed in the wrong
+#: frame -- which is not something mapping a different column fixes.
+UNMIRRORABLE_OFFSET = Unmirrorable("offset")
+
+#: A value the driver and the engine would not spell the same way, declined
+#: whatever the column's resolution and whatever the operator. Nothing about
+#: the column or the transform fixes it -- see `literal_round_trips` -- so the
+#: advice the resolution reason carries would send an owner after the wrong
+#: thing entirely.
+UNMIRRORABLE_ESCAPING = Unmirrorable("escaping")
+
+
+def is_unmirrorable(value: Any) -> bool:
+ """Whether `mirror_probe_request` declined this request."""
+ return isinstance(value, Unmirrorable)
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def _native_generic_type(
+ column: "TableColumn",
+) -> utils.GenericDataType | None:
+ """
+ What the engine spec makes of ``column``'s declared type.
+
+ `TableColumn.type_generic` answers ``TEMPORAL`` for every column carrying
+ ``is_dttm``, which is the right answer for a chart's time axis and the
+ wrong one for a comparison: an epoch ``BIGINT`` is a number to the engine
+ however it is labelled here. Falls back to the flag where the spec has no
+ answer, so a type Superset cannot resolve is no worse off than before.
+ """
+ try:
+ column_spec = column.db_engine_spec.get_column_spec(
+ column.type, db_extra=column.db_extra
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ column_spec = None
+ if column_spec is not None and column_spec.generic_type is not None:
+ return column_spec.generic_type
+ try:
+ return column.type_generic
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+#: Declared types whose comparison ignores trailing blanks.
+#:
+#: The fixed-width character types, which the SQL standard has compare as
+#: though both sides were padded to the same length -- so ``'US'`` and
+#: ``'US '`` are equal in a ``CHARACTER(3)``, while ``lower()`` of the two is
+#: not. Spelled out rather than matched by prefix because the variable-width
+#: names start with the same letters: ``VARCHAR`` and ``CHARACTER VARYING``
+#: compare the blanks and must not land here.
+PADDED_CHARACTER_TYPES = frozenset(
+ {
+ "CHAR",
+ "NCHAR",
+ # PostgreSQL's own name for ``CHARACTER``, which is what reflection
+ # reports for a ``CHAR(n)`` column there.
+ "BPCHAR",
+ "CHARACTER",
+ "NATIONAL CHAR",
+ "NATIONAL CHARACTER",
+ }
+)
+
+
+def _is_padded_character_type(column: TableColumn) -> bool:
+ """
+ Whether ``column``'s declared type compares without its trailing blanks.
+
+ Read off the declared type rather than the engine spec's resolved one: the
+ specs map ``CHAR`` and ``VARCHAR`` onto the same `sqlalchemy.String`, so
+ the distinction this needs is gone by then. The length suffix is dropped
+ and the name matched against `PADDED_CHARACTER_TYPES`, so an unfamiliar
+ spelling answers ``False`` and the engine-level flag decides as before --
+ this gate adds a decline rather than lifting one. A column with no
+ declared type has nothing to read, and answers the same way.
+ """
+ if not isinstance(column.type, str):
+ return False
+ native = re.sub(r"\s+", " ", column.type.strip().upper())
+ return native.split("(")[0].strip() in PADDED_CHARACTER_TYPES
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ Padding is asked about per column, because it is a property of the *type*
+ rather than of the engine. ``binary_string_comparison`` speaks for an
+ engine's default text comparison, and on PostgreSQL -- which declares it
+ -- a ``CHAR(2)`` still matches a filter for ``'US '`` against a stored
+ ``'US'``, because the standard says a padded character type compares
+ without its trailing blanks. The mirror ``region_key = lower('US ')`` then
+ excludes the row. So a fixed-width character type declines whatever the
+ engine says, and an engine that ignores trailing blanks on its *variable*
+ types says so by not declaring the flag at all (see `RedshiftEngineSpec`).
+
+ The type asked for is the engine spec's reading of the column's declared
+ type, not `TableColumn.type_generic`, which answers ``TEMPORAL`` for
+ anything carrying ``is_dttm``. A ``VARCHAR`` flagged temporal is still text
+ to the engine: on MySQL a filter for ``'2026-01-01T00:00:00'`` matches a
+ stored ``'...t00:00:00'``, while the mirror ``p = hex('...T...')`` excludes
+ it -- and asking the semantic flag skipped the check entirely.
+
+ A type the spec cannot classify declines, which is what the paragraph above
+ promises and what only the exception branch used to do. PostgreSQL's
+ ``citext`` matches no type pattern, so it answered ``None`` -- neither
+ string nor not-string -- and was waved through, which is precisely wrong
+ for a type whose whole purpose is case-insensitive comparison. Declining
+ costs the pruning; admitting it costs rows.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ # Ahead of the generic-type question, which a padded type can lose: the
+ # specs map ``CHARACTER`` onto no generic type at all on some engines, and
+ # a fixed-width character type is a string whether or not Superset can say
+ # so from the name.
+ if _is_padded_character_type(column):
+ return False
+ generic_type = _native_generic_type(column)
+ if generic_type is None:
+ return False
+ if generic_type != utils.GenericDataType.STRING:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_unicode_escaped_identifier(transform: str | None) -> bool:
+ """Whether the transform names something through a ``U&"..."`` escape.
+
+ See `UNICODE_ESCAPED_IDENTIFIER_RE`. Answered on raw text for the same
+ reason as the comment above: the parse reports a name the engine does not
+ use, which is exactly what makes the denylist blind to it.
+ """
+ return (
+ bool(transform)
+ and UNICODE_ESCAPED_IDENTIFIER_RE.search(transform or "") is not None
+ )
+
+
+#: Sequence pseudo-columns, which advance a sequence when they are *read*.
+#:
+#: ``orders_seq.NEXTVAL`` parses as a qualified column reference, not a
+#: function call, so neither `SQLStatement.is_mutating` -- which walks function
+#: names -- nor the function denylist can see it. The probe would then run
+#: ``SELECT orders_seq.NEXTVAL + 1 FROM DUAL`` and advance the sequence, again
+#: on every cache expiry, for a dataset editor holding neither SQL Lab nor a
+#: DML grant. Reading one is a write however the parser classifies it.
+#:
+#: The function spelling (``nextval('s')`` on PostgreSQL) is a different shape
+#: and is caught as a function; this is only about the suffix form.
+SEQUENCE_PSEUDO_COLUMNS = frozenset({"nextval", "currval"})
+
+#: The same thing written as a call.
+#:
+#: Only the suffix form parses as a column; `nextval('s')` on PostgreSQL and
+#: DuckDB, `NEXTVAL(s)`/`SETVAL(s, 1)` on MySQL and MariaDB, and SQL Server's
+#: `NEXT VALUE FOR s` all parse as functions. `SQLStatement.is_mutating` walks
+#: function names on PostgreSQL alone -- deliberately, since the same names are
+#: read-only elsewhere -- so every other engine let these through.
+#:
+#: Matched on the name whatever the engine, because advancing a sequence is a
+#: write wherever it happens and a transform has no reason to call one.
+SEQUENCE_FUNCTIONS = frozenset(
+ {"nextval", "setval", "next_value_for", "nextvalfor", "prevval", "lastval"}
+)
+
+
+def references_sequence(statement: SQLStatement) -> bool:
+ """Whether the statement reads or advances a sequence.
+
+ Both spellings: the pseudo-column suffix, which parses as a column (see
+ `SEQUENCE_PSEUDO_COLUMNS`), and the call, which parses as a function (see
+ `SEQUENCE_FUNCTIONS`).
+
+ Answered on the parse rather than on raw text, because position is what
+ makes it the construct: a column or alias merely *called* ``nextval`` is
+ an ordinary column, and a string literal holding the word is text.
+ """
+ return bool(
+ statement.get_column_names() & SEQUENCE_PSEUDO_COLUMNS
+ or statement.get_disallowed_functions(set(SEQUENCE_FUNCTIONS))
+ )
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """
+ Whether the transform contains a balanced Jinja block.
+
+ A block is an opening delimiter followed, anywhere later, by its closing
+ one -- the same thing ``{{.*?}}`` and its two siblings match under
+ ``re.DOTALL``. Scanned with `str.find` rather than that pattern, because a
+ lazy match retried from every opening delimiter is quadratic in a run of
+ them, and this runs on stored transforms with no length bound of its own:
+ `is_transform_active` reads whatever the column holds. The earliest opening
+ delimiter is the only one worth trying, since any closing delimiter after a
+ later one is also after it.
+ """
+ if not transform:
+ return False
+ for opening, closing in JINJA_BLOCK_DELIMITERS:
+ start = transform.find(opening)
+ if start != -1 and transform.find(closing, start + len(opening)) != -1:
+ return True
+ return False
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+
+ Three spellings have to be looked for, because one name reaches the parse
+ three ways: as a function call, as a zero-argument call a dialect resolves
+ itself, and -- for the datetime keywords -- as a bare word that parses as a
+ column reference.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ # The parenthesis-free spellings, which parse as columns rather than
+ # functions and so are invisible to the walk above. See
+ # `BARE_WALL_CLOCK_KEYWORDS`.
+ found |= {
+ name.upper() for name in BARE_WALL_CLOCK_KEYWORDS & statement.get_column_names()
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error( # noqa: C901
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ And it must be a *read*. Shape is a separate question from effect: a bare
+ scalar expression can still write, so `SQLStatement.is_mutating` is asked
+ too -- the same question SQL Lab and the chart executor ask before letting
+ SQL run. See the gate itself for what that reaches and what it does not.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ # Also ahead of the parse, and for a stronger reason than cost: every gate
+ # below reasons about the parse tree, and this is the one construct that
+ # makes the parse tree describe a different statement from the one the
+ # engine runs. Checked here as well as in `validate_transform` because this
+ # is the door a row written by an earlier release still comes through.
+ if contains_executable_comment(transform):
+ return str(
+ _(
+ "A partition value transform cannot contain a MySQL "
+ "executable comment, which the database executes and every "
+ "validator reads as a comment."
+ )
+ )
+
+ if contains_unicode_escaped_identifier(transform):
+ return str(
+ _(
+ "A partition value transform cannot name anything through a "
+ 'U&"..." escape sequence, which the database decodes and '
+ "every validator reads literally."
+ )
+ )
+
+ # Same door, same reason: the name the denylist below would match is not
+ # the name the engine resolves. See `UNICODE_ESCAPED_IDENTIFIER_RE`.
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The read-only gate, which nothing above implies. The shape gates ask what
+ # the transform *selects*; this asks what evaluating it *does*, and a bare
+ # scalar expression can still write. `nextval(:value)` on PostgreSQL
+ # advances a sequence: one function call, no clause, no sub-query, and not
+ # in the default `DISALLOWED_SQL_FUNCTIONS` either -- so every gate above
+ # passes it and the probe then runs it. `setval` is the same shape, and
+ # `exp.Execute` and the opaque-`exp.Command` forms arrive the same way.
+ #
+ # The large-object writers (`lo_export`, `lowrite`, `lo_from_bytea`, ...)
+ # are caught here too, and the shipped denylist happens to name them as
+ # well -- but that is config an operator can replace, while this is not.
+ #
+ # `is_mutating` is the same question SQL Lab, `get_virtual_table_metadata`
+ # and the chart executor ask before letting SQL run, so a transform is held
+ # to the bar the rest of Superset already sets rather than to one invented
+ # here. Unconditional rather than gated on `Database.allow_dml`: a transform
+ # is a scalar function of `:value` by definition, so there is no legitimate
+ # mutating one, and the probe runs on a cache schedule nobody chose -- a
+ # write would repeat every time the entry expired.
+ #
+ # It bears saying what this does not reach. A user-defined function whose
+ # body writes is a plain call no parser can tell from `lower(:value)`, and
+ # `is_mutating`'s function-name walk is PostgreSQL-only by design, since the
+ # same names are read-only elsewhere. Neither residual is specific to this
+ # feature -- a dataset editor can already have the engine evaluate an
+ # arbitrary expression through a calculated column or a virtual dataset's
+ # SQL -- and closing them means authorizing the preview against the
+ # database, not parsing harder.
+ if statement.is_mutating():
+ return str(
+ _(
+ "A partition value transform cannot change data. It is "
+ "evaluated against the database to check that it mirrors, so "
+ "it has to be a read."
+ )
+ )
+
+ # Not reached by the walk above, which is why it is its own gate: a
+ # sequence pseudo-column is a *column* to the parser and a write to the
+ # engine. See `SEQUENCE_PSEUDO_COLUMNS`.
+ if references_sequence(statement):
+ return str(
+ _(
+ "A partition value transform cannot read a sequence. "
+ "NEXTVAL advances the sequence every time it is evaluated, "
+ "and the transform is evaluated on a cache schedule."
+ )
+ )
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the
+ probe uninspected. Rendering is not what makes that true: a string element
+ is checked by `literal_round_trips` before it is rendered -- the dialect's
+ literal processor and the engine's lexer do not always agree about what a
+ rendered literal says -- and `probe_sql_is_evaluable` re-reads the finished
+ query, which is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def _placeholder_is_bindable(transform: str) -> bool:
+ """
+ Whether SQLAlchemy's ``text()`` can see ``:value`` as a bound parameter.
+
+ `VALUE_PLACEHOLDER_RE` is ``:value\b``, which matches the placeholder in a
+ Postgres cast such as ``:value::bigint``. SQLAlchemy's own bind scan is
+ ``(?<![:\\w$]):([\\w$]+)(?![:\\w$])`` -- note the trailing exclusion -- so a
+ following colon stops it: ``text(":value::bigint")`` reports a parameter
+ named ``valu``, and ``.bindparams(bindparam("value"))`` then raises
+ ``ArgumentError``.
+
+ `_probe` swallows that, so the only symptom was a perfectly valid transform
+ whose mapping silently never pruned, and a preview reporting an engine
+ failure for SQL that was never sent. Every write-side gate passes the
+ transform: it parses, it is a bare expression, and the placeholder *is* in
+ an executable position.
+
+ Answered by attempting the bind itself rather than by pattern-matching
+ ``::`` or reading ``text()``'s private parameter map, so this cannot
+ disagree with what `build_probe_sql` is about to do -- on any dialect, or on
+ a SQLAlchemy whose scan changes.
+ """
+ try:
+ sa.text(transform).bindparams(sa.bindparam("value", value=None))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return False
+ return True
+
+
+def escape_foreign_colons(transform: str) -> str:
+ """
+ ``transform`` with every colon but the ``:value`` placeholder escaped.
+
+ `sqlalchemy.text` reads any ``:word`` as a bind parameter, including one
+ inside a string literal, and an unbound parameter renders as ``NULL``
+ under literal binds rather than raising. So ``:value || \':suffix\'``
+ compiled to ``'us' || 'NULL'``: the mirror asked for a partition value no
+ row holds and the chart dropped rows, with no error for `_probe` to
+ swallow and nothing on screen to say so.
+
+ Escaped rather than refused, because a colon in a literal is ordinary --
+ ``concat(:value, \':\', region)`` builds a composite key -- and the
+ placeholder is the only colon this module means to interpret. `text()`
+ reads ``\\:`` as a literal colon.
+
+ Only the bound path needs this. A `RawProbeValue` or an unbindable
+ placeholder is substituted as text by `parse_skeleton`, which never hands
+ the transform to `text()` at all.
+ """
+ pieces: list[str] = []
+ cursor = 0
+ for match in VALUE_PLACEHOLDER_RE.finditer(transform):
+ pieces.append(transform[cursor : match.start()].replace(":", r"\:"))
+ pieces.append(match.group(0))
+ cursor = match.end()
+ pieces.append(transform[cursor:].replace(":", r"\:"))
+ return "".join(pieces)
+
+
+def literal_round_trips(value: Any, dialect: Dialect | None, engine: str) -> bool:
+ """
+ Whether the engine reads a rendered ``value`` back as that same value.
+
+ The probe runs with no bound parameters, so every value reaches the engine
+ as literal text the driver wrote (see `build_probe_sql`). Whether that text
+ says what the value says is a question about two independent spellings: the
+ driver's escaping, and the engine's lexer. SQLAlchemy's default renderer
+ doubles apostrophes and passes backslashes through; Hive and Spark honour
+ the backslash and not the doubling, so ``'O''Brien'`` is read there as two
+ adjacent literals -- the transform is evaluated at ``OBrien``, and the
+ mirror asks for a partition key that holds none of the rows the filter
+ keeps. The same gap in the other direction lets a value close its own quote
+ and have the rest of it read as SQL.
+
+ Escaping is not the repair. Whether a backslash introduces an escape is a
+ per-session server setting -- ``standard_conforming_strings`` on Postgres,
+ ``NO_BACKSLASH_ESCAPES`` on MySQL, ``escapedStringLiterals`` on Spark -- and
+ nothing in the engine specs exposes it. SQLAlchemy reads it off the server
+ into ``_backslash_escapes`` during ``initialize(connection)``, which the
+ probe's dialect never reaches: `_dialect_for` asks the ``Database`` for a
+ dialect, not for a connection, so Postgres renders ``a\\b`` as
+ ``'a\\\\b'`` and a server with the standard setting reads four
+ characters. An engine-spec flag would have to be defaulted, and either
+ default is wrong for a dozen engines: one leaves the hole open, the other
+ corrupts the probed value.
+
+ So the premise is verified rather than declared, the way
+ `probe_sql_is_evaluable` verifies the finished statement. A value that does
+ not survive the round trip is not mirrored, which costs the query its
+ pruning and nothing else.
+
+ The short-circuit is a proof, not a guess, and it matters for cost: a
+ 200-member ``IN`` list would otherwise parse 200 times on the chart path.
+ If the renderer emitted the value between two quotes and changed nothing in
+ it, and the value carries neither a quote nor a backslash, then no lexer in
+ play can read it as anything but itself. Both exclusions are load-bearing:
+ on Hive ``a\\b`` renders verbatim and reads as ``a`` followed by a
+ backspace.
+
+ :param value: a filter value about to be rendered into the probe
+ :param dialect: the dialect that will render it, as `_dialect_for` reports
+ :param engine: ``database.backend``, whose lexer reads the result
+ :return: whether the two agree about what the literal says
+ """
+ if isinstance(value, RawProbeValue):
+ # Already SQL, with no single value for a parse to be compared against:
+ # its elements are checked before they are rendered, by
+ # `ExploreMixin._array_mirror_probe_value`. A backslash surviving into
+ # the finished text is refused here all the same, as the backstop for a
+ # renderer this module does not own.
+ return "\\" not in value.sql
+ if not isinstance(value, str):
+ # Numbers and instants are not written between delimiters, so there is
+ # no escaping for the two sides to disagree about.
+ return True
+
+ rendered = _compile_literal(sa.literal(value), dialect)
+ if rendered == f"'{value}'" and "'" not in value and "\\" not in value:
+ return True
+
+ try:
+ return (
+ SQLStatement(f"SELECT {rendered}", engine).get_select_literal_value()
+ == value
+ )
+ except SupersetParseError:
+ # A rendered literal the engine's own dialect will not parse is the
+ # strongest form of disagreement there is.
+ return False
+
+
+def value_round_trips(database: Database, value: Any) -> bool:
+ """
+ `literal_round_trips` for a caller holding a database, not a dialect.
+
+ Which renderer and which lexer apply is this module's business, so the two
+ callers outside it -- the chart path's own gate in
+ `ExploreMixin.mirror_probe_request` and the mapping summary Explore reads
+ -- ask in these terms and stay out of it.
+
+ :param database: the database whose driver renders and whose engine reads
+ :param value: a filter value about to be rendered into the probe
+ :return: whether the two agree about what the literal says
+ """
+ return literal_round_trips(value, _dialect_for(database), database.backend)
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text. That is not itself a boundary:
+ the processor's escaping is not always the escaping the engine honours, and
+ a value can close its own quote through the gap. The boundary is
+ `literal_round_trips` on the way in -- which callers must have run, like
+ `stored_expression_error` below -- and `probe_sql_is_evaluable` on the way
+ out.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ bindable = _placeholder_is_bindable(transform)
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ elif bindable:
+ # Every other colon escaped first: `text()` would read one inside a
+ # string literal as a second bind parameter and render it `NULL`.
+ # See `escape_foreign_colons`.
+ clause = sa.text(escape_foreign_colons(transform)).bindparams(
+ sa.bindparam("value", value=value)
+ )
+ rendered = _compile_literal(clause, dialect)
+ else:
+ # `text()` cannot see the placeholder (see
+ # `_placeholder_is_bindable`), so the value is rendered by the
+ # dialect's own literal processor first and substituted as SQL
+ # text. The same two steps in the other order: binding exists to
+ # get the value through that processor, and `_compile_literal`
+ # inlines the result either way, so this is the same string by a
+ # different route -- not a loosening of the "never interpolate a
+ # raw value" rule. `parse_skeleton` substitutes literally, so the
+ # rendered literal arrives here exactly as it was rendered, which
+ # is what makes `literal_round_trips`' verdict on it good for this
+ # branch as much as for the bound one.
+ rendered = parse_skeleton(
+ transform, _compile_literal(sa.literal(value), dialect)
+ )
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Five things have to hold, and all five are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+ * No comment, anywhere. A value that closes its own quote has to hide the
+ text `build_probe_sql` appended after it, and a comment is the only way
+ to do that and still balance the quotes -- so this is what makes the
+ alias check above sufficient rather than merely necessary. Read off the
+ parse rather than the text, so a comment *inside* a literal is data and
+ costs no pruning, and so the question is asked in the engine's own
+ dialect. A transform has no legitimate reason to carry one either; see
+ `EXECUTABLE_COMMENT_RE`.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ # Before the parse, because this gate's whole contract is that what the
+ # parse describes is what the engine will run, and an executable comment is
+ # precisely the text where that stops being true. The transform is already
+ # refused for carrying one; this covers the compiled statement, so no later
+ # change to how values are rendered can reintroduce it behind the gates
+ # below.
+ if contains_executable_comment(sql) or contains_unicode_escaped_identifier(sql):
+ return False
+
+ try:
+ script = SQLScript(sql, engine)
Review Comment:
The gate parses the compiled probe with the dialect's default string rules, but on MySQL with `NO_BACKSLASH_ESCAPES` the server reads `\` differently. A transform such as `:value + LENGTH('\') + (SELECT secret_number FROM vault LIMIT 1) -- ')` parses here as one string literal, so `has_subquery()`, `has_comment()` and the `v0` alias check all pass, while that server sees a real sub-select and a trailing comment that swallows the appended alias. The preview then returns the other table's value through `emitted_predicate`, without RLS or table access checks, to anyone who can edit the dataset. Could the gate decline MySQL probes when the transform contains a backslash (or when the session's SQL mode is not known to be the default)?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #43870:
URL: https://github.com/apache/superset/pull/43870#issuecomment-5961993219
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers an incremental AI Review.
- `/review full` - Manually triggers a full AI Review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #43870:
URL: https://github.com/apache/superset/pull/43870#issuecomment-6010205860
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers an incremental AI Review.
- `/review full` - Manually triggers a full AI Review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4234368173
##########
tests/unit_tests/datasets/partition_mapping_preview_test.py:
##########
@@ -0,0 +1,1190 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+The partition mapping preview endpoint.
+
+This route fires a real warehouse query from a text input in the dataset
+editor, so the order of its guards is the point: parse and denylist checks run
+*before* anything reaches the engine, which is what keeps a half-typed
+expression from costing a query at all.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+from unittest.mock import MagicMock, patch
+
+import pytest
+from flask import Flask
+from sqlalchemy.orm.session import Session
+
+from superset import db
+
+PROBE = "superset.connectors.sqla.partition_mapping.evaluate_transform"
+
+
+@pytest.fixture(autouse=True)
+def enable_partition_filter_mapping(app: Flask) -> Any:
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = True
+ yield
+ del app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"]
+
+
+@pytest.fixture(autouse=True)
+def real_cache(app: Flask) -> Any:
+ """
+ The test app runs a null cache, which would make the rate limiter a no-op.
+ """
+ from flask_caching import Cache
+
+ from superset.extensions import cache_manager
+
+ cache = Cache(config={"CACHE_TYPE": "SimpleCache", "CACHE_DEFAULT_TIMEOUT": 300})
+ cache.init_app(app)
+ original = cache_manager._cache # noqa: SLF001
+ cache_manager._cache = cache # noqa: SLF001
+ yield
+ cache_manager._cache = original # noqa: SLF001
+
+
+@pytest.fixture(autouse=True)
+def allow_editorship(mocker: Any) -> Any:
+ """
+ The route gates on per-object editorship on top of ``@protect()``. The unit
+ test app has no real roles, so grant it here rather than in every test.
+ """
+ mocker.patch(
+ "superset.datasets.api.security_manager.raise_for_editorship",
+ )
+
+
+@pytest.fixture
+def dataset(session: Session) -> Any:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.models.core import Database
+
+ SqlaTable.metadata.create_all(db.session.get_bind())
+ database = Database(database_name="my_db", sqlalchemy_uri="sqlite://")
+ table = SqlaTable(
+ table_name="web_events",
+ database=database,
+ main_dttm_col="event_time",
+ columns=[
+ TableColumn(column_name="event_time", is_dttm=True, type="TIMESTAMP"),
+ TableColumn(column_name="dt_epoch", type="BIGINT"),
+ # A second, text-typed partition key. A transform that answers with
+ # text cannot be previewed against `dt_epoch` -- the predicate it
+ # would emit is `dt_epoch = 'us'`, which the database refuses, and
+ # `probed_value_type_error` says so before the preview can call it
+ # valid. Tests whose transform answers with text point here.
+ TableColumn(column_name="region_key", type="VARCHAR"),
+ # And a temporal one, for a transform that answers with a date or a
+ # timestamp. `region_key` will not do: the type gate holds a text
+ # key to text results, because not every engine accepts anything
+ # else in a text comparison and one of them compares it as never
+ # equal rather than refusing it.
+ TableColumn(column_name="part_ts", type="TIMESTAMP"),
+ # A text *mapped* column. A temporal one will not stand in for it:
+ # a sample that is not an ISO instant declines on a column the
+ # engine compares more coarsely than the value carries, which is
+ # the right answer there and noise in a test about anything else.
+ TableColumn(column_name="country", type="VARCHAR"),
+ ],
+ )
+ table.partition_column = "dt_epoch"
+ db.session.add(table)
+ db.session.flush()
+ return table
+
+
+def test_preview_returns_the_emitted_predicate(
+ client: Any, full_api_access: None, dataset: Any
+) -> None:
+ with patch(PROBE, return_value=[1768435200]):
+ response = client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={
+ "mapped_column": "event_time",
+ "value_transform": "unix_timestamp(:value)",
+ "sample_values": ["2026-01-15 00:00:00"],
+ },
+ )
+
+ assert response.status_code == 200
+ assert response.json["result"] == {
+ "valid": True,
+ "sample_input": "event_time == '2026-01-15 00:00:00'",
+ "emitted_predicate": "dt_epoch = 1768435200 OR dt_epoch IS NULL",
+ }
+
+
+def test_preview_mirrors_a_range_when_the_transform_is_monotonic(
+ client: Any, full_api_access: None, dataset: Any
+) -> None:
+ """
+ The case the whole feature exists for: an Explore time range bound.
+ """
+ with patch(PROBE, return_value=[1768435200]):
+ response = client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={
+ "mapped_column": "event_time",
+ "value_transform": "unix_timestamp(:value)",
+ "sample_values": ["2026-01-15 00:00:00"],
+ "operator": ">=",
+ "is_monotonic": True,
+ },
+ )
+
+ assert response.json["result"] == {
+ "valid": True,
+ "sample_input": "event_time >= '2026-01-15 00:00:00'",
+ "emitted_predicate": "dt_epoch >= 1768435200 OR dt_epoch IS NULL",
+ }
+
+
+def test_preview_shows_a_strict_bound_mirroring_non_strictly(
+ client: Any, full_api_access: None, dataset: Any
+) -> None:
+ """
+ The preview and the query path agree only because both go through
+ `build_mirrored_predicates`. A preview rendering `<` while the chart emitted
+ `<=` would be the editor claiming something the SQL does not do.
+
+ `sample_input` describes the owner's filter and `emitted_predicate` the
+ mirror, so the two carrying different operators is the behaviour under test
+ rather than a defect.
+ """
+ with patch(PROBE, return_value=[1768435200]):
+ response = client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={
+ "mapped_column": "event_time",
+ "value_transform": "unix_timestamp(:value)",
+ "sample_values": ["2026-01-15 00:00:00"],
+ "operator": "<",
+ "is_monotonic": True,
+ },
+ )
+
+ assert response.json["result"] == {
+ "valid": True,
+ "sample_input": "event_time < '2026-01-15 00:00:00'",
+ "emitted_predicate": "dt_epoch <= 1768435200 OR dt_epoch IS NULL",
+ }
+
+
+def test_preview_refuses_a_range_when_the_transform_is_not_monotonic(
+ client: Any, full_api_access: None, dataset: Any
+) -> None:
+ """
+ Refusing here rather than showing a predicate is the point: the query path
+ would not mirror this filter either, and a preview that implied otherwise
+ would be the one thing worse than no preview.
+ """
+ with patch(PROBE, side_effect=AssertionError("probe must not run")):
+ response = client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={
+ "mapped_column": "event_time",
+ "value_transform": "unix_timestamp(:value)",
+ "sample_values": ["2026-01-15 00:00:00"],
+ "operator": ">=",
+ "is_monotonic": False,
+ },
+ )
+
+ result = response.json["result"]
+ assert result["valid"] is False
+ assert "preserves ordering" in result["error"]
+
+
+def test_preview_names_the_comparison_when_text_equality_cannot_mirror(
+ client: Any, full_api_access: None, dataset: Any
+) -> None:
+ """
+ On an engine whose string comparison is not byte-exact, `=` and `IN` on a
+ text column are withdrawn whatever the owner declares about ordering. The
+ reason has to say so, or it sends them to a checkbox that changes nothing.
+ """
+ with patch.object(
+ dataset.database.db_engine_spec, "binary_string_comparison", False
+ ):
+ with patch(PROBE, side_effect=AssertionError("probe must not run")):
+ response = client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={
+ "mapped_column": "country",
+ "partition_column": "region_key",
+ "value_transform": "lower(:value)",
+ "sample_values": ["US"],
+ "operator": "IN",
+ "is_monotonic": True,
+ },
+ )
+
+ result = response.json["result"]
+ assert result["valid"] is False
+ assert result["reason"] == "operator"
+ assert "preserves ordering" not in result["error"]
+ assert "case or trailing spaces" in result["error"]
+
+
+def test_preview_mirrors_in_element_wise(
+ client: Any, full_api_access: None, dataset: Any
+) -> None:
+ """
+ Wireframe 1h: a non-temporal mapping previews as an `IN`, not as a `>=`
+ against the first value.
+ """
+ with patch(PROBE, return_value=["us", "ca"]):
+ response = client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={
+ "mapped_column": "country",
+ "partition_column": "region_key",
+ "value_transform": "lower(:value)",
+ "sample_values": ["US", "CA"],
+ "operator": "IN",
+ },
+ )
+
+ assert response.json["result"] == {
+ "valid": True,
+ "sample_input": "country IN ('US', 'CA')",
+ "emitted_predicate": "region_key IN ('us', 'ca') OR region_key IS NULL",
+ }
+
+
+def test_preview_rejects_an_operator_that_can_never_mirror(
+ client: Any, full_api_access: None, dataset: Any
+) -> None:
+ response = client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={
+ "mapped_column": "event_time",
+ "value_transform": "unix_timestamp(:value)",
+ "sample_values": ["2026-01-15 00:00:00"],
+ "operator": "NOT IN",
+ },
+ )
+
+ assert response.status_code == 400
+
+
+def test_preview_reports_a_parse_error_without_touching_the_engine(
+ client: Any, full_api_access: None, dataset: Any
+) -> None:
+ """
+ Validate first, probe second. A half-typed transform is by definition
+ unparseable, which is most of the traffic a debounced text input produces.
+ """
+ with patch(PROBE, side_effect=AssertionError("probe must not run")):
+ response = client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={
+ "mapped_column": "event_time",
+ "value_transform": "unix_timestamp(:value",
+ "sample_values": ["2026-01-15 00:00:00"],
+ },
+ )
+
+ assert response.status_code == 200
+ assert response.json["result"]["valid"] is False
+ assert response.json["result"]["error"]
+
+
+def test_preview_rejects_a_non_deterministic_transform(
+ client: Any, full_api_access: None, dataset: Any
+) -> None:
+ with patch(PROBE, side_effect=AssertionError("probe must not run")):
+ response = client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={
+ "mapped_column": "event_time",
+ "value_transform": "unix_timestamp()",
+ "sample_values": ["2026-01-15 00:00:00"],
+ },
+ )
+
+ assert response.json["result"]["valid"] is False
+
+
+def test_preview_reports_an_unknown_mapped_column(
+ client: Any, full_api_access: None, dataset: Any
+) -> None:
+ with patch(PROBE, side_effect=AssertionError("probe must not run")):
+ response = client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={
+ "mapped_column": "nope",
+ "value_transform": "unix_timestamp(:value)",
+ "sample_values": ["2026-01-15 00:00:00"],
+ },
+ )
+
+ assert response.json["result"]["valid"] is False
+
+
+def test_preview_refuses_a_transform_whose_result_the_key_cannot_hold(
+ client: Any, full_api_access: None, dataset: Any
+) -> None:
+ """
+ The one verdict a preview must never give: "Valid" for a mapping that makes
+ every chart fail. `cast(:value as text) || 'x'` evaluates perfectly, so the
+ probe succeeds -- and the preview went on to render the predicate the chart
+ would carry, `dt_epoch >= '2026-01-15 00:00:00x'` against a BIGINT, which
+ Postgres answers with a 400.
+
+ Its own `reason`, because "the database would not evaluate this" and "it
+ evaluated and answered with the wrong kind of thing" are different problems
+ and only the owner can say which transform they meant.
+ """
+ with patch(PROBE, return_value=["2026-01-15 00:00:00x"]):
+ response = client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={
+ "mapped_column": "event_time",
+ "value_transform": "cast(:value as text) || 'x'",
+ "sample_values": ["2026-01-15 00:00:00"],
+ },
+ )
+
+ assert response.status_code == 200
+ result = response.json["result"]
+ assert result["valid"] is False
+ assert result["reason"] == "type"
+ assert "dt_epoch" in result["error"]
+ assert result["sample_input"] == "event_time == '2026-01-15 00:00:00'"
+
+
+def test_preview_refuses_a_number_against_a_text_partition_key(
+ client: Any, full_api_access: None, dataset: Any
+) -> None:
+ """
+ The mirror image, and the one that used to be exempt. A text partition key
+ was held to no type at all, on the belief that every engine takes a number
+ in a text comparison -- but Postgres refuses `character varying = integer`,
+ Trino `varchar = bigint` and BigQuery `STRING = INT64`, so the preview said
+ "Valid" for a mapping whose every chart 400s.
+
+ SQLite is the reason this is a decline rather than a coercion: it raises
+ nothing and compares a number against text as never equal, so the mirror
+ would silently drop every row the filter keeps.
+ """
+ with patch(PROBE, return_value=[1768435200]):
+ response = client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={
+ "mapped_column": "event_time",
+ "partition_column": "region_key",
+ "value_transform": "unix_timestamp(:value)",
+ "sample_values": ["2026-01-15 00:00:00"],
+ },
+ )
+
+ assert response.status_code == 200
+ result = response.json["result"]
+ assert result["valid"] is False
+ assert result["reason"] == "type"
+ assert "region_key" in result["error"]
+ assert "string" in result["error"]
+
+
+def test_preview_mirrors_text_against_a_text_partition_key(
+ client: Any, full_api_access: None, dataset: Any
+) -> None:
+ """The other half: a text key still takes a transform that answers text."""
+ with patch(PROBE, return_value=["20260115"]):
+ response = client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={
+ "mapped_column": "event_time",
+ "partition_column": "region_key",
+ "value_transform": "to_char(:value, 'YYYYMMDD')",
+ "sample_values": ["2026-01-15 00:00:00"],
+ },
+ )
+
+ assert response.status_code == 200
+ result = response.json["result"]
+ assert result["valid"] is True
+ assert "'20260115'" in result["emitted_predicate"]
+
+
+def test_preview_reports_a_failed_probe_rather_than_erroring(
+ client: Any, full_api_access: None, dataset: Any
+) -> None:
+ with patch(PROBE, return_value=None):
+ response = client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={
+ "mapped_column": "event_time",
+ "value_transform": "unix_timestamp(:value)",
+ "sample_values": ["2026-01-15 00:00:00"],
+ },
+ )
+
+ assert response.status_code == 200
+ assert response.json["result"]["valid"] is False
+
+
+def test_preview_404s_for_an_unknown_dataset(
+ client: Any, full_api_access: None, dataset: Any
+) -> None:
+ response = client.post(
+ "/api/v1/dataset/99999/partition_mapping/preview/",
+ json={
+ "mapped_column": "event_time",
+ "value_transform": "unix_timestamp(:value)",
+ "sample_values": ["2026-01-15"],
+ },
+ )
+ assert response.status_code == 404
+
+
+def test_preview_is_gated_on_the_feature_flag(
+ app: Flask, client: Any, full_api_access: None, dataset: Any
+) -> None:
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = False
+
+ response = client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={
+ "mapped_column": "event_time",
+ "value_transform": "unix_timestamp(:value)",
+ "sample_values": ["2026-01-15"],
+ },
+ )
+ assert response.status_code == 404
+
+
+def test_preview_rejects_an_invalid_payload(
+ client: Any, full_api_access: None, dataset: Any
+) -> None:
+ response = client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={"nonsense": True},
+ )
+ assert response.status_code == 400
+
+
+def test_preview_is_rate_limited_per_user_and_dataset(
+ app: Flask, client: Any, full_api_access: None, dataset: Any
+) -> None:
+ """
+ Debouncing is a client-side courtesy, not a guard: a held keydown, or a few
+ owners with the editor open, is sustained load on a production cluster.
+ """
+ app.config["PARTITION_TRANSFORM_PREVIEW_RATE_LIMIT"] = 2
+
+ payload = {
+ "mapped_column": "event_time",
+ "value_transform": "unix_timestamp(:value)",
+ "sample_values": ["2026-01-15"],
+ }
+ with patch(PROBE, return_value=[1]):
+ statuses = [
+ client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={**payload, "sample_values": [f"2026-01-{day:02d}"]},
+ ).status_code
+ for day in range(1, 5)
+ ]
+
+ assert statuses[:2] == [200, 200]
+ assert 429 in statuses[2:]
+
+
+def test_the_budget_is_spent_exactly_once_per_request(
+ app: Flask, client: Any, full_api_access: None, dataset: Any
+) -> None:
+ """
+ Counting is `add` then `inc`, so the first request of a window and every
+ one after it cost the same single unit. A read-then-write pair would let
+ concurrent previews all observe the same sub-limit value and all through.
+ """
+ app.config["PARTITION_TRANSFORM_PREVIEW_RATE_LIMIT"] = 3
+
+ payload = {
+ "mapped_column": "event_time",
+ "value_transform": "unix_timestamp(:value)",
+ "sample_values": ["2026-01-15"],
+ }
+ with patch(PROBE, return_value=[1]):
+ statuses = [
+ client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={**payload, "sample_values": [f"2026-01-{day:02d}"]},
+ ).status_code
+ for day in range(1, 6)
+ ]
+
+ assert statuses == [200, 200, 200, 429, 429]
Review Comment:
The limiter buckets on `int(time.time()) // PREVIEW_RATE_LIMIT_WINDOW`, and this test sends five real requests without freezing the clock. If the minute rolls over after the third request, the new bucket starts from zero and the statuses come back `[200, 200, 200, 200, 200]`, so the assertion fails on an otherwise correct build; `test_preview_is_rate_limited_per_user_and_dataset` above (`429 in statuses[2:]`) has the same exposure. Could both sequences run under `patch("superset.datasets.api.time.time", return_value=...)` like the window-reset test below?
##########
superset/models/helpers.py:
##########
@@ -4334,36 +4432,715 @@ def dttm_sql_literal(self, dttm: datetime, col: "TableColumn") -> str:
return f"""'{dttm.strftime("%Y-%m-%d %H:%M:%S.%f")}'"""
- def get_time_filter( # pylint: disable=too-many-arguments # noqa: C901
+ def _mirror_probe_value(self, dttm: datetime, col: Optional["TableColumn"]) -> Any:
+ """
+ ``dttm`` in the mapped column's own stored representation.
+
+ The predicate this mirror stands in for compares the column against
+ `dttm_sql_literal(dttm, col)`, so the transform has to be probed with
+ the same value. On a column stored as an epoch integer, ``T`` is a
+ function of an integer: probing it with a `datetime` either returns
+ something unrelated to the partition keys or raises, and a raise costs
+ the dataset its pruning silently.
+
+ Only the ``python_date_format`` branches of `dttm_sql_literal` are
+ reproduced, because only those produce a *value*. `convert_dttm` yields
+ engine-specific SQL text, which cannot be bound as a parameter; its own
+ divergence from the probe is handled by widening the bounds instead
+ (`_engine_literal_resolution`).
+
+ In `dttm_sql_literal`'s own order, though: it asks ``convert_dttm``
+ first and reaches the format only when the engine answers nothing. A
+ column can carry both -- a TIMESTAMP with a ``%Y%m%d``
+ ``python_date_format``, or an entry in
+ ``python_date_format_by_column_name`` -- and applying the format
+ unconditionally probed a value the real predicate never compares.
+ ``event_time >= '2026-01-01 00:00:00'`` mirrored as
+ ``partition_col >= '20260101'``, and a January 15 row keyed
+ ``2026-01-15`` sorts below that string, so the chart lost a row the
+ filter keeps.
+
+ Where the engine does answer, the `datetime` is returned unchanged and
+ the widening path takes over -- which is exactly what already happens
+ for every temporal column that carries no format at all.
+ """
+ if col is None:
+ return dttm
+
+ if col.type and self.db_engine_spec.convert_dttm(
+ col.type, dttm, db_extra=self.db_extra
+ ):
+ # The format is unreachable in `dttm_sql_literal` for this column,
+ # so reproducing it here would describe a different bound.
+ return dttm
+
+ tf = col.python_date_format
+ if not tf and self.db_extra:
+ tf = self.db_extra.get("python_date_format_by_column_name", {}).get(
+ col.column_name
+ )
+ if not tf:
+ return dttm
+
+ if tf in EPOCH_FORMATS:
+ dttm_tz_aware = dttm
+ if dttm_tz_aware.tzinfo is None:
+ dttm_tz_aware = dttm_tz_aware.replace(tzinfo=timezone.utc)
+ return int(dttm_tz_aware.timestamp()) * EPOCH_FORMATS[tf]
+ return dttm.strftime(tf)
+
+ def _engine_literal_resolution(
+ self, dttm: datetime, col: Optional["TableColumn"]
+ ) -> LiteralResolution:
+ """
+ How much of ``dttm`` survives into this engine's literal for ``col``.
+
+ The real predicate compares `dttm_sql_literal(dttm, col)`, so whatever
+ that literal throws away is a bound the engine never sees. A mirror
+ derived from the full precision then describes a *narrower* range than
+ the predicate it stands in for -- and narrower means it drops rows the
+ filter keeps.
+
+ Two things get thrown away in practice:
+
+ - the sub-second part. SQLite renders a timestamp with
+ ``timespec="seconds"``.
+ - the time of day entirely. Every engine spec with a ``types.Date``
+ branch renders ``dttm.date().isoformat()``, so Presto, Trino,
+ BigQuery and some two dozen others answer `DATE '2026-01-01'` for a
+ bound of 10:00 -- and `T(DATE '2026-01-01')` is below the mirror's
+ own lower bound, so the whole first day is dropped.
+
+ Detected rather than enumerated per engine, because the branch depends
+ on the column's type as well as the spec: instants differing only in the
+ part under test render as the same text exactly when the engine has
+ thrown that part away.
+
+ The day test uses two fixed times of day rather than ``dttm`` and one
+ alternative, so a bound that happens to sit on the hour the alternative
+ uses cannot read as "no time at all". Neither probe sits at midnight on
+ purpose: SQLite renders a DATE column at exactly midnight as a bare
+ date, so a midnight probe would differ from its alternative for a
+ reason that has nothing to do with resolution.
+
+ Likewise both sub-second probes carry a non-zero remainder. Comparing
+ against ``dttm`` truncated to the second looks like the obvious test and
+ is wrong for the same formatting-boundary reason.
+
+ A non-temporal column has no answer here, and asking anyway gets a wrong
+ one. SQLite's ``convert_dttm`` renders for ``types.String`` as well as
+ for the date types, so a ``VARCHAR`` mapped column reads as
+ second-resolution -- and a filter value that happens to *look* like an
+ instant then has its bound rounded as though the engine had truncated
+ it. On a VARCHAR ``code`` mapped onto a VARCHAR ``p`` by ``:value``,
+ ``code < '2026-07-06T10:08:11.500000'`` was mirrored as
+ ``p <= '2026-07-06 10:08:12.000000'``; a space sorts before ``T``, so a
+ row holding ``2026-07-06T09:00:00`` fell outside the mirror while
+ matching the filter.
+
+ The guard lives here rather than in each caller so this and
+ `_column_literal_resolution` cannot disagree about which column is
+ coarse -- which is the same reason that helper delegates to this one.
+
+ "Temporal" is the column's generic type, not just its ``is_dttm`` flag.
+ `get_time_filter` renders a bound through ``convert_dttm`` for any
+ ``DATE`` column, flagged or not, so a ``DATE`` column left unflagged
+ still compares a bare day -- and skipping the resolution check there
+ would hand the probe 10:00 for a bound the engine reads as midnight.
+ """
+ if col is None or not col.type or col.type_generic != GenericDataType.TEMPORAL:
+ return LiteralResolution.FULL
+
+ def render(moment: datetime) -> Optional[str]:
+ return self.db_engine_spec.convert_dttm(
+ col.type, moment, db_extra=self.db_extra
+ )
+
+ try:
+ early = render(dttm.replace(hour=1, minute=2, second=3, microsecond=444444))
+ late = render(
+ dttm.replace(hour=22, minute=33, second=44, microsecond=555555)
+ )
+ if early is not None and early == late:
+ return LiteralResolution.DAY
+
+ # Flooring to the second is a no-op on a bound that has no
+ # sub-second part, so there is nothing to detect.
+ if not dttm.microsecond:
+ return LiteralResolution.FULL
+
+ first = render(dttm.replace(microsecond=111111))
+ second = render(dttm.replace(microsecond=222222))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return LiteralResolution.FULL
+
+ if first is not None and first == second:
+ return LiteralResolution.SECOND
+ return LiteralResolution.FULL
+
+ def _round_bounds_outward(
self,
- time_col: "TableColumn",
+ start_dttm: Optional[datetime],
+ end_dttm: Optional[datetime],
+ col: Optional["TableColumn"],
+ ) -> tuple[Optional[datetime], Optional[datetime]]:
+ """
+ The bounds widened to whatever the engine's literal actually resolves to.
+
+ Rounding outward is never narrower than the predicate being mirrored,
+ which is the only property the mirror has to hold.
+ """
+ resolutions = {
+ self._engine_literal_resolution(bound, col)
+ for bound in (start_dttm, end_dttm)
+ if bound is not None
+ }
+
+ if LiteralResolution.DAY in resolutions:
+ # The engine compares a bare date, so the real predicate's lower
+ # bound is the start of that day and its upper bound admits the
+ # whole of the day before. Anything finer excludes rows it keeps.
+ if start_dttm is not None:
+ start_dttm = start_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ )
+ if end_dttm is not None and end_dttm != end_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ ):
+ end_dttm = end_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ ) + timedelta(days=1)
+ elif LiteralResolution.SECOND in resolutions:
+ if start_dttm is not None:
+ start_dttm = start_dttm.replace(microsecond=0)
+ if end_dttm is not None and end_dttm.microsecond:
+ end_dttm = end_dttm.replace(microsecond=0) + timedelta(seconds=1)
+
+ return start_dttm, end_dttm
+
+ def _literal_is_coarser_than(
+ self, dttm: datetime, col: Optional["TableColumn"]
+ ) -> bool:
+ """
+ Whether the engine's literal for ``dttm`` throws away part of it.
+
+ Unlike a range, an equality cannot be widened outward, so the only safe
+ answer when the engine compares less than the full value is to decline
+ the mirror.
+ """
+ resolution = self._engine_literal_resolution(dttm, col)
+ if resolution is LiteralResolution.DAY:
+ return dttm != dttm.replace(hour=0, minute=0, second=0, microsecond=0)
+ if resolution is LiteralResolution.SECOND:
+ return bool(dttm.microsecond)
+ return False
+
+ def _column_literal_resolution(
+ self, col: Optional["TableColumn"]
+ ) -> LiteralResolution:
+ """
+ How much of *any* value this engine compares on ``col``.
+
+ `_engine_literal_resolution` answers about a particular instant, which
+ is what a mirror derived from one needs. Two callers have no instant to
+ ask about -- the summary the Explore glyph reads, and a filter value
+ `_instant_from_filter_value` cannot read as an instant at all -- and
+ both need the column's own answer. Through one helper so that the glyph
+ and the query path cannot disagree about which column is coarse, which
+ is the same reason `mirrorable_operators` is computed once.
+
+ A non-temporal column has no answer, and asking anyway gets a wrong one:
+ SQLite's ``convert_dttm`` renders for ``types.String`` as well as for the
+ date types, so a reference instant makes a ``VARCHAR`` mapped column look
+ second-resolution -- and ``country = 'US'``, the text half of this
+ feature, reads as a value the engine compares coarsely.
+
+ That guard is `_engine_literal_resolution`'s, not this function's. It
+ used to be here, on the belief that the per-instant callers never met
+ the case because they arrive only with a value that parsed as an
+ instant -- which is untrue of a text column holding ISO-shaped text,
+ where the value parses and the column is still not temporal.
+ """
+ return self._engine_literal_resolution(_RESOLUTION_REFERENCE_INSTANT, col)
+
+ def _round_bound_outward(
+ self,
+ instant: datetime,
+ col: Optional["TableColumn"],
+ *,
+ is_upper: bool,
+ ) -> datetime:
+ """
+ One bound widened to whatever the engine resolves ``col`` to.
+
+ `_round_bounds_outward` answers for a since/until pair, because a time
+ range is the shape it was written for. A single comparison is one end of
+ such a pair with the other end absent, and the widening is per-end
+ already -- a lower bound moves back, an upper bound forward.
+
+ Narrowing the return type is the other half of the point: a bound handed
+ in non-`None` comes back non-`None`, and saying so here saves every
+ caller from re-establishing it.
+ """
+ start_dttm, end_dttm = self._round_bounds_outward(
+ None if is_upper else instant,
+ instant if is_upper else None,
+ col,
+ )
+ rounded = end_dttm if is_upper else start_dttm
+ return rounded if rounded is not None else instant
+
+ def _in_column_number_type(self, value: Any, col: Optional["TableColumn"]) -> Any:
+ """
+ A numeric ``value`` in the number type the mapped column stores.
+
+ The engine compares a number against the column in the column's own
+ domain, so ``n = '1.0'`` on an integer ``n`` matches the row holding
+ ``1``. `filter_values_handler` hands over ``1.0``, though, and a
+ transform whose output depends on the representation --
+ ``CAST(:value AS TEXT)`` answers ``'1.0'`` where the row's key is
+ ``'1'`` -- then mirrors to a partition value no matching row holds.
+ Probing at the value the column would hold keeps ``T(col) = T(v)``.
+
+ Only lossless conversions: an integral number for an integer column, a
+ number a float represents exactly for a float column. Anything else is
+ returned unchanged -- a non-integral value on an integer column matches
+ no row, so its mirror cannot drop one, and a ``DECIMAL`` column's text
+ depends on a scale the spec does not expose.
+ """
+ if (
+ col is None
+ or not col.type
+ or isinstance(value, bool)
+ or not isinstance(value, (int, float, Decimal))
+ ):
+ return value
+ try:
+ column_spec = self.db_engine_spec.get_column_spec(
+ col.type, db_extra=self.db_extra
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return value
+ if column_spec is None:
+ return value
+ sqla_type = column_spec.sqla_type
+ type_class = sqla_type if isinstance(sqla_type, type) else type(sqla_type)
+ if issubclass(type_class, sa.Integer):
+ if isinstance(value, int):
+ return value
+ try:
+ return int(value) if value == int(value) else value
+ except (OverflowError, ValueError):
+ # Infinity and NaN have no integer, and match no integer row.
+ return value
+ if issubclass(type_class, sa.Float) and float(value) == value:
+ return float(value)
Review Comment:
Converting an integral value to `float` for a float column changes what a representation-dependent transform sees. On PostgreSQL with a `REAL` mapped column `n`, a text partition key, `CAST(:value AS TEXT)` and a row `n = 1, p = '1'`, the filter `n = 1` used to probe `CAST(1 AS TEXT)` and mirror `p = '1'`. It now probes `CAST(1.0 AS TEXT)`, which PostgreSQL reads as a NUMERIC literal and renders as `'1.0'`, so the mirror becomes `p = '1.0'` and drops the matching row. Is the float conversion safe on engines where a `REAL` column's text form has no `.0`, or should it be limited to engines whose literal keeps the column's type?
##########
docs/admin_docs/configuration/partition-filter-mapping.mdx:
##########
@@ -0,0 +1,314 @@
+---
+title: Partition Filter Mapping
+hide_title: true
+sidebar_position: 15
+version: 1
+---
+
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+
+# Partition Filter Mapping
+
+Tables on Hadoop-family engines are often partitioned on a *technical* column — an epoch
+integer, a lowercased region key — that no analyst would ever filter on. Unless a query
+carries a predicate on that column, the engine scans every partition.
+
+Partition filter mapping makes this a dataset setting instead of a per-chart chore. A
+dataset owner names the partition column, the business column whose filters should be
+mirrored onto it, and a value transform. Superset then appends an equivalent predicate on
+the partition column to every query. Chart authors change nothing; queries prune.
+
+:::caution Experimental
+This feature is behind the `PARTITION_FILTER_MAPPING` feature flag and is off by default.
+:::
+
+## Enabling it
+
+```python
+FEATURE_FLAGS = {
+ "PARTITION_FILTER_MAPPING": True,
+}
+```
+
+Configure it as a **static boolean**. A callable placed in `FEATURE_FLAGS` is *not*
+evaluated: `FeatureFlagManager` stores the configured values unchanged, so
+`"PARTITION_FILTER_MAPPING": lambda: False` resolves to a truthy function object and turns
+the feature **on**. Per-request resolution comes only from `GET_FEATURE_FLAGS_FUNC` and
+`IS_FEATURE_ENABLED_FUNC`, and for this flag both must return the same answer for every
+user: a flag that resolves differently per user or tenant would let a user with the feature
+off read a cached chart result that was produced from pruned SQL by a user with it on.
+
+## Configuring a mapping
+
+In the dataset editor's **Columns** tab, under *Default Column Settings*, pick a
+**Partition column**. By default the mapping follows the dataset's default datetime column,
+so re-pointing that column moves the mapping with it; set an explicit override if you want it
+pinned to a different column.
+
+Expand the mapped column's row in *Column Settings* and set the **value transform**: a SQL
+expression containing a `:value` placeholder, which stands for the filter value being
+mirrored. The **Transform preserves ordering** checkbox sits directly beneath it.
+
+| Mapped column | Partition column | Transform |
+|---|---|---|
+| `event_time` (`TIMESTAMP`) | `dt_epoch` (`BIGINT`) | `unix_timestamp(:value)` |
+| `country` (`VARCHAR`) | `region_key` (`VARCHAR`) | `lower(:value)` |
+
+A filter of `event_time >= '2026-01-01'` then adds `dt_epoch >= 1767225600` to the query.
+The added predicate is an ordinary `WHERE` clause and shows up in **View query**.
+
+### Transform preserves ordering
+
+Range filters — including the Explore time range, the most important case — are only
+mirrored when you check **Transform preserves ordering**.
+
+Monotonicity is a property of the *transform*, not of the column's data type.
+`unix_timestamp(:value)` preserves ordering. `hour(:value)`,
+`date_format(:value, 'dd')` and `dayofweek(:value)` are all perfectly reasonable
+partition transforms on a `TIMESTAMP` column and none of them do: `hour('2026-01-01 23:00')`
+is greater than `hour('2026-01-02 01:00')` even though the first instant is earlier. Mirroring
+a range through one of those would silently return wrong numbers, so Superset asks you to
+declare it rather than guessing.
+
+A *bucketing* transform preserves ordering and is the common case rather than
+an exception: `to_char(:value, 'YYYYMMDD')`, `date(:value)` and
+`cast(unix_timestamp(:value) / 86400 as bigint)` each map a whole day onto one
+partition key, which is exactly what a daily-partitioned table wants. Check the
+box for these.
+
+When the box is unchecked, `=` and `IN` filters still mirror; ranges do not.
+
+## What is and isn't mirrored
+
+| Filter | Mirrored |
+|---|---|
+| `=`, `IN` | Always, except on a text column whose engine does not compare text exactly, or when the engine compares less of the value than the filter carries |
+| `>`, `>=`, `<`, `<=`, time ranges | Only when the transform preserves ordering — and a strict bound mirrors non-strictly |
+| `!=`, `NOT IN`, `LIKE`, `ILIKE`, `IS NULL`, `IS TRUE` | Never |
+
+**Strict bounds.** Preserving ordering means non-decreasing, not strictly
+increasing, so `event_time < '2026-07-06 12:00'` mirrors to
+`day_key <= '20260706'` rather than `day_key < '20260706'`. Under a day key both
+sides of a mid-day boundary share a key, and the strict form would prune away
+the partition the boundary rows live in. The mirror reads one extra partition
+and keeps every row the filter keeps.
+
+Negations are never safe. A transform need not be injective: `lower(:value)` with
+`country != 'US'` would mirror to `region_key != 'us'`, which excludes rows whose `country`
+is already lowercase `'us'` — rows the original filter *keeps*.
+
+**Text comparison.** Mirroring `col = v` onto `partition_col = T(v)` assumes the engine
+compares `col` the way the transform was written against. Under a case-insensitive collation
+it does not: a stored `country` of `'us'` satisfies a filter for `'US'`, while the mirror is
+derived from `'US'` and excludes the row. So `=` and `IN` on a **text** mapped column only
+mirror on engines whose default text comparison is exact — Hive, Impala, Trino, Presto,
+Spark, Databricks, PostgreSQL, Snowflake, BigQuery and SQLite. On MySQL and SQL Server, whose
+default collations are case-insensitive, a text mapping is stored and shown but no `=` or
+`IN` filter mirrors through it; map a numeric or temporal column instead. Numeric and
+temporal comparison is exact everywhere, and ranges are unaffected either way — checking
+**Transform preserves ordering** is already a statement about the column's own ordering.
+
+One case Superset cannot check for you: a column that declares its own collation, such as
+`country COLLATE NOCASE`, on an engine that is otherwise exact. Nothing in the metadata
+exposes that, so it falls under the same pipeline assumption as the partition key itself.
+
+**Value resolution.** Mirroring also assumes the engine compares the value your filter
+carries. It does not always. On a `DATE` mapped column, `event_date = '2026-07-06 10:08:11'`
+is compared on the date part alone — Postgres casts the string, Presto and Trino render
+`DATE '2026-07-06'` — so the filter keeps the whole of July 6 while a mirror derived from
+10:08:11 keeps one instant of it. Superset detects what your engine drops, from the column's
+type rather than from a list of engines, and responds by operator: a range **widens** to the
+day, so `event_date >= '2026-07-05 10:00'` mirrors as if the bound were `'2026-07-05 00:00'`
+— one extra partition read, every row the filter keeps — while `=` and `IN` have nowhere to
+widen to and do **not** mirror at all. A `=` or `IN` whose value carries no time of day,
+such as `'2026-07-06'` or a date picked in the filter popover, mirrors normally. The same
+applies one grain finer on engines that compare timestamps only to the second.
+
+Reading the value is what makes all of that possible, and Superset reads **ISO 8601 only** —
+`2026-07-06`, `2026-07-06 10:08:11`, `2026-07-06T10:08:11`. It is the one format whose
+meaning is not a guess: `06/07/2026` is July 6 to a US reader and June 7 to most of the
+world, and a mirror built from the wrong one drops rows silently. So on a column the engine
+compares coarsely, a datetime typed in any other format — `07/06/2026 10:08:11`,
+`2026/07/06 10:08:11`, `July 6 2026 10:08:11` — does not mirror, for any operator, and no
+pruning indicator appears. The filter itself is unaffected; the query is correct and simply
+reads the whole table. Write the bound in ISO 8601, or pick it from the filter popover, and
+the mirror comes back. None of this applies where the engine compares the whole value: on a
+`TIMESTAMP` column any format your database accepts mirrors, because there is nothing left
Review Comment:
This says any format the database accepts mirrors on a `TIMESTAMP` column, but `_mirror_probe_input` now declines every instant that carries a UTC offset before it reaches the full-resolution return. A filter such as `event_time >= '2026-01-01T01:00:00+01:00'` on a full-resolution column therefore emits no mirror and no pruning indicator, and the preview's refusal tells the owner to map a column the engine compares in full, which this dataset already has. Should the page name the offset exception, and should the preview give it its own explanation instead of the precision-loss one?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2770 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+#: Returned by `ExploreMixin.mirror_probe_request` for a filter no mirror can
+#: stand in for: one the engine compares more coarsely than the value carries, a
+#: value it cannot render as a literal, or an ``IN`` list with a member of
+#: either kind. A sentinel rather than `None`, because `None` is a filter value
+#: in its own right.
+#:
+#: Lives here rather than beside that method so the preview can read it too:
+#: `superset.models.helpers` imports this module, so the sentinel can only cross
+#: the boundary in this direction. Both callers have to recognise the same
+#: object -- a preview that answered "valid" for a request the chart path
+#: declines is the drift this is here to prevent.
+UNMIRRORABLE = object()
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error( # noqa: C901
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ And it must be a *read*. Shape is a separate question from effect: a bare
+ scalar expression can still write, so `SQLStatement.is_mutating` is asked
+ too -- the same question SQL Lab and the chart executor ask before letting
+ SQL run. See the gate itself for what that reaches and what it does not.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ # Also ahead of the parse, and for a stronger reason than cost: every gate
+ # below reasons about the parse tree, and this is the one construct that
+ # makes the parse tree describe a different statement from the one the
+ # engine runs. Checked here as well as in `validate_transform` because this
+ # is the door a row written by an earlier release still comes through.
+ if contains_executable_comment(transform):
+ return str(
+ _(
+ "A partition value transform cannot contain a MySQL "
+ "executable comment, which the database executes and every "
+ "validator reads as a comment."
+ )
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The read-only gate, which nothing above implies. The shape gates ask what
+ # the transform *selects*; this asks what evaluating it *does*, and a bare
+ # scalar expression can still write. `nextval(:value)` on PostgreSQL
+ # advances a sequence: one function call, no clause, no sub-query, and not
+ # in the default `DISALLOWED_SQL_FUNCTIONS` either -- so every gate above
+ # passes it and the probe then runs it. `setval` is the same shape, and
+ # `exp.Execute` and the opaque-`exp.Command` forms arrive the same way.
+ #
+ # The large-object writers (`lo_export`, `lowrite`, `lo_from_bytea`, ...)
+ # are caught here too, and the shipped denylist happens to name them as
+ # well -- but that is config an operator can replace, while this is not.
+ #
+ # `is_mutating` is the same question SQL Lab, `get_virtual_table_metadata`
+ # and the chart executor ask before letting SQL run, so a transform is held
+ # to the bar the rest of Superset already sets rather than to one invented
+ # here. Unconditional rather than gated on `Database.allow_dml`: a transform
+ # is a scalar function of `:value` by definition, so there is no legitimate
+ # mutating one, and the probe runs on a cache schedule nobody chose -- a
+ # write would repeat every time the entry expired.
+ #
+ # It bears saying what this does not reach. A user-defined function whose
+ # body writes is a plain call no parser can tell from `lower(:value)`, and
+ # `is_mutating`'s function-name walk is PostgreSQL-only by design, since the
+ # same names are read-only elsewhere. Neither residual is specific to this
+ # feature -- a dataset editor can already have the engine evaluate an
+ # arbitrary expression through a calculated column or a virtual dataset's
+ # SQL -- and closing them means authorizing the preview against the
+ # database, not parsing harder.
+ if statement.is_mutating():
+ return str(
+ _(
+ "A partition value transform cannot change data. It is "
+ "evaluated against the database to check that it mirrors, so "
+ "it has to be a read."
+ )
+ )
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the probe
+ uninspected -- string elements are escaped by the dialect's own literal
+ processor. `probe_sql_is_evaluable` then re-reads the finished query, which
+ is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def _placeholder_is_bindable(transform: str) -> bool:
+ """
+ Whether SQLAlchemy's ``text()`` can see ``:value`` as a bound parameter.
+
+ `VALUE_PLACEHOLDER_RE` is ``:value\b``, which matches the placeholder in a
+ Postgres cast such as ``:value::bigint``. SQLAlchemy's own bind scan is
+ ``(?<![:\\w$]):([\\w$]+)(?![:\\w$])`` -- note the trailing exclusion -- so a
+ following colon stops it: ``text(":value::bigint")`` reports a parameter
+ named ``valu``, and ``.bindparams(bindparam("value"))`` then raises
+ ``ArgumentError``.
+
+ `_probe` swallows that, so the only symptom was a perfectly valid transform
+ whose mapping silently never pruned, and a preview reporting an engine
+ failure for SQL that was never sent. Every write-side gate passes the
+ transform: it parses, it is a bare expression, and the placeholder *is* in
+ an executable position.
+
+ Answered by attempting the bind itself rather than by pattern-matching
+ ``::`` or reading ``text()``'s private parameter map, so this cannot
+ disagree with what `build_probe_sql` is about to do -- on any dialect, or on
+ a SQLAlchemy whose scan changes.
+ """
+ try:
+ sa.text(transform).bindparams(sa.bindparam("value", value=None))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return False
+ return True
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ bindable = _placeholder_is_bindable(transform)
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ elif bindable:
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ rendered = _compile_literal(clause, dialect)
+ else:
+ # `text()` cannot see the placeholder (see
+ # `_placeholder_is_bindable`), so the value is rendered by the
+ # dialect's own literal processor first and substituted as SQL
+ # text. The same two steps in the other order: binding exists to
+ # get the value through that processor, and `_compile_literal`
+ # inlines the result either way, so this is the same string by a
+ # different route -- not a loosening of the "never interpolate a
+ # raw value" rule. `parse_skeleton` substitutes literally, so a
+ # rendered literal containing a backslash is safe here.
+ rendered = parse_skeleton(
+ transform, _compile_literal(sa.literal(value), dialect)
+ )
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Four things have to hold, and all four are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ # Before the parse, because this gate's whole contract is that what the
+ # parse describes is what the engine will run, and an executable comment is
+ # precisely the text where that stops being true. The transform is already
+ # refused for carrying one; this covers the compiled statement, so no later
+ # change to how values are rendered can reintroduce it behind the gates
+ # below.
+ if contains_executable_comment(sql):
+ return False
+
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if not isinstance(statement, SQLStatement):
+ # A dialect whose statements this gate cannot take apart -- KQL -- gets
+ # no probe rather than an unchecked one. It never had one: the clause
+ # inspection below is implemented for SQL statements only, and the
+ # alternative to declining here is an `AttributeError` that `_probe`
+ # swallows into the same outcome, less legibly.
+ return False
+ if statement.has_subquery():
+ return False
+ if statement.get_clause_names() - {"from"}:
+ return False
+ if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+ """
+ The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+ Parsed rather than string-compared so that the comparison in
+ `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+ not parse answers ``None``, which no statement carrying a FROM can match --
+ the probe then declines, which is the right way for an unreadable engine
+ constant to fail.
+ """
+ if not from_suffix.strip():
+ return None
+ try:
+ return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+ except SupersetParseError:
+ return None
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=values is not None and not any(value is None for value in values),
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ from_suffix = database.db_engine_spec.select_without_from_suffix
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ from_suffix,
+ )
+ if not probe_sql_is_evaluable(
+ sql, database.backend, len(distinct), from_suffix
+ ):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _execution_identity(database: Database) -> str | None:
+ """
+ Who the warehouse will run the probe as, when that can vary by caller.
+
+ `_probe_cache_key` keys on the `Database` record, which is the *connection*
+ -- not the identity it is opened under. Two hooks make that identity a
+ function of the Superset user instead:
+
+ * ``impersonate_user`` on the database, which hands the effective username
+ to `db_engine_spec.impersonate_user`;
+ * ``DB_CONNECTION_MUTATOR``, which receives the effective username and may
+ return an entirely different account's URL.
+
+ Under either one, a cached probe result computed under user A's grants was
+ served to user B, and the preview echoed it back in ``emitted_predicate``.
+ A transform wrapping a read-capable function the denylist does not name --
+ Oracle's ``DBMS_XMLGEN.GETXML`` is the worked example -- then leaks across
+ users who were never allowed the same rows.
+
+ Returns ``None`` when neither hook is configured, which is the common case
+ and deliberately leaves the key as it was: the cache exists to keep a
+ synchronous warehouse round trip off the chart-query path, and keying every
+ deployment on the username would cost every deployment the hit rate to fix
+ the two that need it.
+
+ The *Superset* username rather than the resolved warehouse account, because
+ it is the input both hooks branch on, and reading it needs no URL parse and
+ puts no credential in the key.
+ """
+ if not (database.impersonate_user or app.config["DB_CONNECTION_MUTATOR"]):
+ return None
+ return get_username()
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _mirror_verdict_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str:
+ """
+ `_probe_cache_key` without the values.
+
+ Whether a transform can be evaluated at all is a property of the transform
+ and the connection, not of the filter that happened to be probing it, so
+ one chart's answer settles the question for the next one.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ # Whether a transform *can* be evaluated is a property of the
+ # transform and the connection -- but under impersonation the
+ # connection is per-user, and a function one account may call can
+ # be refused to another. See `_execution_identity`.
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_verdict:{digest}"
+
+
+def record_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ *,
+ mirrors: bool,
+) -> None:
+ """
+ Remember whether this transform produced a mirror, for the UI to read.
+
+ Advisory only. Nothing in the query path consults it: a probe that failed
+ once is retried on the next chart exactly as it is today, because declining
+ to prune for a whole cache timeout over one transient engine blip is the
+ trade `evaluate_transform` deliberately refuses -- see the comment where it
+ declines to cache a failure.
+
+ What this is for is the *claim*. `is_transform_active` parses the transform
+ and no more, so a transform the database rejects -- a misspelled function
+ is the common case -- is "active", and the editor's banner and Explore's
+ pruning glyph promise a speed-up that never happens. A promise is exactly
+ the thing that may be withheld on one bad answer and restored on a good
+ one, which is why this is a separate entry from the probe's own results
+ rather than a relaxation of that rule.
+
+ Written by `_run_probe`, so the preview endpoint -- which shares the
+ evaluator -- settles the question before the owner has even saved.
+ """
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(
+ _mirror_verdict_cache_key(database, catalog, schema, transform),
+ mirrors,
+ timeout=timeout,
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform verdict", exc_info=True)
+
+
+def known_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> bool | None:
+ """
+ The last verdict `record_mirror_verdict` stored, or `None` if there is none.
+
+ `None` is the honest answer on a cold cache and is deliberately not `False`:
+ reporting a working mapping as broken until something probes it would
+ trade one wrong claim for another. The alternative -- probing from the
+ read side -- would put a warehouse round trip on every Explore and
+ dashboard load, and a failing transform is not cached at all, so it would
+ be a round trip every single time.
+ """
+ try:
+ verdict = cache_manager.cache.get(
+ _mirror_verdict_cache_key(database, catalog, schema, transform)
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return verdict if isinstance(verdict, bool) else None
+
+
+def _compile_literal(element: Any, dialect: Dialect | None) -> str:
+ """
+ Compile with inline literals, undoing the paramstyle's percent doubling.
+
+ Both ``TextClause`` and literal compilation run the dialect's
+ ``post_process_text``, which doubles every ``%`` whenever the identifier
+ preparer asks it to -- true for MySQL and Postgres and for every spec
+ inheriting their paramstyle. That doubling exists so a later DBAPI
+ parameter-interpolation pass can undo it, and the probe has no such pass:
+ it executes with no bound parameters at all. So a transform of
+ ``date_format(:value, '%Y%m%d')`` reaches the warehouse asking for the
+ literal string ``%%Y%%m%%d``, the probe returns that instead of a date, and
+ the mirrored predicate drops every row the filter keeps.
+
+ The same normalization ``Database.compile_sqla_query`` applies for the same
+ reason. ``_double_percents`` is private and not guaranteed on a third-party
+ dialect, hence the ``getattr`` default.
+ """
+ compiled = str(
+ element.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
+ )
+ if dialect is not None and getattr(
+ dialect.identifier_preparer, "_double_percents", False
+ ):
+ compiled = compiled.replace("%%", "%")
+ return compiled
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be *asked* to stand in for itself, and the transform
+ cannot carry Jinja or call a non-deterministic function. Tier 2
+ (``blocking=False``) is everything that merely leaves the mapping inactive
+ -- including a self-mapping nobody asked for, where the partition column
+ merely happens to be the default datetime column.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column == partition_column:
+ # Asked for explicitly, so report it as the mistake it is.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+ elif not partition_mapped_column and main_dttm_col == partition_column:
+ # Resolved onto itself only because the default datetime column happens
+ # to be the partition column -- a state metadata sync could produce
+ # without anyone asking for it. The mapping is inert either way, since
+ # `resolve_partition_mapping` bails out on it, so this reports and lets
+ # the write through: blocking here means a dataset already in the state
+ # can never be saved again, not even to change its description, and
+ # there is no field whose edit would clear the error first.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "%(name)s is both the partition column and the default "
+ "datetime column, so the mapping points at itself and "
+ "stays inactive. Set a mapped column override, or change "
+ "the default datetime column.",
+ name=partition_column,
+ ),
+ blocking=False,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def drop_unmapped_value_transforms(
+ columns: list[dict[str, Any]] | None,
+ *,
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ names_by_id: dict[int, str] | None = None,
+) -> list[str]:
+ """
+ Null the value transform on every *incoming* column the mapping cannot mirror.
+
+ The write-side twin of `DatasetDAO.clear_unmapped_partition_transforms`,
+ which answers for the model. A mapping has exactly one mirrored column, so
+ at most one column may carry a transform. One parked on any other column is
+ invisible -- no row but the mapped one renders a transform -- and yet it is
+ stored, and it goes live the moment the mapped column resolves back to it.
+ Clearing an override is enough to do that: a null
+ ``partition_mapped_column`` means "follow ``main_dttm_col``".
+
+ Ungated on the feature flag, unlike its model-level twin, and the difference
+ is what each one discards. That one drops stored configuration, so with the
+ flag off it would be pure loss. This one drops only a value the request in
+ hand is asking to write where the invariant says none may live -- and the
+ flag-off window is precisely when such a value gets parked for later, since
+ the editor hides these fields and the model-level pass declines to run.
+
+ Three writers reach the columns with no effective model-level pass between
+ them, which is why this exists at all: the deprecated
+ ``POST /datasource/save/``, which writes straight through
+ `update_from_object` and so never had one; and a
+ ``PUT /api/v1/dataset/<pk>`` or a dataset import made while the flag is
+ off, where the pass runs on both sides of the write and declines on both.
+
+ Mutates the payload in place, because every caller hands its own request
+ dict straight on to the code that writes it. Returns the names it cleared,
+ so the caller can say so in a log: this is a silent correction to a payload
+ whose author may have meant it.
+
+ A column whose payload mentions neither field is left alone. "Incoming" is
+ the whole scope -- a transform already in storage on a column this request
+ says nothing about is the model-level pass's business, under its own flag.
+
+ The mapped column resolves the way every other reader resolves it,
+ ``partition_mapped_column or main_dttm_col``, and resolves to nothing
+ without a partition column -- in which case no column may hold a transform
+ either.
+
+ :param names_by_id: how to read the name off a payload entry that gives
+ only an ``id``. `DatasetDAO._upsert_columns` identifies an existing
+ column by its primary key and lets ``column_name`` be omitted -- the
+ column keeps the name it has -- so without this an ordinary PUT looked
+ like a payload of nameless columns, none of which matched the mapped
+ one, and every transform in it was dropped. Callers whose writer keys
+ on the name instead (`update_from_object`, the importer) pass nothing.
+ An entry this cannot name is left alone rather than guessed at.
+ """
+ mapped_column = (
+ (partition_mapped_column or main_dttm_col) if partition_column else None
+ )
+ cleared: list[str] = []
+ for column in columns or []:
+ name = column.get("column_name")
+ if name is None and names_by_id is not None:
+ column_id = column.get("id")
+ if column_id is not None:
+ name = names_by_id.get(column_id)
+ if name is None or name == mapped_column:
+ continue
+ if column.get("partition_value_transform") or column.get(
+ "partition_transform_is_monotonic"
+ ):
+ column["partition_value_transform"] = None
+ column["partition_transform_is_monotonic"] = False
+ cleared.append(name)
+ return cleared
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if contains_executable_comment(transform):
+ # Blocking, and checked on raw text next to the Jinja gate because no
+ # parse reports it: sqlglot reads `/*!50000 ... */` as comment data
+ # while MySQL and MariaDB execute it, so every shape gate downstream
+ # inspects a statement the engine will not run. See
+ # `EXECUTABLE_COMMENT_RE`.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform cannot contain a MySQL executable "
+ "comment (/*! ... */ or /*M! ... */). Those are comments "
+ "to every validator and statement text to the database, "
+ "so what would run is not what was checked."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_bare_expression(transform, engine):
+ # Blocking, and deliberately placed in `validate_transform` rather than
+ # only at the probe: one issue here closes the PUT, the importer, the
+ # query-time gate through `is_transform_active`, the Explore indicator's
+ # active verdict and the preview endpoint, all of which already consult
+ # this function.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform must be a single SQL expression. It "
+ "cannot carry a FROM, WHERE, GROUP BY or any other clause, "
+ "and it cannot contain a sub-query."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not contains_value_placeholder(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform must contain the :value placeholder, "
+ "which stands for the filter value being mirrored."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not placeholder_is_executable(transform, engine):
+ # Blocking, and for the same reason the shape gate above is: this is
+ # the function the PUT, the importer, `is_transform_active`, the
+ # Explore indicator and the preview all consult, so one issue here
+ # closes every door at once. A placeholder inside a string literal is
+ # a sub-query the engine will run once a filter value closes the quote;
+ # one inside a comment silently eats the probe's own alias.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The :value placeholder must appear where the engine will "
+ "evaluate it. It cannot sit inside a string literal or a "
+ "comment."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if functions := find_non_deterministic_functions(transform, engine):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform calls %(functions)s, whose result "
+ "depends on when and where it runs. The transform is "
+ "evaluated in a separate session and the result is cached, "
+ "so the emitted predicate would freeze a snapshot of that "
+ "moment.",
+ functions=", ".join(sorted(functions)),
+ ),
+ blocking=True,
+ )
+ ]
+
+ return []
+
+
+@lru_cache(maxsize=LRU_CACHE_MAX_SIZE)
+def is_transform_active(transform: str | None, engine: str) -> bool:
+ """
+ Whether Superset will mirror filters through this transform.
+
+ `validate_transform` with the messages discarded, so the Explore indicator
+ cannot advertise a mapping the save path recorded as inactive. Anything
+ cheaper here would be a second, weaker statement of the same rule, free to
+ drift from the one the save path applies.
+
+ Blocking issues count too. Jinja and non-deterministic transforms are
+ rejected on PUT, but `CreateDatasetCommand` and import do not validate the
+ mapping, so one can still reach the database -- and it would never mirror a
+ filter either.
+
+ Memoized because `partition_filter_mapping_summary` is serialized on every
+ Explore and dashboard load and this parses the transform. The key is
+ everything the answer depends on: `validate_transform` reads no session, no
+ locale and no config beyond `SQL_MAX_PARSE_LENGTH`, which bounds the parser
+ rather than changing a verdict within that bound.
+ """
+ return not validate_transform(transform, engine)
+
+
+def preview_partition_mapping( # pylint: disable=too-many-return-statements
+ datasource: SqlaTable,
+ *,
+ mapped_column: str,
+ value_transform: str | None,
+ sample_values: list[str],
+ operator: FilterOperator = FilterOperator.EQUALS,
+ is_monotonic: bool = False,
+ partition_column: str | None = None,
+) -> dict[str, Any]:
+ """
+ Evaluate a candidate mapping and describe the predicate it would emit.
+
+ Shares the evaluator -- and therefore the probe cache -- with the query
+ path, so preview and runtime cannot drift and a previewed transform warms
+ the chart path for free. The predicate itself comes from
+ `build_mirrored_predicates`, the same builder the query path uses, so
+ operator shapes cannot drift either: what the panel shows is what a chart
+ would emit.
+
+ Validation runs first and the engine second: a half-typed transform is by
+ definition unparseable, so most of what a text input produces costs zero
+ queries.
+
+ Every part of the mapping is taken from the request rather than the stored
+ dataset. The editor previews while the owner is still editing -- a mapping
+ that has to be saved before it can be checked is not a preview.
+ """
+ partition_column = partition_column or datasource.partition_column
+ if not partition_column:
+ return {
+ "valid": False,
+ "reason": "unconfigured",
+ "error": _("No partition column is set."),
+ }
+
+ columns_by_name = {str(column.column_name): column for column in datasource.columns}
+ if mapped_column not in columns_by_name:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _("%(name)s is not a column on this dataset.", name=mapped_column),
+ }
+
+ # The bail-out `resolve_partition_mapping` makes at query time, and that
+ # `partition_filter_mapping_summary` repeats for the Explore indicator.
+ # Without it here, preview reports a valid emitted predicate for a mapping
+ # no chart will ever mirror -- the one answer a preview panel must not give.
+ if has_active_advanced_data_type(columns_by_name[mapped_column]):
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _(
+ "%(name)s has an advanced data type, so its filters are "
+ "translated into their own predicate shape and cannot be "
+ "mirrored onto the partition column.",
+ name=mapped_column,
+ ),
+ }
+
+ engine = datasource.database.backend
+ for issue in validate_partition_mapping(
+ column_names=set(columns_by_name),
+ partition_column=str(partition_column),
+ partition_mapped_column=mapped_column,
+ main_dttm_col=datasource.main_dttm_col,
+ transform=value_transform,
+ engine=engine,
+ ):
+ return {
+ "valid": False,
+ # The parse failure is the one an owner sees constantly, and it is
+ # the only one the mockup gives its own headline to.
+ "reason": (
+ "parse"
+ if issue.field == "partition_value_transform"
+ and not is_parseable(value_transform, engine)
+ else "validation"
+ ),
+ "error": str(issue.message),
+ }
+
+ # The policy every other stored expression goes through. The save path
+ # applies it in `UpdateDatasetCommand._validate_partition_mapping`, but
+ # preview evaluates a candidate transform that has not been saved, so
+ # without this the gate had a door around it. See
+ # `stored_expression_error` for what is being kept out and why.
+ if reason := stored_expression_error(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ cast(str, value_transform),
+ ):
+ return {"valid": False, "reason": "validation", "error": reason}
+
+ mapping = PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=mapped_column,
+ value_transform=cast(str, value_transform),
+ is_monotonic=is_monotonic,
+ equality_is_safe=equality_mirrors_safely(
+ columns_by_name[mapped_column], datasource.database.db_engine_spec
+ ),
+ )
+ sample_input = _render_sample_input(
+ datasource, mapped_column, operator, sample_values
+ )
+
+ if operator not in PREVIEWABLE_OPERATORS:
+ # Checked before `mirrors`, which lets `TEMPORAL_RANGE` through when the
+ # transform is declared monotonic -- and the single sample value would
+ # then reach `handle_comparison_filter`, which has no case for a range
+ # and raises. The request schema rejects it too; this keeps the function
+ # honest for any other caller.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is mirrored as a pair of bounds, which "
+ "a preview of a single value cannot describe.",
+ operator=operator.value,
+ ),
+ }
+
+ if operator in MIRRORABLE_ALWAYS and not mapping.equality_is_safe:
+ # Withdrawn by `equality_mirrors_safely`, which no declaration about
+ # ordering can change -- so naming monotonicity here would send the
+ # owner to a checkbox that leaves the answer as it is.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter on this text column is not mirrored: "
+ "the database may treat strings that differ in case or "
+ "trailing spaces as equal, and the mirrored predicate could "
+ "then drop rows the filter keeps.",
+ operator=operator.value,
+ ),
+ }
+
+ if not mapping.mirrors(operator):
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is only mirrored when the transform "
+ "preserves ordering, which this one is not declared to do.",
+ operator=operator.value,
+ ),
+ }
+
+ return _preview_probe(
+ datasource,
+ mapping,
+ columns_by_name[mapped_column],
+ operator,
+ sample_values,
+ sample_input,
+ )
+
+
+def _preview_probe(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ mapped_col: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+ sample_input: str,
+) -> dict[str, Any]:
+ """
+ The half of a preview that needs the warehouse.
+
+ Split out from `preview_partition_mapping` so that the gates which answer
+ from the stored mapping alone stay readable as the single run of guard
+ clauses they are. Everything here has either run a query or decided not to.
+ """
+ value = datasource.mirror_probe_request(
+ operator,
+ _probe_input(datasource, mapped_col, operator, sample_values),
+ mapped_col,
+ )
+ if value is UNMIRRORABLE:
+ # The same step the chart path applies, so the preview cannot promise a
+ # mirror the query declines. Its own reason: the transform is fine and
+ # the engine evaluates it, the filter just carries more of the value
+ # than the engine compares on this column -- which is the column's type
+ # talking, not a broken expression.
+ return {
+ "valid": False,
+ "reason": "resolution",
+ "sample_input": sample_input,
+ "error": _(
+ "This engine compares less of a %(operator)s value on "
+ "%(column)s than the filter carries, so there is no mirror a "
+ "predicate on the partition column could stand in for. Map a "
+ "column the engine compares in full to mirror this operator.",
+ operator=operator.value,
+ column=mapped_col.column_name,
+ ),
+ }
+ errors: list[str] = []
+ type_errors: list[str] = []
+ predicates = build_mirrored_predicates(
+ datasource,
+ mapping,
+ [(operator, value)],
+ errors=errors,
+ type_errors=type_errors,
+ )
+ if type_errors:
+ # Its own reason, because "the database would not evaluate this" and
+ # "it evaluated and answered with the wrong kind of thing" are
+ # different problems with different fixes, and the owner is the only
+ # one who can tell which transform they meant to write.
+ return {
+ "valid": False,
+ "reason": "type",
+ "sample_input": sample_input,
+ "error": type_errors[0],
+ }
+ if not predicates:
+ return {
+ "valid": False,
+ "reason": "engine",
+ "sample_input": sample_input,
+ "error": (
+ _(
+ "The transform could not be evaluated against the "
+ "database: %(reason)s",
+ reason=errors[0],
+ )
+ if errors
+ else _("The transform could not be evaluated against the database.")
+ ),
+ }
+
+ return {
+ "valid": True,
+ "sample_input": sample_input,
+ "emitted_predicate": _render_predicate(datasource, predicates[0]),
+ }
+
+
+def _probe_input(
+ datasource: SqlaTable,
+ column: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+) -> Any:
+ """
+ The sample values as the query path would bind them.
+
+ The request carries samples as strings, and the probe is keyed on exactly
+ what it is handed, so passing them through raw asks the engine a different
+ question from the one a chart asks. A sample of ``2025`` on a numeric
+ column has to arrive as the integer the chart compares: under a transform
+ of ``typeof(:value)`` the raw string previewed ``'text'`` where the chart
+ emitted ``'integer'``. And because `_probe_cache_key` keys on each value's
+ ``repr``, the two also missed each other's cache entirely -- so the "a
+ previewed transform warms the chart path for free" claim in
+ `preview_partition_mapping`'s docstring did not actually hold.
+
+ Coerced by `filter_values_handler`, the same function the query path uses,
+ rather than by a second implementation of the same rules. Everything the
+ query path then does to the coerced value -- rendering an expression as a
+ literal, widening a bound, declining a comparison the engine resolves too
+ coarsely -- is `ExploreMixin.mirror_probe_request`'s, and the caller hands
+ this result straight to it.
+
+ Ranges are not previewable (see `PREVIEWABLE_OPERATORS`), so the bound
+ conversion `_collect_partition_mirror_range` applies -- a ``datetime`` into
+ the column's stored representation -- has no counterpart here.
+
+ An array column is the exception to `filter_values_handler`: its predicate
+ is built from the raw value, parsed into elements and rendered as the
+ engine's own array literal, so the chart path probes that literal
+ (`ExploreMixin._array_mirror_probe_value`) and this does too. Passing the
+ handled text instead previewed ``length('[1, 2]')`` for a filter whose
+ query probes ``length(array(1, 2))``.
+
+ Answers with a value, or `None` where an engine spec claims array columns
+ without an array literal -- which `mirror_probe_request` then declines, as
+ the chart path declines it. Otherwise `UNMIRRORABLE` is
+ `mirror_probe_request`'s to return, and the caller hands this straight to it.
+ """
+ is_list = operator == FilterOperator.IN
+ column_spec = datasource.db_engine_spec.get_column_spec(native_type=column.type)
+ if (
+ column_spec
+ and column_spec.generic_type == utils.GenericDataType.MULTI_VALUE
+ and operator in MIRRORABLE_ALWAYS
+ ):
+ # `=` and `IN` are the previewable operators the array branch builds a
+ # literal for; a bound on an array column binds the handled value on
+ # the chart path too, so it falls through to the same here.
+ return datasource._array_mirror_probe_value( # noqa: SLF001
+ sample_values if is_list else sample_values[0],
+ operator,
+ datasource.db_engine_spec.get_array_element_type(column.type),
+ datasource.db_engine_spec,
+ )
+ handled = datasource.filter_values_handler(
+ # `list[str]` is not a `list[FilterValue]` to mypy, invariantly, even
+ # though every `str` is a `FilterValue`.
+ values=cast(FilterValues, sample_values if is_list else sample_values[0]),
+ operator=operator,
+ target_generic_type=(
+ column_spec.generic_type if column_spec else utils.GenericDataType.STRING
+ ),
+ target_native_type=column.type,
+ is_list_target=is_list,
+ db_engine_spec=datasource.db_engine_spec,
+ db_extra=datasource.db_extra,
+ )
+ # No `ColumnElement` conversion here: an epoch-milliseconds sample comes back
+ # as engine SQL rather than a value, and `mirror_probe_request` renders it --
+ # the same step, on the same values, as for a chart filter.
+ return handled
+
+
+def _render_sample_input(
+ datasource: SqlaTable,
+ mapped_column: str,
+ operator: FilterOperator,
+ values: list[str],
+) -> str:
+ """
+ The filter being previewed, written the way an owner would read it.
+
+ Display-only -- it is never executed -- but it is still read as SQL, so the
+ column is quoted and the values are rendered by the dialect rather than
+ concatenated raw. A column named ``order date`` would otherwise come out as
+ two bare words.
+ """
+ quoted = datasource.quote_identifier(mapped_column)
+ if operator == FilterOperator.IN:
+ rendered = ", ".join(
+ _render_literal(datasource.database, value) for value in values
+ )
+ return f"{quoted} IN ({rendered})"
+ return (
+ f"{quoted} {operator.value} {_render_literal(datasource.database, values[0])}"
+ )
+
+
+def _render_predicate(datasource: SqlaTable, predicate: ColumnElement[Any]) -> str:
+ """
+ Compile a mirrored predicate to the text a reader would see in View query.
+
+ Every value in it is a probed constant by this point, so ``literal_binds``
+ renders the same literals the chart query carries.
+ """
+ return _compile_literal(predicate, _dialect_for(datasource.database)).replace(
+ "\n", " "
+ )
+
+
+def _render_literal(database: Database, value: Any) -> str:
+ """
+ Render a value the way it appears in the generated SQL.
+
+ Compiled by the dialect rather than formatted by hand. `str()` would render
+ a NULL as the Python repr `None` and leave a date unquoted, neither of which
+ is SQL, and hand-rolled quote-doubling would only ever have been right for
+ strings.
+ """
+ return _compile_literal(sa.literal(value), _dialect_for(database))
+
+
+def build_mirrored_predicates(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ requests: list[tuple[FilterOperator, Any]],
+ *,
+ errors: list[str] | None = None,
+ type_errors: list[str] | None = None,
+) -> list[ColumnElement[Any]]:
+ """
+ Turn collected ``(operator, value)`` mirror requests into predicates.
+
+ ``requests`` is expected to be deduplicated by the caller. Every value is
+ resolved in a single probe round trip -- one per chart query at most -- then
+ emitted as a literal constant, so "View query" shows the reader an ordinary
+ ``WHERE`` clause rather than an inline expression.
+
+ A strict bound is emitted non-strictly; see `mirror_operator`. That happens
+ here, at the one point where a ``FilterOperator`` becomes SQL, rather than
+ at the collection sites in `ExploreMixin`: the preview endpoint calls this
+ directly, so this is what keeps the predicate the editor shows an owner and
+ the predicate the chart carries from disagreeing.
+
+ :param errors: optional sink; see `evaluate_transform`.
+ :param type_errors: optional sink for a probe result the partition column
+ cannot hold -- see `probed_value_type_error`. Separate from ``errors``
+ because the two say different things to an owner: that one is "the
+ database would not evaluate this", and this one is "it evaluated, and
+ answered with the wrong kind of thing".
+ """
+ if not requests:
+ return []
+
+ partition_column = next(
+ (
+ column
+ for column in datasource.columns
+ if column.column_name == mapping.partition_column
+ ),
+ None,
+ )
+ if partition_column is None:
+ return []
+
+ # Flatten every value that needs probing into one list, remembering how many
+ # each request consumed so the results can be handed back out.
+ flat: list[Any] = []
+ spans: list[tuple[FilterOperator, int, int]] = []
+ for operator, value in requests:
+ values = list(value) if operator == FilterOperator.IN else [value]
+ spans.append((operator, len(flat), len(values)))
+ flat.extend(values)
+
+ evaluated = evaluate_transform(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ mapping.value_transform,
+ flat,
+ errors=errors,
+ )
+ if evaluated is None:
+ return []
+
+ if not _bounds_are_ordered(evaluated, spans):
+ return []
+
+ # Declining here is the last chance to decline at all: once these
+ # predicates are in the statement, a value the partition column cannot
+ # hold fails the whole chart rather than its pruning.
+ if reason := probed_value_type_error(partition_column, evaluated):
+ logger.warning(
+ "Partition transform returned a value the partition column cannot "
+ "hold; queries will not prune: %s",
+ reason,
+ )
+ if type_errors is not None:
+ type_errors.append(reason)
+ # Deliberately *not* recorded as a mirror verdict. The transform
+ # evaluated perfectly; what failed is the comparison against this
+ # dataset's partition column -- and `_mirror_verdict_cache_key` is
+ # keyed on database, catalog, schema and transform, with no partition
+ # column in it. Recorded, this dataset-specific outcome answered for
+ # every other dataset sharing the transform: `CAST(:value AS text)`
+ # mirroring happily onto a text key in dataset A was reported
+ # `evaluable: false` -- and its pruning indicator hidden -- because
+ # someone previewed the same transform against a numeric key in
+ # dataset B. A probe cache hit on A never rewrites the verdict, so it
+ # stayed wrong until the entry expired.
+ return []
+
+ sqla_col = datasource.convert_tbl_column_to_sqla_col(partition_column)
+ predicates = _predicates_from_probe(
+ sqla_col, datasource.db_engine_spec, evaluated, spans
+ )
+ if not predicates:
+ return []
+
+ # A comparison against a NULL partition value is NULL, so a row parked in a
+ # NULL partition is dropped by the mirror even when the real filter matches
+ # it -- Hive and Impala's default partition, or a transform that returns
+ # NULL for an input it cannot convert. The mirror only has to be no
+ # narrower than the filter it stands in for, so admitting NULL partitions
+ # keeps those rows. Engines still prune; they read one extra partition.
+ return [sa.or_(sa.and_(*predicates), sqla_col.is_(None))]
+
+
+def _predicates_from_probe(
+ sqla_col: ColumnElement[Any],
+ db_engine_spec: type[BaseEngineSpec],
+ evaluated: list[Any],
+ spans: list[tuple[FilterOperator, int, int]],
+) -> list[ColumnElement[Any]]:
+ """
+ One predicate on the partition column per surviving mirror request.
+
+ A request whose probe answered `None` for any of its values is skipped
+ rather than emitted: `col = NULL` is `NULL`, so it would drop every row the
+ filter keeps. A strict bound is emitted non-strictly; see `mirror_operator`.
+ """
+ predicates: list[ColumnElement[Any]] = []
+ for operator, start, length in spans:
+ chunk = evaluated[start : start + length]
+ if any(value is None for value in chunk):
+ continue
+ if operator == FilterOperator.IN:
+ # The probe answers per value, so a transform over a mixed-number
+ # filter can answer with a mixed-number partition key -- and
+ # `in_` infers the bind type from the first element it is handed.
+ # Without this, probe results of `[33, 29.02]` emit
+ # `IN (33, 29)` and prune away the partition holding `29.02`.
+ predicates.append(sqla_col.in_(normalize_mixed_numbers(chunk)))
+ else:
+ predicates.append(
+ db_engine_spec.handle_comparison_filter(
+ sqla_col, mirror_operator(operator), chunk[0]
+ )
+ )
+ return predicates
+
+
+#: Operators whose value is the lower end of a range, and whose upper-end twins.
+#:
+#: Shared with `ExploreMixin._mirror_probe_input`, which rounds a bound *outward*
+#: where the engine resolves it more coarsely than the filter carries -- backward
+#: for a lower bound, forward for an upper one. Which end an operator names is
+#: the only thing separating the two directions in either caller, so the two have
+#: to agree on it rather than each classify for itself.
+LOWER_BOUND_OPERATORS = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+}
+UPPER_BOUND_OPERATORS = {
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+#: What Python type a probe result may have, per generic type of the partition
+#: column it is about to be compared against.
+#:
+#: Only the types a mismatch can actually break a query with are listed. An
+#: unresolvable column type is absent because there is nothing to check
+#: against, and ``MULTI_VALUE`` because this module does not mirror onto an
+#: array partition key at all.
+#: ``numbers.Number`` rather than ``(int, float)``: Postgres answers
+#: ``extract(epoch from ...)`` with a `Decimal`, which is the single commonest
+#: transform this feature has, and an engine is free to answer with any number
+#: type its driver prefers. What the check is for is a *string* where a number
+#: belongs, and every numeric type is equally not that.
+_PROBE_RESULT_TYPES: dict[utils.GenericDataType, tuple[type, ...]] = {
+ utils.GenericDataType.NUMERIC: (numbers.Number,),
+ utils.GenericDataType.BOOLEAN: (bool,),
+ # A day key such as ``to_char(:value, 'YYYYMMDD')`` is legitimately text,
+ # so ``str`` is admitted -- but only for text an engine reads as an
+ # instant. `_reads_as_temporal` is the second half of this entry.
+ utils.GenericDataType.TEMPORAL: (datetime, date, str),
+ # Text, and not a number rendered as one. Not every engine accepts a number
+ # in a text comparison: Postgres refuses ``character varying = integer``,
+ # Trino ``varchar = bigint`` and BigQuery ``STRING = INT64``, all of which
+ # fail the whole chart once the predicate is in the statement. SQLite is
+ # worse -- it raises nothing and compares across storage classes as never
+ # equal, so the mirror drops every row rather than losing pruning, which is
+ # the one outcome this feature may not have. An owner whose partition key
+ # really is text writes the cast into the transform.
+ utils.GenericDataType.STRING: (str,),
+}
+
+
+#: Day/second keys a temporal column accepts as text, beyond ISO 8601.
+#: ``YYYYMMDD`` is the commonest bucketing key this feature exists for, and
+#: Postgres, Trino and BigQuery all read it as a date.
+_TEMPORAL_KEY_FORMATS = ("%Y%m%d", "%Y%m%d%H%M%S", "%Y-%m-%d %H:%M:%S")
+
+
+def _reads_as_temporal(value: str) -> bool:
+ """
+ Whether an engine would read this text as a date or timestamp.
+
+ `_PROBE_RESULT_TYPES` admits ``str`` for a temporal partition column
+ because a day key such as ``to_char(:value, 'YYYYMMDD')`` is legitimately
+ text -- but it admitted *every* string, so a transform that answers with
+ ordinary text passed the gate and failed the chart instead. On PostgreSQL a
+ ``VARCHAR`` mapped column under ``lower(:value)`` probes ``'US'`` to
+ ``'us'`` and emits ``p = 'us'`` against a ``DATE`` key, which the engine
+ refuses once the predicate is already in the statement -- so a chart that
+ worked before the mapping returns an error rather than losing its pruning.
+
+ Answered by parsing, not by asking the engine: the check runs on the
+ chart-query path, where a second round trip is the cost this module spends
+ its effort avoiding. Parsing is also the conservative direction -- anything
+ unrecognised declines, and declining costs only the pruning.
+ """
+ try:
+ datetime.fromisoformat(value)
+ return True
+ except ValueError:
+ pass
+ for fmt in _TEMPORAL_KEY_FORMATS:
+ try:
+ # Round-tripped, because `strptime` accepts unpadded fields: a bare
+ # epoch such as ``1767225600`` otherwise parses as
+ # ``%Y%m%d%H%M%S`` -- 1767-02-25 06:00 -- and is emitted as
+ # ``part_date = '1767225600'``, which is the bad-literal error this
+ # whole gate exists to stop. Re-rendering and comparing is what
+ # makes "parses" mean "is in this format" rather than "the parser
+ # found something in it".
+ if datetime.strptime(value, fmt).strftime(fmt) == value:
+ return True
+ except ValueError:
+ continue
+ return False
+
+
+def probed_value_type_error(
+ partition_column: "TableColumn",
+ values: Sequence[Any],
+) -> str | None:
+ """
+ Why these probe results cannot be compared against the partition column.
+
+ A transform can evaluate perfectly and still answer with something the
+ partition column cannot hold: ``cast(:value as text) || 'x'`` against a
+ ``BIGINT`` partition key probes fine, passes the ordering check -- two
+ strings compare -- and then reaches `handle_comparison_filter`, which is
+ just ``col >= value``. SQLAlchemy takes the bind's type from the *value*
+ rather than from the column, so the engine is the first thing to object,
+ and it objects by failing the whole chart: by that point the predicate is
+ in the statement and there is nothing left to fail open.
+
+ So the mismatch is caught here, where declining still costs only the
+ pruning, and reported to the preview, where the owner can see it before
+ they save. Nothing else in this module looks at the partition column's own
+ type: every other gate is about the mapped column.
+
+ Fails open wherever it has no information -- an unresolvable column type,
+ a generic type with nothing a mismatch can break -- and closed only on a
+ clear mismatch. ``bool`` is excluded from ``NUMERIC`` on purpose: it
+ satisfies `isinstance(x, int)` -- and `numbers.Number` -- while rendering
+ as ``true``, which is not a number to any engine that cares.
+ """
+ try:
+ generic_type = partition_column.type_generic
Review Comment:
This reads the partition column's type through `type_generic`, which is `TEMPORAL` whenever `is_dttm` is set, whatever the column physically stores. With a `BIGINT` partition column flagged temporal (`python_date_format = epoch_s`), a transform of `:value` and a bound of `1768435200`, the probe returns an integer, `_PROBE_RESULT_TYPES[TEMPORAL]` only admits `datetime`, `date` and `str`, and the gate refuses it: preview reports `reason: "type"` and chart queries lose the mirror for a mapping the engine would accept. Should the check use the column's native type from the engine spec, the way the probe-input normalization does, rather than the semantic flag?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4179203238
##########
superset/models/helpers.py:
##########
@@ -5317,6 +5633,43 @@ def get_sqla_query( # pylint: disable=too-many-arguments,too-many-locals,too-ma
db_extra=self.db_extra,
)
+ # Mirror onto the partition column. This single site covers
+ # ad-hoc filters, dashboard native filters and cross-filters,
+ # because they all arrive as entries in `filter`. `eq` rather
+ # than the raw `val`: it is the value the real predicate uses.
+ # `TEMPORAL_RANGE` is collected in its own branch below, where
+ # the range has been resolved into a pair of bounds.
+ #
+ # A grain makes the real predicate compare the *truncated*
+ # column, so the raw value no longer describes the rows it
+ # matches: drill-to-detail sends `==` on a bucket start, which
+ # every row in the bucket satisfies once truncated. Mirroring it
+ # raw would keep only the bucket's first instant.
+ #
+ # Grained ranges do mirror, by widening (see the TEMPORAL_RANGE
+ # branch below). The same trick is deferred rather than unsafe
+ # here: `==` on a bucket would have to become a two-sided range,
+ # which needs a monotonic transform -- `EQUALS` mirrors without
+ # one today -- and a parse back into a datetime; and a grained
+ # `IN` would need a union of buckets, which this sink cannot
+ # express because its entries are AND-ed.
+ if (
+ col_obj is not None
+ and op != utils.FilterOperator.TEMPORAL_RANGE
+ and not filter_grain
+ ):
+ # Window-independent, so both sinks get it. The subquery
+ # filters a different time window but the same everything
+ # else, and this filter is in `where_clause_and` for both.
+ for sink in (partition_mirror, partition_mirror_inner):
+ self._collect_partition_mirror_filter(
Review Comment:
For a numeric IN filter containing `['9007199254740993', '1.5']`, the original predicate later normalizes to floats and matches `n = 9007199254740992`, while this earlier mirror probes the unnormalized integer and excludes that row. Could collection use the final comparison values after numeric normalization and array-literal coercion?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,1613 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import re
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: Every entry point enforces it -- the typed column field, the import schema
+#: and the preview request -- because `is_transform_active` parses the stored
+#: value on each Explore load, and an unbounded string would make that parse
+#: the expensive part of rendering a chart.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+ """
+ return VALUE_PLACEHOLDER_RE.sub(_PARSE_STANDIN, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(transform: str, engine: str) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error(
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ selections = []
+ for index, value in enumerate(values):
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
Review Comment:
With a transform of `':value'`, a sample of ` || (SELECT secret FROM vault LIMIT 1) || ` compiles into an executable subquery even though validation sees only `SELECT 'NULL'`, allowing preview to expose data without the table/RLS checks. Could quoted or comment-contained placeholders be rejected, or the final compiled SQL be validated before executing the probe?
##########
superset/views/datasource/views.py:
##########
@@ -87,6 +88,51 @@ def _load_dataset_for_samples(
return dataset, None
+def _partition_transform_error(
+ orm_datasource: Any,
+ datasource_dict: dict[str, Any],
+) -> str | None:
+ """
+ The first column whose incoming value transform may not be stored, if any.
+
+ Only datasets carry a partition mapping, and only a transform the request
+ actually changes is worth refusing over -- re-sending a value already in
+ storage is what a GET-then-PUT client does, and a transform stored before
+ this check existed is disarmed at probe time instead.
+ """
+ incoming = [
+ column
+ for column in datasource_dict.get("columns") or []
+ if column.get("partition_value_transform")
+ ]
+ database = getattr(orm_datasource, "database", None)
+ if not incoming or database is None:
+ return None
+
+ stored = {
+ column.column_name: column.partition_value_transform
+ for column in orm_datasource.columns
+ }
+ for column in incoming:
Review Comment:
This legacy save accepts a valid transform longer than 1,024 characters, such as `lower(` plus 1,100 spaces plus `:value)`, but importing its unchanged export rejects the transform's length. Could this enforce `MAX_TRANSFORM_LENGTH` before `update_from_object`, as PUT and preview do?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,1613 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import re
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: Every entry point enforces it -- the typed column field, the import schema
+#: and the preview request -- because `is_transform_active` parses the stored
+#: value on each Explore load, and an unbounded string would make that parse
+#: the expensive part of rendering a chart.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+ """
+ return VALUE_PLACEHOLDER_RE.sub(_PARSE_STANDIN, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(transform: str, engine: str) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error(
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ selections = []
+ for index, value in enumerate(values):
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ selections.append(f"{_compile_literal(clause, dialect)} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ database.db_engine_spec.select_without_from_suffix,
+ )
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _compile_literal(element: Any, dialect: Dialect | None) -> str:
+ """
+ Compile with inline literals, undoing the paramstyle's percent doubling.
+
+ Both ``TextClause`` and literal compilation run the dialect's
+ ``post_process_text``, which doubles every ``%`` whenever the identifier
+ preparer asks it to -- true for MySQL and Postgres and for every spec
+ inheriting their paramstyle. That doubling exists so a later DBAPI
+ parameter-interpolation pass can undo it, and the probe has no such pass:
+ it executes with no bound parameters at all. So a transform of
+ ``date_format(:value, '%Y%m%d')`` reaches the warehouse asking for the
+ literal string ``%%Y%%m%%d``, the probe returns that instead of a date, and
+ the mirrored predicate drops every row the filter keeps.
+
+ The same normalization ``Database.compile_sqla_query`` applies for the same
+ reason. ``_double_percents`` is private and not guaranteed on a third-party
+ dialect, hence the ``getattr`` default.
+ """
+ compiled = str(
+ element.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
+ )
+ if dialect is not None and getattr(
+ dialect.identifier_preparer, "_double_percents", False
+ ):
+ compiled = compiled.replace("%%", "%")
+ return compiled
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be *asked* to stand in for itself, and the transform
+ cannot carry Jinja or call a non-deterministic function. Tier 2
+ (``blocking=False``) is everything that merely leaves the mapping inactive
+ -- including a self-mapping nobody asked for, where the partition column
+ merely happens to be the default datetime column.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column == partition_column:
+ # Asked for explicitly, so report it as the mistake it is.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+ elif not partition_mapped_column and main_dttm_col == partition_column:
+ # Resolved onto itself only because the default datetime column happens
+ # to be the partition column -- a state metadata sync could produce
+ # without anyone asking for it. The mapping is inert either way, since
+ # `resolve_partition_mapping` bails out on it, so this reports and lets
+ # the write through: blocking here means a dataset already in the state
+ # can never be saved again, not even to change its description, and
+ # there is no field whose edit would clear the error first.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "%(name)s is both the partition column and the default "
+ "datetime column, so the mapping points at itself and "
+ "stays inactive. Set a mapped column override, or change "
+ "the default datetime column.",
+ name=partition_column,
+ ),
+ blocking=False,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_bare_expression(transform, engine):
+ # Blocking, and deliberately placed in `validate_transform` rather than
+ # only at the probe: one issue here closes the PUT, the importer, the
+ # query-time gate through `is_transform_active`, the Explore indicator's
+ # active verdict and the preview endpoint, all of which already consult
+ # this function.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform must be a single SQL expression. It "
+ "cannot carry a FROM, WHERE, GROUP BY or any other clause, "
+ "and it cannot contain a sub-query."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not contains_value_placeholder(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform must contain the :value placeholder, "
+ "which stands for the filter value being mirrored."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if functions := find_non_deterministic_functions(transform, engine):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform calls %(functions)s, whose result "
+ "depends on when and where it runs. The transform is "
+ "evaluated in a separate session and the result is cached, "
+ "so the emitted predicate would freeze a snapshot of that "
+ "moment.",
+ functions=", ".join(sorted(functions)),
+ ),
+ blocking=True,
+ )
+ ]
+
+ return []
+
+
+@lru_cache(maxsize=LRU_CACHE_MAX_SIZE)
+def is_transform_active(transform: str | None, engine: str) -> bool:
+ """
+ Whether Superset will mirror filters through this transform.
+
+ `validate_transform` with the messages discarded, so the Explore indicator
+ cannot advertise a mapping the save path recorded as inactive. Anything
+ cheaper here would be a second, weaker statement of the same rule, free to
+ drift from the one the save path applies.
+
+ Blocking issues count too. Jinja and non-deterministic transforms are
+ rejected on PUT, but `CreateDatasetCommand` and import do not validate the
+ mapping, so one can still reach the database -- and it would never mirror a
+ filter either.
+
+ Memoized because `partition_filter_mapping_summary` is serialized on every
+ Explore and dashboard load and this parses the transform. The key is
+ everything the answer depends on: `validate_transform` reads no session, no
+ locale and no config beyond `SQL_MAX_PARSE_LENGTH`, which bounds the parser
+ rather than changing a verdict within that bound.
+ """
+ return not validate_transform(transform, engine)
+
+
+def preview_partition_mapping( # pylint: disable=too-many-return-statements
+ datasource: SqlaTable,
+ *,
+ mapped_column: str,
+ value_transform: str | None,
+ sample_values: list[str],
+ operator: FilterOperator = FilterOperator.EQUALS,
+ is_monotonic: bool = False,
+ partition_column: str | None = None,
+) -> dict[str, Any]:
+ """
+ Evaluate a candidate mapping and describe the predicate it would emit.
+
+ Shares the evaluator -- and therefore the probe cache -- with the query
+ path, so preview and runtime cannot drift and a previewed transform warms
+ the chart path for free. The predicate itself comes from
+ `build_mirrored_predicates`, the same builder the query path uses, so
+ operator shapes cannot drift either: what the panel shows is what a chart
+ would emit.
+
+ Validation runs first and the engine second: a half-typed transform is by
+ definition unparseable, so most of what a text input produces costs zero
+ queries.
+
+ Every part of the mapping is taken from the request rather than the stored
+ dataset. The editor previews while the owner is still editing -- a mapping
+ that has to be saved before it can be checked is not a preview.
+ """
+ partition_column = partition_column or datasource.partition_column
+ if not partition_column:
+ return {
+ "valid": False,
+ "reason": "unconfigured",
+ "error": _("No partition column is set."),
+ }
+
+ columns_by_name = {str(column.column_name): column for column in datasource.columns}
+ if mapped_column not in columns_by_name:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _("%(name)s is not a column on this dataset.", name=mapped_column),
+ }
+
+ # The bail-out `resolve_partition_mapping` makes at query time, and that
+ # `partition_filter_mapping_summary` repeats for the Explore indicator.
+ # Without it here, preview reports a valid emitted predicate for a mapping
+ # no chart will ever mirror -- the one answer a preview panel must not give.
+ if has_active_advanced_data_type(columns_by_name[mapped_column]):
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _(
+ "%(name)s has an advanced data type, so its filters are "
+ "translated into their own predicate shape and cannot be "
+ "mirrored onto the partition column.",
+ name=mapped_column,
+ ),
+ }
+
+ engine = datasource.database.backend
+ for issue in validate_partition_mapping(
+ column_names=set(columns_by_name),
+ partition_column=str(partition_column),
+ partition_mapped_column=mapped_column,
+ main_dttm_col=datasource.main_dttm_col,
+ transform=value_transform,
+ engine=engine,
+ ):
+ return {
+ "valid": False,
+ # The parse failure is the one an owner sees constantly, and it is
+ # the only one the mockup gives its own headline to.
+ "reason": (
+ "parse"
+ if issue.field == "partition_value_transform"
+ and not is_parseable(value_transform, engine)
+ else "validation"
+ ),
+ "error": str(issue.message),
+ }
+
+ # The policy every other stored expression goes through. The save path
+ # applies it in `UpdateDatasetCommand._validate_partition_mapping`, but
+ # preview evaluates a candidate transform that has not been saved, so
+ # without this the gate had a door around it. See
+ # `stored_expression_error` for what is being kept out and why.
+ if reason := stored_expression_error(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ cast(str, value_transform),
+ ):
+ return {"valid": False, "reason": "validation", "error": reason}
+
+ mapping = PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=mapped_column,
+ value_transform=cast(str, value_transform),
+ is_monotonic=is_monotonic,
+ equality_is_safe=equality_mirrors_safely(
+ columns_by_name[mapped_column], datasource.database.db_engine_spec
+ ),
+ )
+ sample_input = _render_sample_input(
+ datasource, mapped_column, operator, sample_values
+ )
+
+ if operator not in PREVIEWABLE_OPERATORS:
+ # Checked before `mirrors`, which lets `TEMPORAL_RANGE` through when the
+ # transform is declared monotonic -- and the single sample value would
+ # then reach `handle_comparison_filter`, which has no case for a range
+ # and raises. The request schema rejects it too; this keeps the function
+ # honest for any other caller.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is mirrored as a pair of bounds, which "
+ "a preview of a single value cannot describe.",
+ operator=operator.value,
+ ),
+ }
+
+ if not mapping.mirrors(operator):
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is only mirrored when the transform "
+ "preserves ordering, which this one is not declared to do.",
+ operator=operator.value,
+ ),
+ }
+
+ value: Any = sample_values if operator == FilterOperator.IN else sample_values[0]
+ errors: list[str] = []
+ predicates = build_mirrored_predicates(
+ datasource, mapping, [(operator, value)], errors=errors
+ )
+ if not predicates:
+ return {
+ "valid": False,
+ "reason": "engine",
+ "sample_input": sample_input,
+ "error": (
+ _(
+ "The transform could not be evaluated against the "
+ "database: %(reason)s",
+ reason=errors[0],
+ )
+ if errors
+ else _("The transform could not be evaluated against the database.")
+ ),
+ }
+
+ return {
+ "valid": True,
+ "sample_input": sample_input,
+ "emitted_predicate": _render_predicate(datasource, predicates[0]),
+ }
+
+
+def _render_sample_input(
+ datasource: SqlaTable,
+ mapped_column: str,
+ operator: FilterOperator,
+ values: list[str],
+) -> str:
+ """
+ The filter being previewed, written the way an owner would read it.
+
+ Display-only -- it is never executed -- but it is still read as SQL, so the
+ column is quoted and the values are rendered by the dialect rather than
+ concatenated raw. A column named ``order date`` would otherwise come out as
+ two bare words.
+ """
+ quoted = datasource.quote_identifier(mapped_column)
+ if operator == FilterOperator.IN:
+ rendered = ", ".join(
+ _render_literal(datasource.database, value) for value in values
+ )
+ return f"{quoted} IN ({rendered})"
+ return (
+ f"{quoted} {operator.value} {_render_literal(datasource.database, values[0])}"
+ )
+
+
+def _render_predicate(datasource: SqlaTable, predicate: ColumnElement[Any]) -> str:
+ """
+ Compile a mirrored predicate to the text a reader would see in View query.
+
+ Every value in it is a probed constant by this point, so ``literal_binds``
+ renders the same literals the chart query carries.
+ """
+ return _compile_literal(predicate, _dialect_for(datasource.database)).replace(
+ "\n", " "
+ )
+
+
+def _render_literal(database: Database, value: Any) -> str:
+ """
+ Render a value the way it appears in the generated SQL.
+
+ Compiled by the dialect rather than formatted by hand. `str()` would render
+ a NULL as the Python repr `None` and leave a date unquoted, neither of which
+ is SQL, and hand-rolled quote-doubling would only ever have been right for
+ strings.
+ """
+ return _compile_literal(sa.literal(value), _dialect_for(database))
+
+
+def build_mirrored_predicates(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ requests: list[tuple[FilterOperator, Any]],
+ *,
+ errors: list[str] | None = None,
+) -> list[ColumnElement[Any]]:
+ """
+ Turn collected ``(operator, value)`` mirror requests into predicates.
+
+ ``requests`` is expected to be deduplicated by the caller. Every value is
+ resolved in a single probe round trip -- one per chart query at most -- then
+ emitted as a literal constant, so "View query" shows the reader an ordinary
+ ``WHERE`` clause rather than an inline expression.
+
+ :param errors: optional sink; see `evaluate_transform`.
+ """
+ if not requests:
+ return []
+
+ partition_column = next(
+ (
+ column
+ for column in datasource.columns
+ if column.column_name == mapping.partition_column
+ ),
+ None,
+ )
+ if partition_column is None:
+ return []
+
+ # Flatten every value that needs probing into one list, remembering how many
+ # each request consumed so the results can be handed back out.
+ flat: list[Any] = []
+ spans: list[tuple[FilterOperator, int, int]] = []
+ for operator, value in requests:
+ values = list(value) if operator == FilterOperator.IN else [value]
+ spans.append((operator, len(flat), len(values)))
+ flat.extend(values)
+
+ evaluated = evaluate_transform(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ mapping.value_transform,
+ flat,
+ errors=errors,
+ )
+ if evaluated is None:
+ return []
+
+ if not _bounds_are_ordered(evaluated, spans):
+ return []
+
+ sqla_col = datasource.convert_tbl_column_to_sqla_col(partition_column)
+ db_engine_spec = datasource.db_engine_spec
+
+ predicates: list[ColumnElement[Any]] = []
+ for operator, start, length in spans:
+ chunk = evaluated[start : start + length]
+ if any(value is None for value in chunk):
+ continue
+ if operator == FilterOperator.IN:
+ predicates.append(sqla_col.in_(chunk))
Review Comment:
Mixed probe results such as `[33, 29.02]` make SQLAlchemy infer an integer IN bind from the first value, emitting `p IN (33, 29)` and dropping the matching `29.02` row. Could this preserve numeric output types as the original filter's mixed-number normalization does?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,1613 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import re
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: Every entry point enforces it -- the typed column field, the import schema
+#: and the preview request -- because `is_transform_active` parses the stored
+#: value on each Explore load, and an unbounded string would make that parse
+#: the expensive part of rendering a chart.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+ """
+ return VALUE_PLACEHOLDER_RE.sub(_PARSE_STANDIN, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(transform: str, engine: str) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error(
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ selections = []
+ for index, value in enumerate(values):
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ selections.append(f"{_compile_literal(clause, dialect)} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ database.db_engine_spec.select_without_from_suffix,
+ )
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _compile_literal(element: Any, dialect: Dialect | None) -> str:
+ """
+ Compile with inline literals, undoing the paramstyle's percent doubling.
+
+ Both ``TextClause`` and literal compilation run the dialect's
+ ``post_process_text``, which doubles every ``%`` whenever the identifier
+ preparer asks it to -- true for MySQL and Postgres and for every spec
+ inheriting their paramstyle. That doubling exists so a later DBAPI
+ parameter-interpolation pass can undo it, and the probe has no such pass:
+ it executes with no bound parameters at all. So a transform of
+ ``date_format(:value, '%Y%m%d')`` reaches the warehouse asking for the
+ literal string ``%%Y%%m%%d``, the probe returns that instead of a date, and
+ the mirrored predicate drops every row the filter keeps.
+
+ The same normalization ``Database.compile_sqla_query`` applies for the same
+ reason. ``_double_percents`` is private and not guaranteed on a third-party
+ dialect, hence the ``getattr`` default.
+ """
+ compiled = str(
+ element.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
+ )
+ if dialect is not None and getattr(
+ dialect.identifier_preparer, "_double_percents", False
+ ):
+ compiled = compiled.replace("%%", "%")
+ return compiled
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be *asked* to stand in for itself, and the transform
+ cannot carry Jinja or call a non-deterministic function. Tier 2
+ (``blocking=False``) is everything that merely leaves the mapping inactive
+ -- including a self-mapping nobody asked for, where the partition column
+ merely happens to be the default datetime column.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column == partition_column:
+ # Asked for explicitly, so report it as the mistake it is.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+ elif not partition_mapped_column and main_dttm_col == partition_column:
+ # Resolved onto itself only because the default datetime column happens
+ # to be the partition column -- a state metadata sync could produce
+ # without anyone asking for it. The mapping is inert either way, since
+ # `resolve_partition_mapping` bails out on it, so this reports and lets
+ # the write through: blocking here means a dataset already in the state
+ # can never be saved again, not even to change its description, and
+ # there is no field whose edit would clear the error first.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "%(name)s is both the partition column and the default "
+ "datetime column, so the mapping points at itself and "
+ "stays inactive. Set a mapped column override, or change "
+ "the default datetime column.",
+ name=partition_column,
+ ),
+ blocking=False,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_bare_expression(transform, engine):
+ # Blocking, and deliberately placed in `validate_transform` rather than
+ # only at the probe: one issue here closes the PUT, the importer, the
+ # query-time gate through `is_transform_active`, the Explore indicator's
+ # active verdict and the preview endpoint, all of which already consult
+ # this function.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform must be a single SQL expression. It "
+ "cannot carry a FROM, WHERE, GROUP BY or any other clause, "
+ "and it cannot contain a sub-query."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not contains_value_placeholder(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform must contain the :value placeholder, "
+ "which stands for the filter value being mirrored."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if functions := find_non_deterministic_functions(transform, engine):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform calls %(functions)s, whose result "
+ "depends on when and where it runs. The transform is "
+ "evaluated in a separate session and the result is cached, "
+ "so the emitted predicate would freeze a snapshot of that "
+ "moment.",
+ functions=", ".join(sorted(functions)),
+ ),
+ blocking=True,
+ )
+ ]
+
+ return []
+
+
+@lru_cache(maxsize=LRU_CACHE_MAX_SIZE)
+def is_transform_active(transform: str | None, engine: str) -> bool:
+ """
+ Whether Superset will mirror filters through this transform.
+
+ `validate_transform` with the messages discarded, so the Explore indicator
+ cannot advertise a mapping the save path recorded as inactive. Anything
+ cheaper here would be a second, weaker statement of the same rule, free to
+ drift from the one the save path applies.
+
+ Blocking issues count too. Jinja and non-deterministic transforms are
+ rejected on PUT, but `CreateDatasetCommand` and import do not validate the
+ mapping, so one can still reach the database -- and it would never mirror a
+ filter either.
+
+ Memoized because `partition_filter_mapping_summary` is serialized on every
+ Explore and dashboard load and this parses the transform. The key is
+ everything the answer depends on: `validate_transform` reads no session, no
+ locale and no config beyond `SQL_MAX_PARSE_LENGTH`, which bounds the parser
+ rather than changing a verdict within that bound.
+ """
+ return not validate_transform(transform, engine)
+
+
+def preview_partition_mapping( # pylint: disable=too-many-return-statements
+ datasource: SqlaTable,
+ *,
+ mapped_column: str,
+ value_transform: str | None,
+ sample_values: list[str],
+ operator: FilterOperator = FilterOperator.EQUALS,
+ is_monotonic: bool = False,
+ partition_column: str | None = None,
+) -> dict[str, Any]:
+ """
+ Evaluate a candidate mapping and describe the predicate it would emit.
+
+ Shares the evaluator -- and therefore the probe cache -- with the query
+ path, so preview and runtime cannot drift and a previewed transform warms
+ the chart path for free. The predicate itself comes from
+ `build_mirrored_predicates`, the same builder the query path uses, so
+ operator shapes cannot drift either: what the panel shows is what a chart
+ would emit.
+
+ Validation runs first and the engine second: a half-typed transform is by
+ definition unparseable, so most of what a text input produces costs zero
+ queries.
+
+ Every part of the mapping is taken from the request rather than the stored
+ dataset. The editor previews while the owner is still editing -- a mapping
+ that has to be saved before it can be checked is not a preview.
+ """
+ partition_column = partition_column or datasource.partition_column
+ if not partition_column:
+ return {
+ "valid": False,
+ "reason": "unconfigured",
+ "error": _("No partition column is set."),
+ }
+
+ columns_by_name = {str(column.column_name): column for column in datasource.columns}
+ if mapped_column not in columns_by_name:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _("%(name)s is not a column on this dataset.", name=mapped_column),
+ }
+
+ # The bail-out `resolve_partition_mapping` makes at query time, and that
+ # `partition_filter_mapping_summary` repeats for the Explore indicator.
+ # Without it here, preview reports a valid emitted predicate for a mapping
+ # no chart will ever mirror -- the one answer a preview panel must not give.
+ if has_active_advanced_data_type(columns_by_name[mapped_column]):
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _(
+ "%(name)s has an advanced data type, so its filters are "
+ "translated into their own predicate shape and cannot be "
+ "mirrored onto the partition column.",
+ name=mapped_column,
+ ),
+ }
+
+ engine = datasource.database.backend
+ for issue in validate_partition_mapping(
+ column_names=set(columns_by_name),
+ partition_column=str(partition_column),
+ partition_mapped_column=mapped_column,
+ main_dttm_col=datasource.main_dttm_col,
+ transform=value_transform,
+ engine=engine,
+ ):
+ return {
+ "valid": False,
+ # The parse failure is the one an owner sees constantly, and it is
+ # the only one the mockup gives its own headline to.
+ "reason": (
+ "parse"
+ if issue.field == "partition_value_transform"
+ and not is_parseable(value_transform, engine)
+ else "validation"
+ ),
+ "error": str(issue.message),
+ }
+
+ # The policy every other stored expression goes through. The save path
+ # applies it in `UpdateDatasetCommand._validate_partition_mapping`, but
+ # preview evaluates a candidate transform that has not been saved, so
+ # without this the gate had a door around it. See
+ # `stored_expression_error` for what is being kept out and why.
+ if reason := stored_expression_error(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ cast(str, value_transform),
+ ):
+ return {"valid": False, "reason": "validation", "error": reason}
+
+ mapping = PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=mapped_column,
+ value_transform=cast(str, value_transform),
+ is_monotonic=is_monotonic,
+ equality_is_safe=equality_mirrors_safely(
+ columns_by_name[mapped_column], datasource.database.db_engine_spec
+ ),
+ )
+ sample_input = _render_sample_input(
+ datasource, mapped_column, operator, sample_values
+ )
+
+ if operator not in PREVIEWABLE_OPERATORS:
+ # Checked before `mirrors`, which lets `TEMPORAL_RANGE` through when the
+ # transform is declared monotonic -- and the single sample value would
+ # then reach `handle_comparison_filter`, which has no case for a range
+ # and raises. The request schema rejects it too; this keeps the function
+ # honest for any other caller.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is mirrored as a pair of bounds, which "
+ "a preview of a single value cannot describe.",
+ operator=operator.value,
+ ),
+ }
+
+ if not mapping.mirrors(operator):
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is only mirrored when the transform "
+ "preserves ordering, which this one is not declared to do.",
+ operator=operator.value,
+ ),
+ }
+
+ value: Any = sample_values if operator == FilterOperator.IN else sample_values[0]
Review Comment:
Preview passes string samples directly to the probe, while chart filters first coerce numeric-column values: on SQLite, `typeof(:value)` with sample `2025` previews a partition key of `'text'`, but the equivalent chart filter emits `'integer'`. Could preview apply the same column-aware value normalization before evaluating the transform?
##########
superset/models/helpers.py:
##########
@@ -5689,7 +6106,20 @@ def get_sqla_query( # pylint: disable=too-many-arguments,too-many-locals,too-ma
)
if _inner_filter is not None:
inner_time_filter = [_inner_filter]
- subq = subq.where(and_(*(where_clause_and + inner_time_filter)))
+ # The mirrors swapped for the inner window's own, since the
+ # time filter just built describes that window: an outer-window
+ # mirror here would demand partition keys from a period this
+ # subquery excludes, and the empty ranking would drop the
+ # comparison series from the join below.
+ subq = subq.where(
+ and_(
+ *(
+ where_clause_and_without_mirrors
+ + inner_partition_mirror_predicates
Review Comment:
On ClickHouse, `time_groupby_inline` skips the ranking subquery's time predicate, but these mirrors still restrict it to the selected window, so enabling mapping can change which top series the chart returns (A can win all-time while B wins inside the window). Could inner time mirrors only be added when the corresponding time predicate is actually applied?
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/DatasourceEditor.tsx:
##########
@@ -1128,10 +1222,22 @@ function DatasourceEditor({
validationErrors = validationErrors.concat(folderValidation.errors);
}
+ // Validate the partition filter mapping. `databaseColumns` rather than
+ // `datasource.columns`, because the two only meet in `onChangeInternal`
+ // when the payload is assembled -- `datasource.columns` does not carry the
+ // transform the owner just typed.
+ if (isFeatureEnabled(FeatureFlag.PartitionFilterMapping)) {
+ validationErrors = validationErrors.concat(
Review Comment:
A calculated mapped-column override accepted by PUT/import is absent from `databaseColumns`, so reopening that dataset and changing only its description reports that the mapped column does not exist and disables Save. Could mapping validation include the live calculated columns while keeping the partition-column picker physical-only?
##########
tests/unit_tests/commands/dataset/update_test.py:
##########
@@ -1366,3 +1375,254 @@ def test_update_dataset_rejects_malicious_fetch_values_predicate(
and "fetch_values_predicate" in (exc.field_name or "")
for exc in excinfo.value._exceptions
)
+
+
+def _mapping_command(
+ mocker: MockerFixture,
+ transform: str | None,
+ *,
+ partition_mapped_column: str | None = None,
+) -> UpdateDatasetCommand:
+ """A command whose stored dataset maps `event_time` onto `dt_epoch`."""
+ mapped_column = mocker.MagicMock()
+ mapped_column.column_name = "event_time"
+ mapped_column.partition_value_transform = transform
+ partition_column = mocker.MagicMock()
+ partition_column.column_name = "dt_epoch"
+ # The partition column is the target of a mapping, never the source of one.
+ partition_column.partition_value_transform = None
+
+ mock_dataset = mocker.MagicMock(is_managed_externally=False)
+ mock_dataset.database.backend = "sqlite"
+ mock_dataset.catalog = None
+ mock_dataset.schema = "main"
+ mock_dataset.columns = [mapped_column, partition_column]
+ mock_dataset.main_dttm_col = "event_time"
+ mock_dataset.partition_column = "dt_epoch"
+ mock_dataset.partition_mapped_column = partition_mapped_column
+
+ command = UpdateDatasetCommand(1, {})
+ command._model = mock_dataset
+ return command
+
+
+@with_feature_flags(PARTITION_FILTER_MAPPING=True)
+def test_an_unparseable_transform_does_not_block_the_save(
+ mocker: MockerFixture,
+) -> None:
+ """
+ An unparseable transform is a Tier-2 issue: the mapping saves and stays
+ inactive. `validate_stored_expression` rejects anything it cannot parse, so
+ running it here would turn that into a blocking error and cost the owner the
+ rest of their edits.
+ """
+ gate = mocker.patch("superset.commands.dataset.update.validate_stored_expression")
+ command = _mapping_command(mocker, "unix_timestamp(:value")
+
+ exceptions: list[ValidationError] = []
+ command._validate_partition_mapping(exceptions)
+
+ assert exceptions == []
+ gate.assert_not_called()
+
+
+@with_feature_flags(PARTITION_FILTER_MAPPING=True)
+def test_a_parseable_transform_still_goes_through_the_stored_expression_gate(
+ mocker: MockerFixture,
+) -> None:
+ """The parser gate that governs every other stored expression still runs."""
+ gate = mocker.patch("superset.commands.dataset.update.validate_stored_expression")
+ command = _mapping_command(mocker, "unix_timestamp(:value)")
+
+ exceptions: list[ValidationError] = []
+ command._validate_partition_mapping(exceptions)
+
+ assert exceptions == []
+ gate.assert_called_once()
+ assert ":value" not in gate.call_args.args[-1]
+
+
+@with_feature_flags(PARTITION_FILTER_MAPPING=True)
+@pytest.mark.parametrize(
+ "transform",
+ [
+ "unix_timestamp(:value) UNION ALL SELECT password FROM ab_user",
+ "unix_timestamp(:value); DROP TABLE ab_user",
+ "password || :value FROM ab_user",
+ ],
+ ids=["set-operation", "multi-statement", "bare-from"],
+)
+def test_a_transform_that_is_the_wrong_sql_still_reaches_the_gate(
+ mocker: MockerFixture, transform: str
+) -> None:
+ """
+ The companion to the test above, and the reason the skip condition is "not
+ SQL yet" rather than "does not parse". All three of these fail to parse as
+ a single statement, exactly as a half-typed transform does -- so a skip
+ keyed on parseability would have waved them through. None of them is on the
+ way to a valid transform.
+ """
+ gate = mocker.patch("superset.commands.dataset.update.validate_stored_expression")
+ command = _mapping_command(mocker, transform)
+
+ exceptions: list[ValidationError] = []
+ command._validate_partition_mapping(exceptions)
+
+ # Either the shape issue reports it or the gate does; what matters is that
+ # it is not silently accepted the way an unfinished transform is.
+ assert exceptions or gate.called
+
+
+@with_feature_flags(PARTITION_FILTER_MAPPING=True)
+def test_a_jinja_transform_is_still_rejected(mocker: MockerFixture) -> None:
+ """
+ Skipping the gate for unparseable transforms is not a hole for templating:
+ Jinja is a blocking issue of its own, reported before the gate is reached.
+ """
+ mocker.patch("superset.commands.dataset.update.validate_stored_expression")
+ command = _mapping_command(mocker, "unix_timestamp({{ current_user_id() }})")
+
+ exceptions: list[ValidationError] = []
+ command._validate_partition_mapping(exceptions)
+
+ assert [exc.field_name for exc in exceptions] == ["partition_value_transform"]
+
+
+@with_feature_flags(PARTITION_FILTER_MAPPING=True)
+def test_a_description_only_put_survives_an_implicit_self_mapping(
+ mocker: MockerFixture,
+) -> None:
+ """
+ `fetch_metadata` could choose the partition column as the default datetime
+ column without anyone asking, and a blocking self-mapping error then made
+ the dataset unsaveable forever -- including by the very write that would
+ have set the override that fixes it, and including a write that changes
+ nothing but the description.
+
+ The mapping is inert in that state either way, since
+ `resolve_partition_mapping` bails out on it, so the issue is reported
+ rather than blocking.
+ """
+ mocker.patch("superset.commands.dataset.update.validate_stored_expression")
+ command = _mapping_command(mocker, "unix_timestamp(:value)")
+ command._model.main_dttm_col = "dt_epoch"
Review Comment:
The pre-commit mypy check fails here because `_model` is typed as `SqlaTable | None`; setting it in the helper does not narrow the attribute at this call site. Could the test assert that the model exists before assigning `main_dttm_col`?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,1613 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import re
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: Every entry point enforces it -- the typed column field, the import schema
+#: and the preview request -- because `is_transform_active` parses the stored
+#: value on each Explore load, and an unbounded string would make that parse
+#: the expensive part of rendering a chart.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+ """
+ return VALUE_PLACEHOLDER_RE.sub(_PARSE_STANDIN, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(transform: str, engine: str) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error(
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ selections = []
+ for index, value in enumerate(values):
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ selections.append(f"{_compile_literal(clause, dialect)} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ database.db_engine_spec.select_without_from_suffix,
+ )
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _compile_literal(element: Any, dialect: Dialect | None) -> str:
+ """
+ Compile with inline literals, undoing the paramstyle's percent doubling.
+
+ Both ``TextClause`` and literal compilation run the dialect's
+ ``post_process_text``, which doubles every ``%`` whenever the identifier
+ preparer asks it to -- true for MySQL and Postgres and for every spec
+ inheriting their paramstyle. That doubling exists so a later DBAPI
+ parameter-interpolation pass can undo it, and the probe has no such pass:
+ it executes with no bound parameters at all. So a transform of
+ ``date_format(:value, '%Y%m%d')`` reaches the warehouse asking for the
+ literal string ``%%Y%%m%%d``, the probe returns that instead of a date, and
+ the mirrored predicate drops every row the filter keeps.
+
+ The same normalization ``Database.compile_sqla_query`` applies for the same
+ reason. ``_double_percents`` is private and not guaranteed on a third-party
+ dialect, hence the ``getattr`` default.
+ """
+ compiled = str(
+ element.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
+ )
+ if dialect is not None and getattr(
+ dialect.identifier_preparer, "_double_percents", False
+ ):
+ compiled = compiled.replace("%%", "%")
+ return compiled
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be *asked* to stand in for itself, and the transform
+ cannot carry Jinja or call a non-deterministic function. Tier 2
+ (``blocking=False``) is everything that merely leaves the mapping inactive
+ -- including a self-mapping nobody asked for, where the partition column
+ merely happens to be the default datetime column.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column == partition_column:
+ # Asked for explicitly, so report it as the mistake it is.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+ elif not partition_mapped_column and main_dttm_col == partition_column:
+ # Resolved onto itself only because the default datetime column happens
+ # to be the partition column -- a state metadata sync could produce
+ # without anyone asking for it. The mapping is inert either way, since
+ # `resolve_partition_mapping` bails out on it, so this reports and lets
+ # the write through: blocking here means a dataset already in the state
+ # can never be saved again, not even to change its description, and
+ # there is no field whose edit would clear the error first.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "%(name)s is both the partition column and the default "
+ "datetime column, so the mapping points at itself and "
+ "stays inactive. Set a mapped column override, or change "
+ "the default datetime column.",
+ name=partition_column,
+ ),
+ blocking=False,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_bare_expression(transform, engine):
+ # Blocking, and deliberately placed in `validate_transform` rather than
+ # only at the probe: one issue here closes the PUT, the importer, the
+ # query-time gate through `is_transform_active`, the Explore indicator's
+ # active verdict and the preview endpoint, all of which already consult
+ # this function.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
Review Comment:
This error and seven other new strings are absent from `messages.pot`, leaving them outside the translation workflow and failing both Babel extraction and the unit-suite catalog-drift assertion at this head. Could the template and affected catalogs be regenerated for the current strings?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4272307133
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,3128 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: The opening and closing delimiters of each kind of Jinja block. The probe
+#: would render these in a different context at a different time from the chart
+#: query, so a transform holding one is rejected at save time.
+JINJA_BLOCK_DELIMITERS = (("{{", "}}"), ("{%", "%}"), ("{#", "#}"))
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: A PostgreSQL Unicode-escaped identifier, ``U&"..."``.
+#:
+#: The second construct that breaks the premise above, and in the same way:
+#: ``U&"\\0071uery_to_xml"(...)`` parses as an anonymous function whose name is
+#: the *literal* ``\\0071uery_to_xml``, so the function denylist is matching a
+#: name the engine never sees -- PostgreSQL decodes the escape and runs
+#: ``query_to_xml``, handing a dataset owner rows from outside their RLS scope
+#: through the preview's ``emitted_predicate``.
+#:
+#: Normalizing the escapes and re-checking would be the other repair, and is
+#: worse: it means reimplementing one engine's identifier decoding well enough
+#: to be a security boundary. Refusing the construct is exact, and costs
+#: nothing real -- a transform is a scalar function of ``:value``, and there is
+#: no reason to name a function or column through an escape sequence.
+#:
+#: Refused on every engine, like the executable comment, so a transform stored
+#: on SQLite cannot detonate when the dataset is re-pointed at PostgreSQL. The
+#: ``&`` may be separated from the ``U`` by nothing at all, but whitespace or a
+#: comment between the prefix and the string is not accepted by PostgreSQL
+#: either, so the strict form is the whole surface.
+#:
+#: Matched in raw text, so the prefix is refused inside a string literal too.
+#: That is the same trade the executable comment makes and has the same
+#: justification: a gate whose contract is to fire *before* the parse cannot
+#: ask the parse whether the text was quoted. ``concat(:value, 'u&"x"')`` is
+#: refused, which costs an owner nothing anyone writes.
+UNICODE_ESCAPED_IDENTIFIER_RE = re.compile(r'\bU&"', re.IGNORECASE)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate: a transform such as
+#: ``datediff(day, :value, LOCALTIMESTAMP)`` for a relative partition key is
+#: evaluated once and then keeps emitting yesterday's answer, so the chart
+#: silently drops rows after midnight.
+#:
+#: Matched by SQL function name, so every engine's spelling of "now" has to be
+#: named -- the ANSI four were not enough. Listed rather than delegated to the
+#: engine specs because the risk is the same everywhere and a spec that had not
+#: got round to declaring its own would fail open; a name no engine has is
+#: inert, so over-listing costs nothing.
+NON_DETERMINISTIC_FUNCTIONS = {
+ # ANSI, and the engines that spell it this way.
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "LOCALTIME",
+ "LOCALTIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+ # PostgreSQL. `now()` is statement-stable; these two are not even that.
+ "CLOCK_TIMESTAMP",
+ "STATEMENT_TIMESTAMP",
+ "TIMEOFDAY",
+ # MySQL and MariaDB.
+ "CURDATE",
+ "CURTIME",
+ "SYSDATE",
+ "UTC_DATE",
+ "UTC_TIME",
+ "UTC_TIMESTAMP",
+ "UUID_SHORT",
+ # Oracle.
+ "SYSTIMESTAMP",
+ "SYS_GUID",
+ # SQL Server.
+ "GETDATE",
+ "GETUTCDATE",
+ "SYSDATETIME",
+ "SYSUTCDATETIME",
+ "SYSDATETIMEOFFSET",
+ "NEWID",
+ # BigQuery.
+ "CURRENT_DATETIME",
+ "GENERATE_UUID",
+ # Snowflake.
+ "RANDSTR",
+ "UUID_STRING",
+ # ClickHouse.
+ "NOW64",
+ "RANDCANONICAL",
+ "GENERATEUUIDV4",
+ # H2 and Derby, which the test fixtures use.
+ "RANDOM_UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+class Unmirrorable:
+ """
+ A filter no mirror can stand in for, and why.
+
+ Returned by `ExploreMixin.mirror_probe_request` for a value the engine
+ compares more coarsely than the filter carries, one it cannot render as a
+ literal, one in a time frame the transform would discard, or an ``IN`` list
+ with a member of any of those kinds. An object rather than `None`, because
+ `None` is a filter value in its own right.
+
+ The reason rides along because the preview has to explain the decline to
+ the owner, and the two declines want different advice: "the engine compares
+ less of this value than you typed, so map a column it compares in full" is
+ sound guidance for a `DATE` column and actively misleading for an
+ offset-bearing bound on a `TIMESTAMP` one, which already is such a column.
+ Carried rather than re-derived so the preview's explanation cannot come
+ apart from the chart path's decision.
+
+ Lives here rather than beside that method so the preview can read it too:
+ `superset.models.helpers` imports this module, so these can only cross the
+ boundary in this direction. Both callers recognise the same instances -- a
+ preview that answered "valid" for a request the chart path declines is the
+ drift this is here to prevent.
+ """
+
+ __slots__ = ("reason",)
+
+ def __init__(self, reason: str) -> None:
+ self.reason = reason
+
+ def __repr__(self) -> str:
+ return f"<Unmirrorable {self.reason}>"
+
+
+#: The ordinary decline: whatever the mirror cannot be built from, with the
+#: engine's own comparison resolution as the reason an owner can act on.
+UNMIRRORABLE = Unmirrorable("resolution")
+
+#: A value carrying a UTC offset, declined whatever the column's resolution.
+#: A transform such as ``CAST(:value AS TIMESTAMP)`` drops the offset, so even
+#: an engine that compares the whole instant would be probed in the wrong
+#: frame -- which is not something mapping a different column fixes.
+UNMIRRORABLE_OFFSET = Unmirrorable("offset")
+
+
+def is_unmirrorable(value: Any) -> bool:
+ """Whether `mirror_probe_request` declined this request."""
+ return isinstance(value, Unmirrorable)
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+#: Declared types whose comparison ignores trailing blanks.
+#:
+#: The fixed-width character types, which the SQL standard has compare as
+#: though both sides were padded to the same length -- so ``'US'`` and
+#: ``'US '`` are equal in a ``CHARACTER(3)``, while ``lower()`` of the two is
+#: not. Spelled out rather than matched by prefix because the variable-width
+#: names start with the same letters: ``VARCHAR`` and ``CHARACTER VARYING``
+#: compare the blanks and must not land here.
+PADDED_CHARACTER_TYPES = frozenset(
+ {
+ "CHAR",
+ "NCHAR",
+ # PostgreSQL's own name for ``CHARACTER``, which is what reflection
+ # reports for a ``CHAR(n)`` column there.
+ "BPCHAR",
+ "CHARACTER",
+ "NATIONAL CHAR",
+ "NATIONAL CHARACTER",
+ }
+)
+
+
+def _is_padded_character_type(column: TableColumn) -> bool:
+ """
+ Whether ``column``'s declared type compares without its trailing blanks.
+
+ Read off the declared type rather than the engine spec's resolved one: the
+ specs map ``CHAR`` and ``VARCHAR`` onto the same `sqlalchemy.String`, so
+ the distinction this needs is gone by then. The length suffix is dropped
+ and the name matched against `PADDED_CHARACTER_TYPES`, so an unfamiliar
+ spelling answers ``False`` and the engine-level flag decides as before --
+ this gate adds a decline rather than lifting one. A column with no
+ declared type has nothing to read, and answers the same way.
+ """
+ if not isinstance(column.type, str):
+ return False
+ native = re.sub(r"\s+", " ", column.type.strip().upper())
+ return native.split("(")[0].strip() in PADDED_CHARACTER_TYPES
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ Padding is asked about per column, because it is a property of the *type*
+ rather than of the engine. ``binary_string_comparison`` speaks for an
+ engine's default text comparison, and on PostgreSQL -- which declares it
+ -- a ``CHAR(2)`` still matches a filter for ``'US '`` against a stored
+ ``'US'``, because the standard says a padded character type compares
+ without its trailing blanks. The mirror ``region_key = lower('US ')`` then
+ excludes the row. So a fixed-width character type declines whatever the
+ engine says, and an engine that ignores trailing blanks on its *variable*
+ types says so by not declaring the flag at all (see `RedshiftEngineSpec`).
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ # Ahead of the generic-type question, which a padded type can lose: the
+ # specs map ``CHARACTER`` onto no generic type at all on some engines, and
+ # a fixed-width character type is a string whether or not Superset can say
+ # so from the name.
+ if _is_padded_character_type(column):
+ return False
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_unicode_escaped_identifier(transform: str | None) -> bool:
+ """Whether the transform names something through a ``U&"..."`` escape.
+
+ See `UNICODE_ESCAPED_IDENTIFIER_RE`. Answered on raw text for the same
+ reason as the comment above: the parse reports a name the engine does not
+ use, which is exactly what makes the denylist blind to it.
+ """
+ return (
+ bool(transform)
+ and UNICODE_ESCAPED_IDENTIFIER_RE.search(transform or "") is not None
+ )
+
+
+#: Sequence pseudo-columns, which advance a sequence when they are *read*.
+#:
+#: ``orders_seq.NEXTVAL`` parses as a qualified column reference, not a
+#: function call, so neither `SQLStatement.is_mutating` -- which walks function
+#: names -- nor the function denylist can see it. The probe would then run
+#: ``SELECT orders_seq.NEXTVAL + 1 FROM DUAL`` and advance the sequence, again
+#: on every cache expiry, for a dataset editor holding neither SQL Lab nor a
+#: DML grant. Reading one is a write however the parser classifies it.
+#:
+#: The function spelling (``nextval('s')`` on PostgreSQL) is a different shape
+#: and is caught as a function; this is only about the suffix form.
+SEQUENCE_PSEUDO_COLUMNS = frozenset({"nextval", "currval"})
+
+#: The same thing written as a call.
+#:
+#: Only the suffix form parses as a column; `nextval('s')` on PostgreSQL and
+#: DuckDB, `NEXTVAL(s)`/`SETVAL(s, 1)` on MySQL and MariaDB, and SQL Server's
+#: `NEXT VALUE FOR s` all parse as functions. `SQLStatement.is_mutating` walks
+#: function names on PostgreSQL alone -- deliberately, since the same names are
+#: read-only elsewhere -- so every other engine let these through.
+#:
+#: Matched on the name whatever the engine, because advancing a sequence is a
+#: write wherever it happens and a transform has no reason to call one.
+SEQUENCE_FUNCTIONS = frozenset(
+ {"nextval", "setval", "next_value_for", "nextvalfor", "prevval", "lastval"}
+)
+
+
+def references_sequence(statement: SQLStatement) -> bool:
+ """Whether the statement reads or advances a sequence.
+
+ Both spellings: the pseudo-column suffix, which parses as a column (see
+ `SEQUENCE_PSEUDO_COLUMNS`), and the call, which parses as a function (see
+ `SEQUENCE_FUNCTIONS`).
+
+ Answered on the parse rather than on raw text, because position is what
+ makes it the construct: a column or alias merely *called* ``nextval`` is
+ an ordinary column, and a string literal holding the word is text.
+ """
+ return bool(
+ statement.get_column_names() & SEQUENCE_PSEUDO_COLUMNS
+ or statement.get_disallowed_functions(set(SEQUENCE_FUNCTIONS))
+ )
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """
+ Whether the transform contains a balanced Jinja block.
+
+ A block is an opening delimiter followed, anywhere later, by its closing
+ one -- the same thing ``{{.*?}}`` and its two siblings match under
+ ``re.DOTALL``. Scanned with `str.find` rather than that pattern, because a
+ lazy match retried from every opening delimiter is quadratic in a run of
+ them, and this runs on stored transforms with no length bound of its own:
+ `is_transform_active` reads whatever the column holds. The earliest opening
+ delimiter is the only one worth trying, since any closing delimiter after a
+ later one is also after it.
+ """
+ if not transform:
+ return False
+ for opening, closing in JINJA_BLOCK_DELIMITERS:
+ start = transform.find(opening)
+ if start != -1 and transform.find(closing, start + len(opening)) != -1:
+ return True
+ return False
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error( # noqa: C901
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ And it must be a *read*. Shape is a separate question from effect: a bare
+ scalar expression can still write, so `SQLStatement.is_mutating` is asked
+ too -- the same question SQL Lab and the chart executor ask before letting
+ SQL run. See the gate itself for what that reaches and what it does not.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ # Also ahead of the parse, and for a stronger reason than cost: every gate
+ # below reasons about the parse tree, and this is the one construct that
+ # makes the parse tree describe a different statement from the one the
+ # engine runs. Checked here as well as in `validate_transform` because this
+ # is the door a row written by an earlier release still comes through.
+ if contains_executable_comment(transform):
+ return str(
+ _(
+ "A partition value transform cannot contain a MySQL "
+ "executable comment, which the database executes and every "
+ "validator reads as a comment."
+ )
+ )
+
+ if contains_unicode_escaped_identifier(transform):
+ return str(
+ _(
+ "A partition value transform cannot name anything through a "
+ 'U&"..." escape sequence, which the database decodes and '
+ "every validator reads literally."
+ )
+ )
+
+ # Same door, same reason: the name the denylist below would match is not
+ # the name the engine resolves. See `UNICODE_ESCAPED_IDENTIFIER_RE`.
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The read-only gate, which nothing above implies. The shape gates ask what
+ # the transform *selects*; this asks what evaluating it *does*, and a bare
+ # scalar expression can still write. `nextval(:value)` on PostgreSQL
+ # advances a sequence: one function call, no clause, no sub-query, and not
+ # in the default `DISALLOWED_SQL_FUNCTIONS` either -- so every gate above
+ # passes it and the probe then runs it. `setval` is the same shape, and
+ # `exp.Execute` and the opaque-`exp.Command` forms arrive the same way.
+ #
+ # The large-object writers (`lo_export`, `lowrite`, `lo_from_bytea`, ...)
+ # are caught here too, and the shipped denylist happens to name them as
+ # well -- but that is config an operator can replace, while this is not.
+ #
+ # `is_mutating` is the same question SQL Lab, `get_virtual_table_metadata`
+ # and the chart executor ask before letting SQL run, so a transform is held
+ # to the bar the rest of Superset already sets rather than to one invented
+ # here. Unconditional rather than gated on `Database.allow_dml`: a transform
+ # is a scalar function of `:value` by definition, so there is no legitimate
+ # mutating one, and the probe runs on a cache schedule nobody chose -- a
+ # write would repeat every time the entry expired.
+ #
+ # It bears saying what this does not reach. A user-defined function whose
+ # body writes is a plain call no parser can tell from `lower(:value)`, and
+ # `is_mutating`'s function-name walk is PostgreSQL-only by design, since the
+ # same names are read-only elsewhere. Neither residual is specific to this
+ # feature -- a dataset editor can already have the engine evaluate an
+ # arbitrary expression through a calculated column or a virtual dataset's
+ # SQL -- and closing them means authorizing the preview against the
+ # database, not parsing harder.
+ if statement.is_mutating():
+ return str(
+ _(
+ "A partition value transform cannot change data. It is "
+ "evaluated against the database to check that it mirrors, so "
+ "it has to be a read."
+ )
+ )
+
+ # Not reached by the walk above, which is why it is its own gate: a
+ # sequence pseudo-column is a *column* to the parser and a write to the
+ # engine. See `SEQUENCE_PSEUDO_COLUMNS`.
+ if references_sequence(statement):
+ return str(
+ _(
+ "A partition value transform cannot read a sequence. "
+ "NEXTVAL advances the sequence every time it is evaluated, "
+ "and the transform is evaluated on a cache schedule."
+ )
+ )
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the probe
+ uninspected -- string elements are escaped by the dialect's own literal
+ processor. `probe_sql_is_evaluable` then re-reads the finished query, which
+ is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def _placeholder_is_bindable(transform: str) -> bool:
+ """
+ Whether SQLAlchemy's ``text()`` can see ``:value`` as a bound parameter.
+
+ `VALUE_PLACEHOLDER_RE` is ``:value\b``, which matches the placeholder in a
+ Postgres cast such as ``:value::bigint``. SQLAlchemy's own bind scan is
+ ``(?<![:\\w$]):([\\w$]+)(?![:\\w$])`` -- note the trailing exclusion -- so a
+ following colon stops it: ``text(":value::bigint")`` reports a parameter
+ named ``valu``, and ``.bindparams(bindparam("value"))`` then raises
+ ``ArgumentError``.
+
+ `_probe` swallows that, so the only symptom was a perfectly valid transform
+ whose mapping silently never pruned, and a preview reporting an engine
+ failure for SQL that was never sent. Every write-side gate passes the
+ transform: it parses, it is a bare expression, and the placeholder *is* in
+ an executable position.
+
+ Answered by attempting the bind itself rather than by pattern-matching
+ ``::`` or reading ``text()``'s private parameter map, so this cannot
+ disagree with what `build_probe_sql` is about to do -- on any dialect, or on
+ a SQLAlchemy whose scan changes.
+ """
+ try:
+ sa.text(transform).bindparams(sa.bindparam("value", value=None))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return False
+ return True
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ bindable = _placeholder_is_bindable(transform)
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ elif bindable:
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ rendered = _compile_literal(clause, dialect)
Review Comment:
The filter value is rendered into the probe as an inline literal by the dialect's own literal processor, which for the Hive/Spark dialect doubles apostrophes but leaves backslashes alone, while Spark reads `\'` as an escaped quote. A value such as `x\' || reflect("java.lang.System","getenv","SOME_VAR") AS v0 --` therefore closes the literal, supplies the expected `v0` alias, and comments out the rest, so the compiled probe still passes the single-projection/alias check in `probe_sql_is_evaluable` and runs as an expression of the requester's choosing, with its result echoed back in the mirrored predicate. A Gamma user with chart-data access but no SQL Lab execution could reach that through an equality filter on a mapped column of a Spark dataset. Should this escape backslashes for dialects whose string literals honor them (or decline mirroring when the value contains a backslash) rather than relying on apostrophe doubling?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4168251296
##########
superset/migrations/versions/2026-09-23_00-01_a7f3c2e91d84_add_partition_filter_mapping.py:
##########
@@ -0,0 +1,101 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""add partition filter mapping
+
+Adds the four columns behind the ``PARTITION_FILTER_MAPPING`` feature:
+
+- ``tables.partition_column`` -- the physical column the engine partitions on
+- ``tables.partition_mapped_column`` -- explicit override for the column whose
+ filters are mirrored; NULL means "follow ``main_dttm_col``"
+- ``table_columns.partition_value_transform`` -- the ``:value`` expression
+- ``table_columns.partition_transform_is_monotonic`` -- gates range operators
+
+The Continuum shadow tables get the same columns so dataset version history and
+restore keep working.
+
+Revision ID: a7f3c2e91d84
+Revises: 95d8a99c822e
+Create Date: 2026-08-31 22:30:00.000000
+
+"""
+
+import sqlalchemy as sa
+
+from superset.migrations.shared.utils import add_columns, drop_columns
+
+# revision identifiers, used by Alembic.
+revision = "a7f3c2e91d84"
+down_revision = "95d8a99c822e"
Review Comment:
Master's #43232 added `884a2115ebd3` on the same parent, so the merge has two Alembic heads and `superset db upgrade` fails on every DB leg. Re-parent onto it (and the `Revises:` line at :31).
```suggestion
down_revision = "884a2115ebd3"
```
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/PartitionColumnFields.tsx:
##########
@@ -0,0 +1,274 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { useMemo } from 'react';
+import { t } from '@apache-superset/core/translation';
+import { css, useTheme } from '@apache-superset/core/theme';
+import { Alert } from '@apache-superset/core/components';
+import {
+ Button,
+ Flex,
+ Icons,
+ InfoTooltip,
+ Label,
+ Select,
+ Tooltip,
+ Typography,
+} from '@superset-ui/core/components';
+import {
+ mappedColumnIsImplicit,
+ mappingIsActive,
+ partitionMappingErrors,
+ resolveMappedColumn,
+ suggestedMappedColumn,
+} from './utils';
+import type {
+ PartitionMappingColumn,
+ PartitionMappingDatasource,
+ PartitionMappingIssue,
+} from './types';
+
+interface PartitionColumnFieldsProps {
+ datasource: PartitionMappingDatasource;
+ columns: PartitionMappingColumn[];
+ onPartitionColumnChange: (columnName: string | null) => void;
+ /** Open the given column's row expand in the Columns table. */
+ onNavigateToColumn: (columnName: string) => void;
+}
+
+/**
+ * "Partition column" and the computed "Maps to partition" (wireframes 1a, 1g).
+ *
+ * "Maps to partition" is deliberately read-only. It reflects
+ * `partition_mapped_column ?? main_dttm_col`, and a peer dropdown would let it
+ * drift from the default datetime column silently. The only way to override it
+ * is from the target column's own row, where a transform has to be supplied
+ * alongside.
+ */
+export default function PartitionColumnFields({
+ datasource,
+ columns,
+ onPartitionColumnChange,
+ onNavigateToColumn,
+}: PartitionColumnFieldsProps) {
+ const theme = useTheme();
+
+ const options = useMemo(
+ () =>
+ columns.map(column => ({
+ value: column.column_name,
+ label: column.column_name,
+ customLabel: (
+ <Flex align="center" gap={theme.sizeUnit}>
+ <span>{column.column_name}</span>
+ {column.type && <Label>{column.type}</Label>}
+ </Flex>
+ ),
+ })),
+ [columns, theme.sizeUnit],
+ );
+
+ const mappedColumn = resolveMappedColumn(datasource);
+ const isImplicit = mappedColumnIsImplicit(datasource);
+ const isActive = mappingIsActive(datasource, columns);
+ const { partition_column: partitionColumn } = datasource;
+
+ // `field` is what the issues carry it for: a message about the partition
+ // column belongs under the partition column, not only in the Save button's
+ // tooltip, where an owner has to guess which of the two selects is at fault.
+ const issues = useMemo(
+ () => partitionMappingErrors(datasource, columns),
+ [datasource, columns],
+ );
+ const issueFor = (field: PartitionMappingIssue['field']) =>
+ issues.find(issue => issue.field === field)?.message;
+
+ // "Map a different column instead" normally opens the currently-mapped
+ // column's row, which is where the picker lives. When the mapped column *is*
+ // the partition column -- the self-mapping the backend rejects, and reachable
+ // in one click because the picker offers every column -- that row renders no
+ // mapping section at all, so the one guided way out of the broken state led
+ // nowhere. Offer a column that is not the partition column instead.
+ const differentColumnTarget =
+ mappedColumn && mappedColumn !== partitionColumn
+ ? mappedColumn
+ : (suggestedMappedColumn(columns, partitionColumn) ?? mappedColumn);
+
+ return (
+ <Flex vertical gap={theme.sizeUnit} data-test="partition-column-fields">
+ <Flex align="center" gap={theme.sizeUnit}>
+ <Typography.Text>{t('Partition column')}</Typography.Text>
+ <InfoTooltip
+ tooltip={t(
+ 'The physical column the engine partitions on. Filters on the mapped column are mirrored onto it so the engine can prune partitions.',
+ )}
+ />
+ </Flex>
+ <Select
+ ariaLabel={t('Partition column')}
+ options={options}
+ value={partitionColumn ?? undefined}
+ onChange={value => onPartitionColumnChange((value as string) ?? null)}
+ onClear={() => onPartitionColumnChange(null)}
+ placeholder={t('None')}
+ allowClear
+ data-test="partition-column-select"
+ />
+ {issueFor('partition_column') && (
+ <Typography.Text type="danger" data-test="partition-column-error">
+ {issueFor('partition_column')}
+ </Typography.Text>
+ )}
+ <Typography.Text type="secondary">
+ {t(
+ "Column used for partition pruning on this table. Selecting one hides it from Explore's dimension and filter pickers by default.",
+ )}
+ </Typography.Text>
+
+ {partitionColumn && (
+ <Flex vertical gap={theme.sizeUnit} data-test="maps-to-partition">
+ <Flex align="center" gap={theme.sizeUnit}>
+ <Typography.Text type="secondary">
+ {t('Maps to partition')}
+ </Typography.Text>
+ <InfoTooltip
+ tooltip={t(
+ 'The column whose filters are mirrored. It follows the default datetime column unless a different column holds the mapping.',
+ )}
+ />
+ </Flex>
+
+ {mappedColumn ? (
+ <>
+ <Flex align="center" gap={theme.sizeUnit}>
+ <Label>{mappedColumn}</Label>
+ {isImplicit && (
+ <>
+ <Typography.Text type="secondary">
+ {t('Default datetime column')}
+ </Typography.Text>
+ <Tooltip
+ title={t(
+ 'Set from the default datetime column above, so re-pointing that column moves the mapping with it.',
+ )}
+ >
+ <Icons.LockOutlined
+ iconSize="s"
+ iconColor={theme.colorTextTertiary}
+ />
+ </Tooltip>
+ </>
+ )}
+ </Flex>
+ {issueFor('partition_mapped_column') && (
+ <Typography.Text
+ type="danger"
+ data-test="partition-mapped-column-error"
+ >
+ {issueFor('partition_mapped_column')}
+ </Typography.Text>
+ )}
+ <Typography.Text type="secondary">
+ {t(
+ 'Filters on this column are mirrored onto the partition column.',
+ )}{' '}
+ <Button
+ buttonStyle="link"
+ onClick={() => onNavigateToColumn(differentColumnTarget)}
Review Comment:
`tsc` fails here (TS2345): `differentColumnTarget` is `string | null`. `mappedColumn` is narrowed in this branch, so the fallback is type-only.
```suggestion
onClick={() =>
onNavigateToColumn(differentColumnTarget ?? mappedColumn)
}
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4223950807
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2723 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+#: Returned by `ExploreMixin.mirror_probe_request` for a filter no mirror can
+#: stand in for: one the engine compares more coarsely than the value carries, a
+#: value it cannot render as a literal, or an ``IN`` list with a member of
+#: either kind. A sentinel rather than `None`, because `None` is a filter value
+#: in its own right.
+#:
+#: Lives here rather than beside that method so the preview can read it too:
+#: `superset.models.helpers` imports this module, so the sentinel can only cross
+#: the boundary in this direction. Both callers have to recognise the same
+#: object -- a preview that answered "valid" for a request the chart path
+#: declines is the drift this is here to prevent.
+UNMIRRORABLE = object()
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error( # noqa: C901
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ And it must be a *read*. Shape is a separate question from effect: a bare
+ scalar expression can still write, so `SQLStatement.is_mutating` is asked
+ too -- the same question SQL Lab and the chart executor ask before letting
+ SQL run. See the gate itself for what that reaches and what it does not.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ # Also ahead of the parse, and for a stronger reason than cost: every gate
+ # below reasons about the parse tree, and this is the one construct that
+ # makes the parse tree describe a different statement from the one the
+ # engine runs. Checked here as well as in `validate_transform` because this
+ # is the door a row written by an earlier release still comes through.
+ if contains_executable_comment(transform):
+ return str(
+ _(
+ "A partition value transform cannot contain a MySQL "
+ "executable comment, which the database executes and every "
+ "validator reads as a comment."
+ )
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The read-only gate, which nothing above implies. The shape gates ask what
+ # the transform *selects*; this asks what evaluating it *does*, and a bare
+ # scalar expression can still write. `nextval(:value)` on PostgreSQL
+ # advances a sequence: one function call, no clause, no sub-query, and not
+ # in the default `DISALLOWED_SQL_FUNCTIONS` either -- so every gate above
+ # passes it and the probe then runs it. `setval` is the same shape, and
+ # `exp.Execute` and the opaque-`exp.Command` forms arrive the same way.
+ #
+ # The large-object writers (`lo_export`, `lowrite`, `lo_from_bytea`, ...)
+ # are caught here too, and the shipped denylist happens to name them as
+ # well -- but that is config an operator can replace, while this is not.
+ #
+ # `is_mutating` is the same question SQL Lab, `get_virtual_table_metadata`
+ # and the chart executor ask before letting SQL run, so a transform is held
+ # to the bar the rest of Superset already sets rather than to one invented
+ # here. Unconditional rather than gated on `Database.allow_dml`: a transform
+ # is a scalar function of `:value` by definition, so there is no legitimate
+ # mutating one, and the probe runs on a cache schedule nobody chose -- a
+ # write would repeat every time the entry expired.
+ #
+ # It bears saying what this does not reach. A user-defined function whose
+ # body writes is a plain call no parser can tell from `lower(:value)`, and
+ # `is_mutating`'s function-name walk is PostgreSQL-only by design, since the
+ # same names are read-only elsewhere. Neither residual is specific to this
+ # feature -- a dataset editor can already have the engine evaluate an
+ # arbitrary expression through a calculated column or a virtual dataset's
+ # SQL -- and closing them means authorizing the preview against the
+ # database, not parsing harder.
+ if statement.is_mutating():
+ return str(
+ _(
+ "A partition value transform cannot change data. It is "
+ "evaluated against the database to check that it mirrors, so "
+ "it has to be a read."
+ )
+ )
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the probe
+ uninspected -- string elements are escaped by the dialect's own literal
+ processor. `probe_sql_is_evaluable` then re-reads the finished query, which
+ is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def _placeholder_is_bindable(transform: str) -> bool:
+ """
+ Whether SQLAlchemy's ``text()`` can see ``:value`` as a bound parameter.
+
+ `VALUE_PLACEHOLDER_RE` is ``:value\b``, which matches the placeholder in a
+ Postgres cast such as ``:value::bigint``. SQLAlchemy's own bind scan is
+ ``(?<![:\\w$]):([\\w$]+)(?![:\\w$])`` -- note the trailing exclusion -- so a
+ following colon stops it: ``text(":value::bigint")`` reports a parameter
+ named ``valu``, and ``.bindparams(bindparam("value"))`` then raises
+ ``ArgumentError``.
+
+ `_probe` swallows that, so the only symptom was a perfectly valid transform
+ whose mapping silently never pruned, and a preview reporting an engine
+ failure for SQL that was never sent. Every write-side gate passes the
+ transform: it parses, it is a bare expression, and the placeholder *is* in
+ an executable position.
+
+ Answered by attempting the bind itself rather than by pattern-matching
+ ``::`` or reading ``text()``'s private parameter map, so this cannot
+ disagree with what `build_probe_sql` is about to do -- on any dialect, or on
+ a SQLAlchemy whose scan changes.
+ """
+ try:
+ sa.text(transform).bindparams(sa.bindparam("value", value=None))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return False
+ return True
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ bindable = _placeholder_is_bindable(transform)
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ elif bindable:
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ rendered = _compile_literal(clause, dialect)
+ else:
+ # `text()` cannot see the placeholder (see
+ # `_placeholder_is_bindable`), so the value is rendered by the
+ # dialect's own literal processor first and substituted as SQL
+ # text. The same two steps in the other order: binding exists to
+ # get the value through that processor, and `_compile_literal`
+ # inlines the result either way, so this is the same string by a
+ # different route -- not a loosening of the "never interpolate a
+ # raw value" rule. `parse_skeleton` substitutes literally, so a
+ # rendered literal containing a backslash is safe here.
+ rendered = parse_skeleton(
+ transform, _compile_literal(sa.literal(value), dialect)
+ )
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Four things have to hold, and all four are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ # Before the parse, because this gate's whole contract is that what the
+ # parse describes is what the engine will run, and an executable comment is
+ # precisely the text where that stops being true. The transform is already
+ # refused for carrying one; this covers the compiled statement, so no later
+ # change to how values are rendered can reintroduce it behind the gates
+ # below.
+ if contains_executable_comment(sql):
+ return False
+
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if not isinstance(statement, SQLStatement):
+ # A dialect whose statements this gate cannot take apart -- KQL -- gets
+ # no probe rather than an unchecked one. It never had one: the clause
+ # inspection below is implemented for SQL statements only, and the
+ # alternative to declining here is an `AttributeError` that `_probe`
+ # swallows into the same outcome, less legibly.
+ return False
+ if statement.has_subquery():
+ return False
+ if statement.get_clause_names() - {"from"}:
+ return False
+ if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+ """
+ The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+ Parsed rather than string-compared so that the comparison in
+ `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+ not parse answers ``None``, which no statement carrying a FROM can match --
+ the probe then declines, which is the right way for an unreadable engine
+ constant to fail.
+ """
+ if not from_suffix.strip():
+ return None
+ try:
+ return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+ except SupersetParseError:
+ return None
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=values is not None and not any(value is None for value in values),
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ from_suffix = database.db_engine_spec.select_without_from_suffix
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ from_suffix,
+ )
+ if not probe_sql_is_evaluable(
+ sql, database.backend, len(distinct), from_suffix
+ ):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _execution_identity(database: Database) -> str | None:
+ """
+ Who the warehouse will run the probe as, when that can vary by caller.
+
+ `_probe_cache_key` keys on the `Database` record, which is the *connection*
+ -- not the identity it is opened under. Two hooks make that identity a
+ function of the Superset user instead:
+
+ * ``impersonate_user`` on the database, which hands the effective username
+ to `db_engine_spec.impersonate_user`;
+ * ``DB_CONNECTION_MUTATOR``, which receives the effective username and may
+ return an entirely different account's URL.
+
+ Under either one, a cached probe result computed under user A's grants was
+ served to user B, and the preview echoed it back in ``emitted_predicate``.
+ A transform wrapping a read-capable function the denylist does not name --
+ Oracle's ``DBMS_XMLGEN.GETXML`` is the worked example -- then leaks across
+ users who were never allowed the same rows.
+
+ Returns ``None`` when neither hook is configured, which is the common case
+ and deliberately leaves the key as it was: the cache exists to keep a
+ synchronous warehouse round trip off the chart-query path, and keying every
+ deployment on the username would cost every deployment the hit rate to fix
+ the two that need it.
+
+ The *Superset* username rather than the resolved warehouse account, because
+ it is the input both hooks branch on, and reading it needs no URL parse and
+ puts no credential in the key.
+ """
+ if not (database.impersonate_user or app.config["DB_CONNECTION_MUTATOR"]):
+ return None
+ return get_username()
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _mirror_verdict_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str:
+ """
+ `_probe_cache_key` without the values.
+
+ Whether a transform can be evaluated at all is a property of the transform
+ and the connection, not of the filter that happened to be probing it, so
+ one chart's answer settles the question for the next one.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ # Whether a transform *can* be evaluated is a property of the
+ # transform and the connection -- but under impersonation the
+ # connection is per-user, and a function one account may call can
+ # be refused to another. See `_execution_identity`.
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_verdict:{digest}"
+
+
+def record_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ *,
+ mirrors: bool,
+) -> None:
+ """
+ Remember whether this transform produced a mirror, for the UI to read.
+
+ Advisory only. Nothing in the query path consults it: a probe that failed
+ once is retried on the next chart exactly as it is today, because declining
+ to prune for a whole cache timeout over one transient engine blip is the
+ trade `evaluate_transform` deliberately refuses -- see the comment where it
+ declines to cache a failure.
+
+ What this is for is the *claim*. `is_transform_active` parses the transform
+ and no more, so a transform the database rejects -- a misspelled function
+ is the common case -- is "active", and the editor's banner and Explore's
+ pruning glyph promise a speed-up that never happens. A promise is exactly
+ the thing that may be withheld on one bad answer and restored on a good
+ one, which is why this is a separate entry from the probe's own results
+ rather than a relaxation of that rule.
+
+ Written by `_run_probe`, so the preview endpoint -- which shares the
+ evaluator -- settles the question before the owner has even saved.
+ """
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(
+ _mirror_verdict_cache_key(database, catalog, schema, transform),
+ mirrors,
+ timeout=timeout,
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform verdict", exc_info=True)
+
+
+def known_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> bool | None:
+ """
+ The last verdict `record_mirror_verdict` stored, or `None` if there is none.
+
+ `None` is the honest answer on a cold cache and is deliberately not `False`:
+ reporting a working mapping as broken until something probes it would
+ trade one wrong claim for another. The alternative -- probing from the
+ read side -- would put a warehouse round trip on every Explore and
+ dashboard load, and a failing transform is not cached at all, so it would
+ be a round trip every single time.
+ """
+ try:
+ verdict = cache_manager.cache.get(
+ _mirror_verdict_cache_key(database, catalog, schema, transform)
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return verdict if isinstance(verdict, bool) else None
+
+
+def _compile_literal(element: Any, dialect: Dialect | None) -> str:
+ """
+ Compile with inline literals, undoing the paramstyle's percent doubling.
+
+ Both ``TextClause`` and literal compilation run the dialect's
+ ``post_process_text``, which doubles every ``%`` whenever the identifier
+ preparer asks it to -- true for MySQL and Postgres and for every spec
+ inheriting their paramstyle. That doubling exists so a later DBAPI
+ parameter-interpolation pass can undo it, and the probe has no such pass:
+ it executes with no bound parameters at all. So a transform of
+ ``date_format(:value, '%Y%m%d')`` reaches the warehouse asking for the
+ literal string ``%%Y%%m%%d``, the probe returns that instead of a date, and
+ the mirrored predicate drops every row the filter keeps.
+
+ The same normalization ``Database.compile_sqla_query`` applies for the same
+ reason. ``_double_percents`` is private and not guaranteed on a third-party
+ dialect, hence the ``getattr`` default.
+ """
+ compiled = str(
+ element.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
+ )
+ if dialect is not None and getattr(
+ dialect.identifier_preparer, "_double_percents", False
+ ):
+ compiled = compiled.replace("%%", "%")
+ return compiled
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be *asked* to stand in for itself, and the transform
+ cannot carry Jinja or call a non-deterministic function. Tier 2
+ (``blocking=False``) is everything that merely leaves the mapping inactive
+ -- including a self-mapping nobody asked for, where the partition column
+ merely happens to be the default datetime column.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column == partition_column:
+ # Asked for explicitly, so report it as the mistake it is.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+ elif not partition_mapped_column and main_dttm_col == partition_column:
+ # Resolved onto itself only because the default datetime column happens
+ # to be the partition column -- a state metadata sync could produce
+ # without anyone asking for it. The mapping is inert either way, since
+ # `resolve_partition_mapping` bails out on it, so this reports and lets
+ # the write through: blocking here means a dataset already in the state
+ # can never be saved again, not even to change its description, and
+ # there is no field whose edit would clear the error first.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "%(name)s is both the partition column and the default "
+ "datetime column, so the mapping points at itself and "
+ "stays inactive. Set a mapped column override, or change "
+ "the default datetime column.",
+ name=partition_column,
+ ),
+ blocking=False,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def drop_unmapped_value_transforms(
+ columns: list[dict[str, Any]] | None,
+ *,
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ names_by_id: dict[int, str] | None = None,
+) -> list[str]:
+ """
+ Null the value transform on every *incoming* column the mapping cannot mirror.
+
+ The write-side twin of `DatasetDAO.clear_unmapped_partition_transforms`,
+ which answers for the model. A mapping has exactly one mirrored column, so
+ at most one column may carry a transform. One parked on any other column is
+ invisible -- no row but the mapped one renders a transform -- and yet it is
+ stored, and it goes live the moment the mapped column resolves back to it.
+ Clearing an override is enough to do that: a null
+ ``partition_mapped_column`` means "follow ``main_dttm_col``".
+
+ Ungated on the feature flag, unlike its model-level twin, and the difference
+ is what each one discards. That one drops stored configuration, so with the
+ flag off it would be pure loss. This one drops only a value the request in
+ hand is asking to write where the invariant says none may live -- and the
+ flag-off window is precisely when such a value gets parked for later, since
+ the editor hides these fields and the model-level pass declines to run.
+
+ Three writers reach the columns with no effective model-level pass between
+ them, which is why this exists at all: the deprecated
+ ``POST /datasource/save/``, which writes straight through
+ `update_from_object` and so never had one; and a
+ ``PUT /api/v1/dataset/<pk>`` or a dataset import made while the flag is
+ off, where the pass runs on both sides of the write and declines on both.
+
+ Mutates the payload in place, because every caller hands its own request
+ dict straight on to the code that writes it. Returns the names it cleared,
+ so the caller can say so in a log: this is a silent correction to a payload
+ whose author may have meant it.
+
+ A column whose payload mentions neither field is left alone. "Incoming" is
+ the whole scope -- a transform already in storage on a column this request
+ says nothing about is the model-level pass's business, under its own flag.
+
+ The mapped column resolves the way every other reader resolves it,
+ ``partition_mapped_column or main_dttm_col``, and resolves to nothing
+ without a partition column -- in which case no column may hold a transform
+ either.
+
+ :param names_by_id: how to read the name off a payload entry that gives
+ only an ``id``. `DatasetDAO._upsert_columns` identifies an existing
+ column by its primary key and lets ``column_name`` be omitted -- the
+ column keeps the name it has -- so without this an ordinary PUT looked
+ like a payload of nameless columns, none of which matched the mapped
+ one, and every transform in it was dropped. Callers whose writer keys
+ on the name instead (`update_from_object`, the importer) pass nothing.
+ An entry this cannot name is left alone rather than guessed at.
+ """
+ mapped_column = (
+ (partition_mapped_column or main_dttm_col) if partition_column else None
+ )
+ cleared: list[str] = []
+ for column in columns or []:
+ name = column.get("column_name")
+ if name is None and names_by_id is not None:
+ column_id = column.get("id")
+ if column_id is not None:
+ name = names_by_id.get(column_id)
+ if name is None or name == mapped_column:
+ continue
+ if column.get("partition_value_transform") or column.get(
+ "partition_transform_is_monotonic"
+ ):
+ column["partition_value_transform"] = None
+ column["partition_transform_is_monotonic"] = False
+ cleared.append(name)
+ return cleared
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if contains_executable_comment(transform):
+ # Blocking, and checked on raw text next to the Jinja gate because no
+ # parse reports it: sqlglot reads `/*!50000 ... */` as comment data
+ # while MySQL and MariaDB execute it, so every shape gate downstream
+ # inspects a statement the engine will not run. See
+ # `EXECUTABLE_COMMENT_RE`.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform cannot contain a MySQL executable "
+ "comment (/*! ... */ or /*M! ... */). Those are comments "
+ "to every validator and statement text to the database, "
+ "so what would run is not what was checked."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_bare_expression(transform, engine):
+ # Blocking, and deliberately placed in `validate_transform` rather than
+ # only at the probe: one issue here closes the PUT, the importer, the
+ # query-time gate through `is_transform_active`, the Explore indicator's
+ # active verdict and the preview endpoint, all of which already consult
+ # this function.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform must be a single SQL expression. It "
+ "cannot carry a FROM, WHERE, GROUP BY or any other clause, "
+ "and it cannot contain a sub-query."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not contains_value_placeholder(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform must contain the :value placeholder, "
+ "which stands for the filter value being mirrored."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not placeholder_is_executable(transform, engine):
+ # Blocking, and for the same reason the shape gate above is: this is
+ # the function the PUT, the importer, `is_transform_active`, the
+ # Explore indicator and the preview all consult, so one issue here
+ # closes every door at once. A placeholder inside a string literal is
+ # a sub-query the engine will run once a filter value closes the quote;
+ # one inside a comment silently eats the probe's own alias.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The :value placeholder must appear where the engine will "
+ "evaluate it. It cannot sit inside a string literal or a "
+ "comment."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if functions := find_non_deterministic_functions(transform, engine):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform calls %(functions)s, whose result "
+ "depends on when and where it runs. The transform is "
+ "evaluated in a separate session and the result is cached, "
+ "so the emitted predicate would freeze a snapshot of that "
+ "moment.",
+ functions=", ".join(sorted(functions)),
+ ),
+ blocking=True,
+ )
+ ]
+
+ return []
+
+
+@lru_cache(maxsize=LRU_CACHE_MAX_SIZE)
+def is_transform_active(transform: str | None, engine: str) -> bool:
+ """
+ Whether Superset will mirror filters through this transform.
+
+ `validate_transform` with the messages discarded, so the Explore indicator
+ cannot advertise a mapping the save path recorded as inactive. Anything
+ cheaper here would be a second, weaker statement of the same rule, free to
+ drift from the one the save path applies.
+
+ Blocking issues count too. Jinja and non-deterministic transforms are
+ rejected on PUT, but `CreateDatasetCommand` and import do not validate the
+ mapping, so one can still reach the database -- and it would never mirror a
+ filter either.
+
+ Memoized because `partition_filter_mapping_summary` is serialized on every
+ Explore and dashboard load and this parses the transform. The key is
+ everything the answer depends on: `validate_transform` reads no session, no
+ locale and no config beyond `SQL_MAX_PARSE_LENGTH`, which bounds the parser
+ rather than changing a verdict within that bound.
+ """
+ return not validate_transform(transform, engine)
+
+
+def preview_partition_mapping( # pylint: disable=too-many-return-statements
+ datasource: SqlaTable,
+ *,
+ mapped_column: str,
+ value_transform: str | None,
+ sample_values: list[str],
+ operator: FilterOperator = FilterOperator.EQUALS,
+ is_monotonic: bool = False,
+ partition_column: str | None = None,
+) -> dict[str, Any]:
+ """
+ Evaluate a candidate mapping and describe the predicate it would emit.
+
+ Shares the evaluator -- and therefore the probe cache -- with the query
+ path, so preview and runtime cannot drift and a previewed transform warms
+ the chart path for free. The predicate itself comes from
+ `build_mirrored_predicates`, the same builder the query path uses, so
+ operator shapes cannot drift either: what the panel shows is what a chart
+ would emit.
+
+ Validation runs first and the engine second: a half-typed transform is by
+ definition unparseable, so most of what a text input produces costs zero
+ queries.
+
+ Every part of the mapping is taken from the request rather than the stored
+ dataset. The editor previews while the owner is still editing -- a mapping
+ that has to be saved before it can be checked is not a preview.
+ """
+ partition_column = partition_column or datasource.partition_column
+ if not partition_column:
+ return {
+ "valid": False,
+ "reason": "unconfigured",
+ "error": _("No partition column is set."),
+ }
+
+ columns_by_name = {str(column.column_name): column for column in datasource.columns}
+ if mapped_column not in columns_by_name:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _("%(name)s is not a column on this dataset.", name=mapped_column),
+ }
+
+ # The bail-out `resolve_partition_mapping` makes at query time, and that
+ # `partition_filter_mapping_summary` repeats for the Explore indicator.
+ # Without it here, preview reports a valid emitted predicate for a mapping
+ # no chart will ever mirror -- the one answer a preview panel must not give.
+ if has_active_advanced_data_type(columns_by_name[mapped_column]):
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _(
+ "%(name)s has an advanced data type, so its filters are "
+ "translated into their own predicate shape and cannot be "
+ "mirrored onto the partition column.",
+ name=mapped_column,
+ ),
+ }
+
+ engine = datasource.database.backend
+ for issue in validate_partition_mapping(
+ column_names=set(columns_by_name),
+ partition_column=str(partition_column),
+ partition_mapped_column=mapped_column,
+ main_dttm_col=datasource.main_dttm_col,
+ transform=value_transform,
+ engine=engine,
+ ):
+ return {
+ "valid": False,
+ # The parse failure is the one an owner sees constantly, and it is
+ # the only one the mockup gives its own headline to.
+ "reason": (
+ "parse"
+ if issue.field == "partition_value_transform"
+ and not is_parseable(value_transform, engine)
+ else "validation"
+ ),
+ "error": str(issue.message),
+ }
+
+ # The policy every other stored expression goes through. The save path
+ # applies it in `UpdateDatasetCommand._validate_partition_mapping`, but
+ # preview evaluates a candidate transform that has not been saved, so
+ # without this the gate had a door around it. See
+ # `stored_expression_error` for what is being kept out and why.
+ if reason := stored_expression_error(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ cast(str, value_transform),
+ ):
+ return {"valid": False, "reason": "validation", "error": reason}
+
+ mapping = PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=mapped_column,
+ value_transform=cast(str, value_transform),
+ is_monotonic=is_monotonic,
+ equality_is_safe=equality_mirrors_safely(
+ columns_by_name[mapped_column], datasource.database.db_engine_spec
+ ),
+ )
+ sample_input = _render_sample_input(
+ datasource, mapped_column, operator, sample_values
+ )
+
+ if operator not in PREVIEWABLE_OPERATORS:
+ # Checked before `mirrors`, which lets `TEMPORAL_RANGE` through when the
+ # transform is declared monotonic -- and the single sample value would
+ # then reach `handle_comparison_filter`, which has no case for a range
+ # and raises. The request schema rejects it too; this keeps the function
+ # honest for any other caller.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is mirrored as a pair of bounds, which "
+ "a preview of a single value cannot describe.",
+ operator=operator.value,
+ ),
+ }
+
+ if not mapping.mirrors(operator):
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is only mirrored when the transform "
+ "preserves ordering, which this one is not declared to do.",
+ operator=operator.value,
+ ),
+ }
+
+ return _preview_probe(
+ datasource,
+ mapping,
+ columns_by_name[mapped_column],
+ operator,
+ sample_values,
+ sample_input,
+ )
+
+
+def _preview_probe(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ mapped_col: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+ sample_input: str,
+) -> dict[str, Any]:
+ """
+ The half of a preview that needs the warehouse.
+
+ Split out from `preview_partition_mapping` so that the gates which answer
+ from the stored mapping alone stay readable as the single run of guard
+ clauses they are. Everything here has either run a query or decided not to.
+ """
+ value = datasource.mirror_probe_request(
+ operator,
+ _probe_input(datasource, mapped_col, operator, sample_values),
+ mapped_col,
+ )
+ if value is UNMIRRORABLE:
+ # The same step the chart path applies, so the preview cannot promise a
+ # mirror the query declines. Its own reason: the transform is fine and
+ # the engine evaluates it, the filter just carries more of the value
+ # than the engine compares on this column -- which is the column's type
+ # talking, not a broken expression.
+ return {
+ "valid": False,
+ "reason": "resolution",
+ "sample_input": sample_input,
+ "error": _(
+ "This engine compares less of a %(operator)s value on "
+ "%(column)s than the filter carries, so there is no mirror a "
+ "predicate on the partition column could stand in for. Map a "
+ "column the engine compares in full to mirror this operator.",
+ operator=operator.value,
+ column=mapped_col.column_name,
+ ),
+ }
+ errors: list[str] = []
+ type_errors: list[str] = []
+ predicates = build_mirrored_predicates(
+ datasource,
+ mapping,
+ [(operator, value)],
+ errors=errors,
+ type_errors=type_errors,
+ )
+ if type_errors:
+ # Its own reason, because "the database would not evaluate this" and
+ # "it evaluated and answered with the wrong kind of thing" are
+ # different problems with different fixes, and the owner is the only
+ # one who can tell which transform they meant to write.
+ return {
+ "valid": False,
+ "reason": "type",
+ "sample_input": sample_input,
+ "error": type_errors[0],
+ }
+ if not predicates:
+ return {
+ "valid": False,
+ "reason": "engine",
+ "sample_input": sample_input,
+ "error": (
+ _(
+ "The transform could not be evaluated against the "
+ "database: %(reason)s",
+ reason=errors[0],
+ )
+ if errors
+ else _("The transform could not be evaluated against the database.")
+ ),
+ }
+
+ return {
+ "valid": True,
+ "sample_input": sample_input,
+ "emitted_predicate": _render_predicate(datasource, predicates[0]),
+ }
+
+
+def _probe_input(
+ datasource: SqlaTable,
+ column: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+) -> Any:
+ """
+ The sample values as the query path would bind them.
+
+ The request carries samples as strings, and the probe is keyed on exactly
+ what it is handed, so passing them through raw asks the engine a different
+ question from the one a chart asks. A sample of ``2025`` on a numeric
+ column has to arrive as the integer the chart compares: under a transform
+ of ``typeof(:value)`` the raw string previewed ``'text'`` where the chart
+ emitted ``'integer'``. And because `_probe_cache_key` keys on each value's
+ ``repr``, the two also missed each other's cache entirely -- so the "a
+ previewed transform warms the chart path for free" claim in
+ `preview_partition_mapping`'s docstring did not actually hold.
+
+ Coerced by `filter_values_handler`, the same function the query path uses,
+ rather than by a second implementation of the same rules. Everything the
+ query path then does to the coerced value -- rendering an expression as a
+ literal, widening a bound, declining a comparison the engine resolves too
+ coarsely -- is `ExploreMixin.mirror_probe_request`'s, and the caller hands
+ this result straight to it.
+
+ Ranges are not previewable (see `PREVIEWABLE_OPERATORS`), so the bound
+ conversion `_collect_partition_mirror_range` applies -- a ``datetime`` into
+ the column's stored representation -- has no counterpart here.
+
+ Always answers with a value: nothing here declines. `UNMIRRORABLE` is
+ `mirror_probe_request`'s to return, and the caller hands this straight to it.
+ """
+ is_list = operator == FilterOperator.IN
+ column_spec = datasource.db_engine_spec.get_column_spec(native_type=column.type)
+ handled = datasource.filter_values_handler(
+ # `list[str]` is not a `list[FilterValue]` to mypy, invariantly, even
+ # though every `str` is a `FilterValue`.
+ values=cast(FilterValues, sample_values if is_list else sample_values[0]),
+ operator=operator,
+ target_generic_type=(
+ column_spec.generic_type if column_spec else utils.GenericDataType.STRING
+ ),
+ target_native_type=column.type,
+ is_list_target=is_list,
+ db_engine_spec=datasource.db_engine_spec,
+ db_extra=datasource.db_extra,
+ )
+ # No `ColumnElement` conversion here: an epoch-milliseconds sample comes back
+ # as engine SQL rather than a value, and `mirror_probe_request` renders it --
+ # the same step, on the same values, as for a chart filter.
+ return handled
+
+
+def _render_sample_input(
+ datasource: SqlaTable,
+ mapped_column: str,
+ operator: FilterOperator,
+ values: list[str],
+) -> str:
+ """
+ The filter being previewed, written the way an owner would read it.
+
+ Display-only -- it is never executed -- but it is still read as SQL, so the
+ column is quoted and the values are rendered by the dialect rather than
+ concatenated raw. A column named ``order date`` would otherwise come out as
+ two bare words.
+ """
+ quoted = datasource.quote_identifier(mapped_column)
+ if operator == FilterOperator.IN:
+ rendered = ", ".join(
+ _render_literal(datasource.database, value) for value in values
+ )
+ return f"{quoted} IN ({rendered})"
+ return (
+ f"{quoted} {operator.value} {_render_literal(datasource.database, values[0])}"
+ )
+
+
+def _render_predicate(datasource: SqlaTable, predicate: ColumnElement[Any]) -> str:
+ """
+ Compile a mirrored predicate to the text a reader would see in View query.
+
+ Every value in it is a probed constant by this point, so ``literal_binds``
+ renders the same literals the chart query carries.
+ """
+ return _compile_literal(predicate, _dialect_for(datasource.database)).replace(
+ "\n", " "
+ )
+
+
+def _render_literal(database: Database, value: Any) -> str:
+ """
+ Render a value the way it appears in the generated SQL.
+
+ Compiled by the dialect rather than formatted by hand. `str()` would render
+ a NULL as the Python repr `None` and leave a date unquoted, neither of which
+ is SQL, and hand-rolled quote-doubling would only ever have been right for
+ strings.
+ """
+ return _compile_literal(sa.literal(value), _dialect_for(database))
+
+
+def build_mirrored_predicates(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ requests: list[tuple[FilterOperator, Any]],
+ *,
+ errors: list[str] | None = None,
+ type_errors: list[str] | None = None,
+) -> list[ColumnElement[Any]]:
+ """
+ Turn collected ``(operator, value)`` mirror requests into predicates.
+
+ ``requests`` is expected to be deduplicated by the caller. Every value is
+ resolved in a single probe round trip -- one per chart query at most -- then
+ emitted as a literal constant, so "View query" shows the reader an ordinary
+ ``WHERE`` clause rather than an inline expression.
+
+ A strict bound is emitted non-strictly; see `mirror_operator`. That happens
+ here, at the one point where a ``FilterOperator`` becomes SQL, rather than
+ at the collection sites in `ExploreMixin`: the preview endpoint calls this
+ directly, so this is what keeps the predicate the editor shows an owner and
+ the predicate the chart carries from disagreeing.
+
+ :param errors: optional sink; see `evaluate_transform`.
+ :param type_errors: optional sink for a probe result the partition column
+ cannot hold -- see `probed_value_type_error`. Separate from ``errors``
+ because the two say different things to an owner: that one is "the
+ database would not evaluate this", and this one is "it evaluated, and
+ answered with the wrong kind of thing".
+ """
+ if not requests:
+ return []
+
+ partition_column = next(
+ (
+ column
+ for column in datasource.columns
+ if column.column_name == mapping.partition_column
+ ),
+ None,
+ )
+ if partition_column is None:
+ return []
+
+ # Flatten every value that needs probing into one list, remembering how many
+ # each request consumed so the results can be handed back out.
+ flat: list[Any] = []
+ spans: list[tuple[FilterOperator, int, int]] = []
+ for operator, value in requests:
+ values = list(value) if operator == FilterOperator.IN else [value]
+ spans.append((operator, len(flat), len(values)))
+ flat.extend(values)
+
+ evaluated = evaluate_transform(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ mapping.value_transform,
+ flat,
+ errors=errors,
+ )
+ if evaluated is None:
+ return []
+
+ if not _bounds_are_ordered(evaluated, spans):
+ return []
+
+ # Declining here is the last chance to decline at all: once these
+ # predicates are in the statement, a value the partition column cannot
+ # hold fails the whole chart rather than its pruning.
+ if reason := probed_value_type_error(partition_column, evaluated):
+ logger.warning(
+ "Partition transform returned a value the partition column cannot "
+ "hold; queries will not prune: %s",
+ reason,
+ )
+ if type_errors is not None:
+ type_errors.append(reason)
+ # Deliberately *not* recorded as a mirror verdict. The transform
+ # evaluated perfectly; what failed is the comparison against this
+ # dataset's partition column -- and `_mirror_verdict_cache_key` is
+ # keyed on database, catalog, schema and transform, with no partition
+ # column in it. Recorded, this dataset-specific outcome answered for
+ # every other dataset sharing the transform: `CAST(:value AS text)`
+ # mirroring happily onto a text key in dataset A was reported
+ # `evaluable: false` -- and its pruning indicator hidden -- because
+ # someone previewed the same transform against a numeric key in
+ # dataset B. A probe cache hit on A never rewrites the verdict, so it
+ # stayed wrong until the entry expired.
+ return []
+
+ sqla_col = datasource.convert_tbl_column_to_sqla_col(partition_column)
+ predicates = _predicates_from_probe(
+ sqla_col, datasource.db_engine_spec, evaluated, spans
+ )
+ if not predicates:
+ return []
+
+ # A comparison against a NULL partition value is NULL, so a row parked in a
+ # NULL partition is dropped by the mirror even when the real filter matches
+ # it -- Hive and Impala's default partition, or a transform that returns
+ # NULL for an input it cannot convert. The mirror only has to be no
+ # narrower than the filter it stands in for, so admitting NULL partitions
+ # keeps those rows. Engines still prune; they read one extra partition.
+ return [sa.or_(sa.and_(*predicates), sqla_col.is_(None))]
+
+
+def _predicates_from_probe(
+ sqla_col: ColumnElement[Any],
+ db_engine_spec: type[BaseEngineSpec],
+ evaluated: list[Any],
+ spans: list[tuple[FilterOperator, int, int]],
+) -> list[ColumnElement[Any]]:
+ """
+ One predicate on the partition column per surviving mirror request.
+
+ A request whose probe answered `None` for any of its values is skipped
+ rather than emitted: `col = NULL` is `NULL`, so it would drop every row the
+ filter keeps. A strict bound is emitted non-strictly; see `mirror_operator`.
+ """
+ predicates: list[ColumnElement[Any]] = []
+ for operator, start, length in spans:
+ chunk = evaluated[start : start + length]
+ if any(value is None for value in chunk):
+ continue
+ if operator == FilterOperator.IN:
+ # The probe answers per value, so a transform over a mixed-number
+ # filter can answer with a mixed-number partition key -- and
+ # `in_` infers the bind type from the first element it is handed.
+ # Without this, probe results of `[33, 29.02]` emit
+ # `IN (33, 29)` and prune away the partition holding `29.02`.
+ predicates.append(sqla_col.in_(normalize_mixed_numbers(chunk)))
+ else:
+ predicates.append(
+ db_engine_spec.handle_comparison_filter(
+ sqla_col, mirror_operator(operator), chunk[0]
+ )
+ )
+ return predicates
+
+
+#: Operators whose value is the lower end of a range, and whose upper-end twins.
+#:
+#: Shared with `ExploreMixin._mirror_probe_input`, which rounds a bound *outward*
+#: where the engine resolves it more coarsely than the filter carries -- backward
+#: for a lower bound, forward for an upper one. Which end an operator names is
+#: the only thing separating the two directions in either caller, so the two have
+#: to agree on it rather than each classify for itself.
+LOWER_BOUND_OPERATORS = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+}
+UPPER_BOUND_OPERATORS = {
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+#: What Python type a probe result may have, per generic type of the partition
+#: column it is about to be compared against.
+#:
+#: Only the types a mismatch can actually break a query with are listed. An
+#: unresolvable column type is absent because there is nothing to check
+#: against, and ``MULTI_VALUE`` because this module does not mirror onto an
+#: array partition key at all.
+#: ``numbers.Number`` rather than ``(int, float)``: Postgres answers
+#: ``extract(epoch from ...)`` with a `Decimal`, which is the single commonest
+#: transform this feature has, and an engine is free to answer with any number
+#: type its driver prefers. What the check is for is a *string* where a number
+#: belongs, and every numeric type is equally not that.
+_PROBE_RESULT_TYPES: dict[utils.GenericDataType, tuple[type, ...]] = {
+ utils.GenericDataType.NUMERIC: (numbers.Number,),
+ utils.GenericDataType.BOOLEAN: (bool,),
+ # A day key such as ``to_char(:value, 'YYYYMMDD')`` is legitimately text,
+ # so ``str`` is admitted -- but only for text an engine reads as an
+ # instant. `_reads_as_temporal` is the second half of this entry.
+ utils.GenericDataType.TEMPORAL: (datetime, date, str),
+ # Text, and not a number rendered as one. Not every engine accepts a number
+ # in a text comparison: Postgres refuses ``character varying = integer``,
+ # Trino ``varchar = bigint`` and BigQuery ``STRING = INT64``, all of which
+ # fail the whole chart once the predicate is in the statement. SQLite is
+ # worse -- it raises nothing and compares across storage classes as never
+ # equal, so the mirror drops every row rather than losing pruning, which is
+ # the one outcome this feature may not have. An owner whose partition key
+ # really is text writes the cast into the transform.
+ utils.GenericDataType.STRING: (str,),
+}
+
+
+#: Day/second keys a temporal column accepts as text, beyond ISO 8601.
+#: ``YYYYMMDD`` is the commonest bucketing key this feature exists for, and
+#: Postgres, Trino and BigQuery all read it as a date.
+_TEMPORAL_KEY_FORMATS = ("%Y%m%d", "%Y%m%d%H%M%S", "%Y-%m-%d %H:%M:%S")
+
+
+def _reads_as_temporal(value: str) -> bool:
+ """
+ Whether an engine would read this text as a date or timestamp.
+
+ `_PROBE_RESULT_TYPES` admits ``str`` for a temporal partition column
+ because a day key such as ``to_char(:value, 'YYYYMMDD')`` is legitimately
+ text -- but it admitted *every* string, so a transform that answers with
+ ordinary text passed the gate and failed the chart instead. On PostgreSQL a
+ ``VARCHAR`` mapped column under ``lower(:value)`` probes ``'US'`` to
+ ``'us'`` and emits ``p = 'us'`` against a ``DATE`` key, which the engine
+ refuses once the predicate is already in the statement -- so a chart that
+ worked before the mapping returns an error rather than losing its pruning.
+
+ Answered by parsing, not by asking the engine: the check runs on the
+ chart-query path, where a second round trip is the cost this module spends
+ its effort avoiding. Parsing is also the conservative direction -- anything
+ unrecognised declines, and declining costs only the pruning.
+ """
+ try:
+ datetime.fromisoformat(value)
+ return True
+ except ValueError:
+ pass
+ for fmt in _TEMPORAL_KEY_FORMATS:
+ try:
+ datetime.strptime(value, fmt)
+ return True
+ except ValueError:
+ continue
Review Comment:
`strptime` accepts unpadded fields, so an epoch string like `'1767225600'` passes as `%Y%m%d%H%M%S` (1767-02-25 06:00) and is emitted as `part_date = '1767225600'`, the bad-literal error this gate exists to stop.
```suggestion
try:
# Round-tripped: `strptime` accepts unpadded fields, so a bare
# epoch such as ``1767225600`` otherwise parses as ``%Y%m%d%H%M%S``.
if datetime.strptime(value, fmt).strftime(fmt) == value:
return True
except ValueError:
continue
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "hughhhh (via GitHub)" <gi...@apache.org>.
hughhhh commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4392784632
##########
superset/models/helpers.py:
##########
@@ -4552,36 +4661,777 @@ def dttm_sql_literal(self, dttm: datetime, col: "TableColumn") -> str:
return f"""'{dttm.strftime("%Y-%m-%d %H:%M:%S.%f")}'"""
- def get_time_filter( # pylint: disable=too-many-arguments # noqa: C901
+ def _mirror_probe_value(self, dttm: datetime, col: Optional["TableColumn"]) -> Any:
+ """
+ ``dttm`` in the mapped column's own stored representation.
+
+ The predicate this mirror stands in for compares the column against
+ `dttm_sql_literal(dttm, col)`, so the transform has to be probed with
+ the same value. On a column stored as an epoch integer, ``T`` is a
+ function of an integer: probing it with a `datetime` either returns
+ something unrelated to the partition keys or raises, and a raise costs
+ the dataset its pruning silently.
+
+ Only the ``python_date_format`` branches of `dttm_sql_literal` are
+ reproduced, because only those produce a *value*. `convert_dttm` yields
+ engine-specific SQL text, which cannot be bound as a parameter; its own
+ divergence from the probe is handled by widening the bounds instead
+ (`_engine_literal_resolution`).
+
+ In `dttm_sql_literal`'s own order, though: it asks ``convert_dttm``
+ first and reaches the format only when the engine answers nothing. A
+ column can carry both -- a TIMESTAMP with a ``%Y%m%d``
+ ``python_date_format``, or an entry in
+ ``python_date_format_by_column_name`` -- and applying the format
+ unconditionally probed a value the real predicate never compares.
+ ``event_time >= '2026-01-01 00:00:00'`` mirrored as
+ ``partition_col >= '20260101'``, and a January 15 row keyed
+ ``2026-01-15`` sorts below that string, so the chart lost a row the
+ filter keeps.
+
+ Where the engine does answer, the `datetime` is returned unchanged and
+ the widening path takes over -- which is exactly what already happens
+ for every temporal column that carries no format at all.
+ """
+ if col is None:
+ return dttm
+
+ if col.type and self.db_engine_spec.convert_dttm(
+ col.type, dttm, db_extra=self.db_extra
+ ):
+ # The format is unreachable in `dttm_sql_literal` for this column,
+ # so reproducing it here would describe a different bound.
+ return dttm
Review Comment:
{ai generated comment}
Thanks, fixed in d91389152e. When the engine renders the bound and the column holds only days, `_mirror_probe_value` now returns `dttm.date()` at midnight, so the probe binds the same day the filter compares. Columns that store a time of day keep the `datetime`: TIMESTAMP, and Oracle `DATE` (via `holds_days_only`, which reads the dialect's own type). With your example run against a real SQLite file, a January range now mirrors as `p >= '2026-01-01' AND p <= '2026-02-01'` and keeps every January 1 row.
One note: at the head you reviewed, this case no longer dropped rows. The new two-shapes check saw the timestamp answer (`…00:00:00.000000`) disagree with the text one (`…00:00:00`) and declined the mirror, so results were correct but the pruning was lost. With the date probe the two forms agree, so the mirror is kept. Covered by `test_a_midnight_bound_on_a_date_column_is_probed_as_the_day`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4201457787
##########
superset/migrations/versions/2026-09-23_00-01_a7f3c2e91d84_add_partition_filter_mapping.py:
##########
@@ -0,0 +1,101 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""add partition filter mapping
+
+Adds the four columns behind the ``PARTITION_FILTER_MAPPING`` feature:
+
+- ``tables.partition_column`` -- the physical column the engine partitions on
+- ``tables.partition_mapped_column`` -- explicit override for the column whose
+ filters are mirrored; NULL means "follow ``main_dttm_col``"
+- ``table_columns.partition_value_transform`` -- the ``:value`` expression
+- ``table_columns.partition_transform_is_monotonic`` -- gates range operators
+
+The Continuum shadow tables get the same columns so dataset version history and
+restore keep working.
+
+Revision ID: a7f3c2e91d84
+Revises: 884a2115ebd3
+Create Date: 2026-08-31 22:30:00.000000
+
+"""
+
+import sqlalchemy as sa
+
+from superset.migrations.shared.utils import add_columns, drop_columns
+
+# revision identifiers, used by Alembic.
+revision = "a7f3c2e91d84"
+down_revision = "884a2115ebd3"
Review Comment:
Master's `00fab727cd0a` also revises `884a2115ebd3`, so the merge still leaves two Alembic heads and `test_migrations_have_one_head` fails; re-parenting here passes it (the `Revises:` docstring line wants the same change).
```suggestion
down_revision = "00fab727cd0a"
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(explore): indicate when a filter is mirrored onto a partition column [superset]
Posted by "hughhhh (via GitHub)" <gi...@apache.org>.
hughhhh closed pull request #43870: feat(explore): indicate when a filter is mirrored onto a partition column
URL: https://github.com/apache/superset/pull/43870
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4320971029
##########
superset/commands/dataset/importers/v0.py:
##########
@@ -291,7 +319,154 @@ def run(self) -> None:
.one()
)
dataset["database_id"] = database.id
- SqlaTable.import_from_dict(dataset, sync=self.sync)
+ self._prepare_partition_mapping(dataset, database)
+ table = SqlaTable.import_from_dict(dataset, sync=self.sync)
+ if table is not None:
+ imported.append(table)
+
+ self._repair_partition_mappings(imported)
+
+ @classmethod
+ def _default_omitted_monotonic_declarations(cls, config: Any) -> None:
+ """
+ Materialize `partition_transform_is_monotonic` wherever a transform is
+ set, anywhere in a v0 config.
+
+ The v1 importer does this on its own raw config, and for the same
+ reason: an overwrite keeps whatever the bundle omits, including a
+ ``True`` left behind by the transform this bundle is replacing. A
+ non-monotonic transform declared monotonic enables range mirrors that
+ exclude rows the filter keeps -- ``abs(:value)`` inheriting a stored
+ ``True`` turns ``n >= -1`` into ``p >= 1`` and misses ``n = 0``.
+
+ Walked rather than addressed directly because a v0 bundle comes in two
+ shapes: a CLI export nests datasets under ``databases[].tables[]``,
+ while a UI export is a bare list of datasets. Only columns that supply
+ a transform are touched, so a re-import that says nothing about a
+ column stays idempotent.
+ """
+ if isinstance(config, list):
+ for entry in config:
+ cls._default_omitted_monotonic_declarations(entry)
+ return
+ if not isinstance(config, dict):
+ return
+ _default_omitted_monotonic_declarations(config.get("columns") or [])
+ for key in (DATABASES_KEY, "tables"):
+ for child in config.get(key) or []:
+ cls._default_omitted_monotonic_declarations(child)
+
+ @staticmethod
+ def _prepare_partition_mapping(
+ dataset: dict[str, Any], database: Optional[Database]
+ ) -> None:
+ """
+ Run the two repairs that have to happen *before* the bundle is applied.
+
+ `_repair_partition_mappings` below runs after `import_from_dict`, which
+ is too late for either of these.
+
+ Sanitizing the bundle. The v1 importer drops a transform the save path
+ would refuse (`drop_unusable_partition_transforms`) on its way in, and
+ v0 did not -- so a legacy bundle naming ``partition_mapped_column: n``
+ and a transform of ``random() + :value`` on ``n`` imported happily and
+ then failed *every* later save: a description-only
+ ``PUT /api/v1/dataset/<id>`` returns 422 on the stored expression, and
+ the mapping never mirrors anything. Applied to the config rather than
+ the model because that is where the transform still is.
+
+ Disarming the old mapping. `DatasetDAO.clear_unmapped_partition_transforms`
+ reads the mapping as it stands, so the post-import call can only enforce
+ the one-transform invariant against the *new* references. An overwrite
+ that re-points the mapping makes a previously unmapped column the
+ effective one, and a transform parked there -- which nothing in the
+ bundle authored -- is found already mapped by the later call and kept.
+ A dataset mapping ``a -> p`` with a parked ``:value + 100`` on ``b``,
+ overwritten by a bundle setting ``partition_mapped_column: b`` and
+ omitting the columns, would mirror ``b = 5`` as ``p = 105`` and drop the
+ row ``(a=1, b=5, p=1)``. The same pre-change call `DatasetDAO.update`
+ and the v1 importer both make, and for the same reason.
+
+ ``database`` is ``None`` only for a CLI bundle importing a connection
+ that does not exist yet, which by definition has no stored dataset to
+ disarm and no dialect to validate a transform against -- the same case
+ `drop_unusable_partition_transforms` already declines to act on.
+ """
+ if database is None:
+ return
+
+ # Deferred import: `daos.dataset` pulls in `views.base`, which
+ # circularly imports back into the commands package at app init.
+ from superset.daos.dataset import DatasetDAO # noqa: PLC0415
+
+ drop_unusable_partition_transforms(dataset, database)
+
+ if not (table_name := dataset.get("table_name")):
+ return
+ existing = (
+ db.session.query(SqlaTable)
+ .filter(
+ SqlaTable.table_name == table_name,
+ SqlaTable.schema == dataset.get("schema"),
+ SqlaTable.catalog == dataset["catalog"]
+ if dataset.get("catalog") is not None
+ else True,
+ SqlaTable.database_id == database.id,
+ )
+ .one_or_none()
+ )
+ if existing is not None:
+ DatasetDAO.clear_unmapped_partition_transforms(existing)
+
+ @staticmethod
+ def _repair_partition_mappings(datasets: list[SqlaTable]) -> None:
+ """
+ Keep the partition filter mapping honest across a v0 import.
+
+ The mapping's columns ride in `SqlaTable.export_fields`, so this path
+ carries them -- but it calls `SqlaTable.import_from_dict` directly and
+ goes through neither `DatasetDAO.update` nor the v1 importer, so
+ neither of the mapping's repairs ran. An older bundle imported with
+ ``--sync columns`` that omits the partition column deletes it and keeps
+ `partition_column` naming it: pruning silently stops, and every later
+ edit of that dataset fails the partition-column-not-found validation,
+ including a description-only PUT, which carries no columns payload and
+ so cannot reach the branch that forgives a stored-only dangle.
+
+ The same pair, in the same order, as `RefreshDatasetCommand` and the
+ v1 importer. Run after the import rather than around it because
+ ``import_from_dict`` is what discovers which datasets are involved.
+ """
+ if not datasets:
+ return
+ # Deferred import: `daos.dataset` pulls in `views.base`, which
+ # circularly imports back into the commands package at app init.
+ from superset.daos.dataset import DatasetDAO # noqa: PLC0415
+
+ db.session.flush()
+ for dataset in datasets:
+ DatasetDAO.clear_dangling_partition_mapping(
Review Comment:
`dataset.columns` is still the pre-import collection here: `import_from_dict` removes omitted columns with `session.delete(...)`, and `flush()` doesn't drop them from an already-loaded relationship. With `sync=["columns"]` and a bundle that omits the partition column `p`, `p` still counts as a survivor, so `partition_column` keeps naming a column that no longer exists. Pruning stops and every later PUT (even description-only) fails the column-not-found validation. Should this expire `columns` before reading the surviving names, the way the v1 importer does?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "hughhhh (via GitHub)" <gi...@apache.org>.
hughhhh commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4319658377
##########
UPDATING.md:
##########
@@ -24,6 +24,24 @@ assists people when migrating to a new version.
## Next
+- Refreshing a dataset's columns from its source -- the "Sync columns from
+ source" button, and a `PUT /api/v1/dataset/<id>?override_columns=true` --
+ no longer resets **Is dimension** and **Is filterable** on columns that
+ already exist. Those two flags were set unconditionally on every column the
+ source reported, so a save that synced columns reverted whatever the dataset
+ owner had chosen for them. A newly discovered column still arrives with both
+ enabled. A deployment that relied on a resync to restore those defaults has
+ to set them explicitly.
+
+- `DISALLOWED_SQL_FUNCTIONS` now names the whole PostgreSQL XML family. Four
Review Comment:
Fixed. The note names `ts_rewrite` and `ts_stat` alongside the XML functions, and says they run their text argument as a query.
##########
docs/admin_docs/configuration/partition-filter-mapping.mdx:
##########
@@ -0,0 +1,204 @@
+---
+title: Partition Filter Mapping
+hide_title: true
+sidebar_position: 15
+version: 1
+---
+
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+
+# Partition Filter Mapping
+
+Tables on Hadoop-family engines are often partitioned on a *technical* column — an epoch
+integer, a lowercased region key — that no analyst would ever filter on. Unless a query
+carries a predicate on that column, the engine scans every partition.
+
+Partition filter mapping makes this a dataset setting instead of a per-chart chore. A
+dataset owner names the partition column, the business column whose filters should be
+mirrored onto it, and a value transform. Superset then appends an equivalent predicate on
+the partition column to every query. Chart authors change nothing; queries prune.
+
+:::caution Experimental
+This feature is behind the `PARTITION_FILTER_MAPPING` feature flag and is off by default.
+:::
+
+## Enabling it
+
+```python
+FEATURE_FLAGS = {
+ "PARTITION_FILTER_MAPPING": True,
+}
+```
+
+Configure it as a **static boolean**. `FEATURE_FLAGS` also accepts per-request callables,
+but a flag that resolves differently per user or tenant would let a user with the feature
+off read a cached chart result that was produced from pruned SQL by a user with it on.
+
+## Configuring a mapping
+
+In the dataset editor's **Columns** tab, under *Default Column Settings*, pick a
+**Partition column**. By default the mapping follows the dataset's default datetime column,
+so re-pointing that column moves the mapping with it; set an explicit override if you want it
+pinned to a different column.
+
+Expand the mapped column's row in *Column Settings* and set the **value transform**: a SQL
+expression containing a `:value` placeholder, which stands for the filter value being
+mirrored. The **Transform preserves ordering** checkbox sits directly beneath it.
+
+| Mapped column | Partition column | Transform |
+|---|---|---|
+| `event_time` (`TIMESTAMP`) | `dt_epoch` (`BIGINT`) | `unix_timestamp(:value)` |
+| `country` (`VARCHAR`) | `region_key` (`VARCHAR`) | `lower(:value)` |
+
+A filter of `event_time >= '2026-01-01'` then adds `dt_epoch >= 1767225600` to the query.
+The added predicate is an ordinary `WHERE` clause and shows up in **View query**.
+
+### Transform preserves ordering
+
+Range filters — including the Explore time range, the most important case — are only
+mirrored when you check **Transform preserves ordering**.
+
+Monotonicity is a property of the *transform*, not of the column's data type.
+`unix_timestamp(:value)` preserves ordering. `hour(:value)`,
+`date_format(:value, 'dd')` and `dayofweek(:value)` are all perfectly reasonable
+partition transforms on a `TIMESTAMP` column and none of them do: `hour('2026-01-01 23:00')`
+is greater than `hour('2026-01-02 01:00')` even though the first instant is earlier. Mirroring
+a range through one of those would silently return wrong numbers, so Superset asks you to
+declare it rather than guessing.
+
+When the box is unchecked, `=` and `IN` filters still mirror; ranges do not.
+
+## What is and isn't mirrored
+
+| Filter | Mirrored |
+|---|---|
+| `=`, `IN` | Always, except on a text column whose engine does not compare text exactly |
+| `>`, `>=`, `<`, `<=`, time ranges | Only when the transform preserves ordering |
+| `!=`, `NOT IN`, `LIKE`, `ILIKE`, `IS NULL`, `IS TRUE` | Never |
+
+Negations are never safe. A transform need not be injective: `lower(:value)` with
+`country != 'US'` would mirror to `region_key != 'us'`, which excludes rows whose `country`
+is already lowercase `'us'` — rows the original filter *keeps*.
+
+**Text comparison.** Mirroring `col = v` onto `partition_col = T(v)` assumes the engine
+compares `col` the way the transform was written against. Under a case-insensitive collation
+it does not: a stored `country` of `'us'` satisfies a filter for `'US'`, while the mirror is
+derived from `'US'` and excludes the row. So `=` and `IN` on a **text** mapped column only
+mirror on engines whose default text comparison is exact — Hive, Impala, Trino, Presto,
+Spark, Databricks, PostgreSQL, Snowflake, BigQuery and SQLite. On MySQL and SQL Server, whose
+default collations are case-insensitive, a text mapping is stored and shown but no `=` or
+`IN` filter mirrors through it; map a numeric or temporal column instead. Numeric and
+temporal comparison is exact everywhere, and ranges are unaffected either way — checking
+**Transform preserves ordering** is already a statement about the column's own ordering.
+
+One case Superset cannot check for you: a column that declares its own collation, such as
+`country COLLATE NOCASE`, on an engine that is otherwise exact. Nothing in the metadata
+exposes that, so it falls under the same pipeline assumption as the partition key itself.
+
+**Time grains.** A filter that carries a time grain — drill-to-detail, mostly — compares the
+*truncated* column, so the raw bounds it carries do not describe the rows it keeps: a row in
+the final partial bucket satisfies `DATE_TRUNC(...) < until` while `col < until` excludes it.
+Grained *ranges* still mirror, with both bounds widened by one bucket so the mirror stays no
+narrower than the real filter. A `P1D` drill therefore reads three days of partitions rather
+than one, instead of scanning the table. Grained `=` and `IN` filters do not mirror.
+
+Widening is only applied to grains whose bucket width Superset knows, which means the
+built-in ones. A grain you added through `TIME_GRAIN_ADDONS`, or a built-in grain whose SQL
+you replaced through `TIME_GRAIN_ADDON_EXPRESSIONS`, has no width Superset can rely on and
+simply does not mirror.
+
+Known gaps, all of which are out of scope rather than bugs:
+
+- **Filter-value dropdowns do not prune.** Populating a filter's value list runs its own
+ `SELECT DISTINCT`, which never goes through the chart query path. There is no filter to
+ mirror from.
+- **Row-level security predicates do not mirror.** They are stored as raw SQL and appended
+ downstream of the structured filters.
+- **Custom SQL `WHERE` clauses do not mirror**, for the same reason.
+- **Columns with an active advanced data type do not mirror.** Those build their own
+ predicate shape from translated values, so there is no operator/value pair to mirror.
+- Dashboard native filters and cross-filters *do* mirror — they arrive as ordinary filters —
+ they just carry no visual indicator in the filter bar.
+
+## The assumption this rests on
+
+Superset emits a predicate on the partition column that stands in for one on the mapped
+column. That substitution is only valid if, for every row in the table:
+
+```
+partition_column = <transform>(mapped_column)
+```
+
+**Superset cannot verify this.** It is a property of whatever ETL populates the partition
+column. If that job lags, backfills with different logic, or writes the partition key in a
+different timezone than the transform resolves, mirrored predicates silently drop real rows
+and charts show quietly wrong numbers. Confirm the invariant with whoever owns the pipeline
+before enabling a mapping on a production dataset.
+
+Rows in a `NULL` partition are the one case Superset *does* defend against. A predicate like
+`dt_epoch >= X` is `NULL` — and so drops the row — wherever `dt_epoch` is `NULL`, even when
+the original filter matches it. That is reachable: a dynamic-partition insert on Hive or
+Impala parks rows whose partition key was `NULL` in the default partition
+(`__HIVE_DEFAULT_PARTITION__`), and the column reads back as `NULL` when you query it. A
+transform that returns `NULL` for an input it cannot convert produces the same thing on any
+engine.
+
+The mirrored predicate is therefore emitted as:
+
+```sql
+(dt_epoch >= X AND dt_epoch < Y) OR dt_epoch IS NULL
+```
+
+The mirror only has to be *no narrower* than the filter it stands in for, so admitting the
+`NULL` partition costs one extra partition read and keeps those rows. Engines still prune
+everything else.
+
+## How the transform is evaluated
+
+The transform is evaluated against the engine — pinned to the dataset's database, catalog
+and schema — and the result is emitted as a literal constant. Results are cached
+(`PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT`, 24 hours by default), which matters because this
+adds a round trip to the chart query path. Day-aligned ranges like "Last month" hit the cache
+constantly; second-granularity relative ranges like "Last 24 hours" essentially never do.
+
+If the evaluation fails for any reason, no predicate is added: the query still runs and is
+still correct, it just scans more partitions.
+
+Because the evaluation happens in a **different session** from the chart query, transforms
+that call non-deterministic functions are rejected when you save. That includes `now()`,
+`current_date`, `current_timestamp`, `rand()` and the zero-argument `unix_timestamp()`, which
+means "now" on Hive and Impala. The one-argument `unix_timestamp(:value)` is fine.
+
+Session-dependent behaviour that Superset cannot detect is still your responsibility:
+`unix_timestamp(:value)` is timezone-dependent on Hive and Impala, so if the evaluating
+session and the query session resolve different timezones the emitted bounds will disagree
+with the timestamp bounds they mirror. Prefer explicitly-anchored transforms.
+
+Jinja templating is not supported in a transform. The template would render in a different
+context and at a different time from the chart query.
+
+## Related configuration
+
+| Setting | Default | Purpose |
+|---|---|---|
+| `PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT` | 24 hours | How long an evaluated transform stays cached |
+| `PARTITION_TRANSFORM_PREVIEW_RATE_LIMIT` | 30 | Per-user, per-dataset preview requests per minute; the editor's preview panel runs a real query |
Review Comment:
Fixed. The page now states that the throttle, the probe cache and the pruning indicator all read `CACHE_CONFIG`, that its default is `{"CACHE_TYPE": "NullCache"}`, what that means for each of the three, and that configuring `DATA_CACHE_CONFIG` does not help.
##########
docs/admin_docs/configuration/partition-filter-mapping.mdx:
##########
@@ -0,0 +1,298 @@
+---
+title: Partition Filter Mapping
+hide_title: true
+sidebar_position: 15
+version: 1
+---
+
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+
+# Partition Filter Mapping
+
+Tables on Hadoop-family engines are often partitioned on a *technical* column — an epoch
+integer, a lowercased region key — that no analyst would ever filter on. Unless a query
+carries a predicate on that column, the engine scans every partition.
+
+Partition filter mapping makes this a dataset setting instead of a per-chart chore. A
+dataset owner names the partition column, the business column whose filters should be
+mirrored onto it, and a value transform. Superset then appends an equivalent predicate on
+the partition column to every query. Chart authors change nothing; queries prune.
+
+:::caution Experimental
+This feature is behind the `PARTITION_FILTER_MAPPING` feature flag and is off by default.
+:::
+
+## Enabling it
+
+```python
+FEATURE_FLAGS = {
+ "PARTITION_FILTER_MAPPING": True,
+}
+```
+
+Configure it as a **static boolean**. `FEATURE_FLAGS` also accepts per-request callables,
Review Comment:
Fixed. The page now says per-request resolution comes only from `GET_FEATURE_FLAGS_FUNC` and `IS_FEATURE_ENABLED_FUNC`, and that for this flag both must return the same answer for every user.
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/DatasourceEditor.tsx:
##########
@@ -1128,10 +1222,22 @@ function DatasourceEditor({
validationErrors = validationErrors.concat(folderValidation.errors);
}
+ // Validate the partition filter mapping. `databaseColumns` rather than
+ // `datasource.columns`, because the two only meet in `onChangeInternal`
+ // when the payload is assembled -- `datasource.columns` does not carry the
+ // transform the owner just typed.
+ if (isFeatureEnabled(FeatureFlag.PartitionFilterMapping)) {
+ validationErrors = validationErrors.concat(
Review Comment:
Fixed. Mapping validation runs against `[...databaseColumns, ...calculatedColumns]`, matching the backend's own column set, while the partition-column picker stays physical-only. Non-blocking issues are filtered out of the Save gate separately.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "hughhhh (via GitHub)" <gi...@apache.org>.
hughhhh commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4319665531
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,1613 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import re
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: Every entry point enforces it -- the typed column field, the import schema
+#: and the preview request -- because `is_transform_active` parses the stored
+#: value on each Explore load, and an unbounded string would make that parse
+#: the expensive part of rendering a chart.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+ """
+ return VALUE_PLACEHOLDER_RE.sub(_PARSE_STANDIN, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(transform: str, engine: str) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error(
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ selections = []
+ for index, value in enumerate(values):
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ selections.append(f"{_compile_literal(clause, dialect)} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ database.db_engine_spec.select_without_from_suffix,
+ )
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _compile_literal(element: Any, dialect: Dialect | None) -> str:
+ """
+ Compile with inline literals, undoing the paramstyle's percent doubling.
+
+ Both ``TextClause`` and literal compilation run the dialect's
+ ``post_process_text``, which doubles every ``%`` whenever the identifier
+ preparer asks it to -- true for MySQL and Postgres and for every spec
+ inheriting their paramstyle. That doubling exists so a later DBAPI
+ parameter-interpolation pass can undo it, and the probe has no such pass:
+ it executes with no bound parameters at all. So a transform of
+ ``date_format(:value, '%Y%m%d')`` reaches the warehouse asking for the
+ literal string ``%%Y%%m%%d``, the probe returns that instead of a date, and
+ the mirrored predicate drops every row the filter keeps.
+
+ The same normalization ``Database.compile_sqla_query`` applies for the same
+ reason. ``_double_percents`` is private and not guaranteed on a third-party
+ dialect, hence the ``getattr`` default.
+ """
+ compiled = str(
+ element.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
+ )
+ if dialect is not None and getattr(
+ dialect.identifier_preparer, "_double_percents", False
+ ):
+ compiled = compiled.replace("%%", "%")
+ return compiled
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be *asked* to stand in for itself, and the transform
+ cannot carry Jinja or call a non-deterministic function. Tier 2
+ (``blocking=False``) is everything that merely leaves the mapping inactive
+ -- including a self-mapping nobody asked for, where the partition column
+ merely happens to be the default datetime column.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column == partition_column:
+ # Asked for explicitly, so report it as the mistake it is.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+ elif not partition_mapped_column and main_dttm_col == partition_column:
+ # Resolved onto itself only because the default datetime column happens
+ # to be the partition column -- a state metadata sync could produce
+ # without anyone asking for it. The mapping is inert either way, since
+ # `resolve_partition_mapping` bails out on it, so this reports and lets
+ # the write through: blocking here means a dataset already in the state
+ # can never be saved again, not even to change its description, and
+ # there is no field whose edit would clear the error first.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "%(name)s is both the partition column and the default "
+ "datetime column, so the mapping points at itself and "
+ "stays inactive. Set a mapped column override, or change "
+ "the default datetime column.",
+ name=partition_column,
+ ),
+ blocking=False,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_bare_expression(transform, engine):
+ # Blocking, and deliberately placed in `validate_transform` rather than
+ # only at the probe: one issue here closes the PUT, the importer, the
+ # query-time gate through `is_transform_active`, the Explore indicator's
+ # active verdict and the preview endpoint, all of which already consult
+ # this function.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
Review Comment:
Fixed. The catalogs were regenerated; `scripts/translations/check_pot_drift.py` reports the template matches a fresh extraction at the current head, and `check_translation_regression.py --compare` against master is +0 on all 31 languages.
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2395 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+#: Returned by `ExploreMixin.mirror_probe_request` for a filter no mirror can
+#: stand in for: one the engine compares more coarsely than the value carries, a
+#: value it cannot render as a literal, or an ``IN`` list with a member of
+#: either kind. A sentinel rather than `None`, because `None` is a filter value
+#: in its own right.
+#:
+#: Lives here rather than beside that method so the preview can read it too:
+#: `superset.models.helpers` imports this module, so the sentinel can only cross
+#: the boundary in this direction. Both callers have to recognise the same
+#: object -- a preview that answered "valid" for a request the chart path
+#: declines is the drift this is here to prevent.
+UNMIRRORABLE = object()
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error(
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the probe
+ uninspected -- string elements are escaped by the dialect's own literal
+ processor. `probe_sql_is_evaluable` then re-reads the finished query, which
+ is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ else:
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ rendered = _compile_literal(clause, dialect)
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Four things have to hold, and all four are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if not isinstance(statement, SQLStatement):
+ # A dialect whose statements this gate cannot take apart -- KQL -- gets
+ # no probe rather than an unchecked one. It never had one: the clause
+ # inspection below is implemented for SQL statements only, and the
+ # alternative to declining here is an `AttributeError` that `_probe`
+ # swallows into the same outcome, less legibly.
+ return False
+ if statement.has_subquery():
+ return False
+ if statement.get_clause_names() - {"from"}:
+ return False
+ if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+ """
+ The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+ Parsed rather than string-compared so that the comparison in
+ `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+ not parse answers ``None``, which no statement carrying a FROM can match --
+ the probe then declines, which is the right way for an unreadable engine
+ constant to fail.
+ """
+ if not from_suffix.strip():
+ return None
+ try:
+ return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+ except SupersetParseError:
+ return None
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=values is not None and not any(value is None for value in values),
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ from_suffix = database.db_engine_spec.select_without_from_suffix
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ from_suffix,
+ )
+ if not probe_sql_is_evaluable(
+ sql, database.backend, len(distinct), from_suffix
+ ):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
Review Comment:
Fixed. `EXECUTABLE_COMMENT_RE` (`/\*M?!`) refuses a transform carrying a MySQL/MariaDB executable comment, answered on the raw text ahead of the parse, so the gates and the engine can no longer see different statements.
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2338 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error(
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the probe
+ uninspected -- string elements are escaped by the dialect's own literal
+ processor. `probe_sql_is_evaluable` then re-reads the finished query, which
+ is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ else:
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ rendered = _compile_literal(clause, dialect)
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Four things have to hold, and all four are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if not isinstance(statement, SQLStatement):
+ # A dialect whose statements this gate cannot take apart -- KQL -- gets
+ # no probe rather than an unchecked one. It never had one: the clause
+ # inspection below is implemented for SQL statements only, and the
+ # alternative to declining here is an `AttributeError` that `_probe`
+ # swallows into the same outcome, less legibly.
+ return False
+ if statement.has_subquery():
+ return False
+ if statement.get_clause_names() - {"from"}:
+ return False
+ if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+ """
+ The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+ Parsed rather than string-compared so that the comparison in
+ `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+ not parse answers ``None``, which no statement carrying a FROM can match --
+ the probe then declines, which is the right way for an unreadable engine
+ constant to fail.
+ """
+ if not from_suffix.strip():
+ return None
+ try:
+ return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+ except SupersetParseError:
+ return None
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=values is not None and not any(value is None for value in values),
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ from_suffix = database.db_engine_spec.select_without_from_suffix
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ from_suffix,
+ )
+ if not probe_sql_is_evaluable(
+ sql, database.backend, len(distinct), from_suffix
+ ):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
Review Comment:
Fixed. Caching is skipped entirely when the connection's identity can vary per user — `if not (database.impersonate_user or app.config["DB_CONNECTION_MUTATOR"])` — so one user's probe results can no longer be served to another.
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,1613 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import re
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: Every entry point enforces it -- the typed column field, the import schema
+#: and the preview request -- because `is_transform_active` parses the stored
+#: value on each Explore load, and an unbounded string would make that parse
+#: the expensive part of rendering a chart.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+ """
+ return VALUE_PLACEHOLDER_RE.sub(_PARSE_STANDIN, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(transform: str, engine: str) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error(
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ selections = []
+ for index, value in enumerate(values):
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ selections.append(f"{_compile_literal(clause, dialect)} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ database.db_engine_spec.select_without_from_suffix,
+ )
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _compile_literal(element: Any, dialect: Dialect | None) -> str:
+ """
+ Compile with inline literals, undoing the paramstyle's percent doubling.
+
+ Both ``TextClause`` and literal compilation run the dialect's
+ ``post_process_text``, which doubles every ``%`` whenever the identifier
+ preparer asks it to -- true for MySQL and Postgres and for every spec
+ inheriting their paramstyle. That doubling exists so a later DBAPI
+ parameter-interpolation pass can undo it, and the probe has no such pass:
+ it executes with no bound parameters at all. So a transform of
+ ``date_format(:value, '%Y%m%d')`` reaches the warehouse asking for the
+ literal string ``%%Y%%m%%d``, the probe returns that instead of a date, and
+ the mirrored predicate drops every row the filter keeps.
+
+ The same normalization ``Database.compile_sqla_query`` applies for the same
+ reason. ``_double_percents`` is private and not guaranteed on a third-party
+ dialect, hence the ``getattr`` default.
+ """
+ compiled = str(
+ element.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
+ )
+ if dialect is not None and getattr(
+ dialect.identifier_preparer, "_double_percents", False
+ ):
+ compiled = compiled.replace("%%", "%")
+ return compiled
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be *asked* to stand in for itself, and the transform
+ cannot carry Jinja or call a non-deterministic function. Tier 2
+ (``blocking=False``) is everything that merely leaves the mapping inactive
+ -- including a self-mapping nobody asked for, where the partition column
+ merely happens to be the default datetime column.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column == partition_column:
+ # Asked for explicitly, so report it as the mistake it is.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+ elif not partition_mapped_column and main_dttm_col == partition_column:
+ # Resolved onto itself only because the default datetime column happens
+ # to be the partition column -- a state metadata sync could produce
+ # without anyone asking for it. The mapping is inert either way, since
+ # `resolve_partition_mapping` bails out on it, so this reports and lets
+ # the write through: blocking here means a dataset already in the state
+ # can never be saved again, not even to change its description, and
+ # there is no field whose edit would clear the error first.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "%(name)s is both the partition column and the default "
+ "datetime column, so the mapping points at itself and "
+ "stays inactive. Set a mapped column override, or change "
+ "the default datetime column.",
+ name=partition_column,
+ ),
+ blocking=False,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_bare_expression(transform, engine):
+ # Blocking, and deliberately placed in `validate_transform` rather than
+ # only at the probe: one issue here closes the PUT, the importer, the
+ # query-time gate through `is_transform_active`, the Explore indicator's
+ # active verdict and the preview endpoint, all of which already consult
+ # this function.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform must be a single SQL expression. It "
+ "cannot carry a FROM, WHERE, GROUP BY or any other clause, "
+ "and it cannot contain a sub-query."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not contains_value_placeholder(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform must contain the :value placeholder, "
+ "which stands for the filter value being mirrored."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if functions := find_non_deterministic_functions(transform, engine):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform calls %(functions)s, whose result "
+ "depends on when and where it runs. The transform is "
+ "evaluated in a separate session and the result is cached, "
+ "so the emitted predicate would freeze a snapshot of that "
+ "moment.",
+ functions=", ".join(sorted(functions)),
+ ),
+ blocking=True,
+ )
+ ]
+
+ return []
+
+
+@lru_cache(maxsize=LRU_CACHE_MAX_SIZE)
+def is_transform_active(transform: str | None, engine: str) -> bool:
+ """
+ Whether Superset will mirror filters through this transform.
+
+ `validate_transform` with the messages discarded, so the Explore indicator
+ cannot advertise a mapping the save path recorded as inactive. Anything
+ cheaper here would be a second, weaker statement of the same rule, free to
+ drift from the one the save path applies.
+
+ Blocking issues count too. Jinja and non-deterministic transforms are
+ rejected on PUT, but `CreateDatasetCommand` and import do not validate the
+ mapping, so one can still reach the database -- and it would never mirror a
+ filter either.
+
+ Memoized because `partition_filter_mapping_summary` is serialized on every
+ Explore and dashboard load and this parses the transform. The key is
+ everything the answer depends on: `validate_transform` reads no session, no
+ locale and no config beyond `SQL_MAX_PARSE_LENGTH`, which bounds the parser
+ rather than changing a verdict within that bound.
+ """
+ return not validate_transform(transform, engine)
+
+
+def preview_partition_mapping( # pylint: disable=too-many-return-statements
+ datasource: SqlaTable,
+ *,
+ mapped_column: str,
+ value_transform: str | None,
+ sample_values: list[str],
+ operator: FilterOperator = FilterOperator.EQUALS,
+ is_monotonic: bool = False,
+ partition_column: str | None = None,
+) -> dict[str, Any]:
+ """
+ Evaluate a candidate mapping and describe the predicate it would emit.
+
+ Shares the evaluator -- and therefore the probe cache -- with the query
+ path, so preview and runtime cannot drift and a previewed transform warms
+ the chart path for free. The predicate itself comes from
+ `build_mirrored_predicates`, the same builder the query path uses, so
+ operator shapes cannot drift either: what the panel shows is what a chart
+ would emit.
+
+ Validation runs first and the engine second: a half-typed transform is by
+ definition unparseable, so most of what a text input produces costs zero
+ queries.
+
+ Every part of the mapping is taken from the request rather than the stored
+ dataset. The editor previews while the owner is still editing -- a mapping
+ that has to be saved before it can be checked is not a preview.
+ """
+ partition_column = partition_column or datasource.partition_column
+ if not partition_column:
+ return {
+ "valid": False,
+ "reason": "unconfigured",
+ "error": _("No partition column is set."),
+ }
+
+ columns_by_name = {str(column.column_name): column for column in datasource.columns}
+ if mapped_column not in columns_by_name:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _("%(name)s is not a column on this dataset.", name=mapped_column),
+ }
+
+ # The bail-out `resolve_partition_mapping` makes at query time, and that
+ # `partition_filter_mapping_summary` repeats for the Explore indicator.
+ # Without it here, preview reports a valid emitted predicate for a mapping
+ # no chart will ever mirror -- the one answer a preview panel must not give.
+ if has_active_advanced_data_type(columns_by_name[mapped_column]):
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _(
+ "%(name)s has an advanced data type, so its filters are "
+ "translated into their own predicate shape and cannot be "
+ "mirrored onto the partition column.",
+ name=mapped_column,
+ ),
+ }
+
+ engine = datasource.database.backend
+ for issue in validate_partition_mapping(
+ column_names=set(columns_by_name),
+ partition_column=str(partition_column),
+ partition_mapped_column=mapped_column,
+ main_dttm_col=datasource.main_dttm_col,
+ transform=value_transform,
+ engine=engine,
+ ):
+ return {
+ "valid": False,
+ # The parse failure is the one an owner sees constantly, and it is
+ # the only one the mockup gives its own headline to.
+ "reason": (
+ "parse"
+ if issue.field == "partition_value_transform"
+ and not is_parseable(value_transform, engine)
+ else "validation"
+ ),
+ "error": str(issue.message),
+ }
+
+ # The policy every other stored expression goes through. The save path
+ # applies it in `UpdateDatasetCommand._validate_partition_mapping`, but
+ # preview evaluates a candidate transform that has not been saved, so
+ # without this the gate had a door around it. See
+ # `stored_expression_error` for what is being kept out and why.
+ if reason := stored_expression_error(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ cast(str, value_transform),
+ ):
+ return {"valid": False, "reason": "validation", "error": reason}
+
+ mapping = PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=mapped_column,
+ value_transform=cast(str, value_transform),
+ is_monotonic=is_monotonic,
+ equality_is_safe=equality_mirrors_safely(
+ columns_by_name[mapped_column], datasource.database.db_engine_spec
+ ),
+ )
+ sample_input = _render_sample_input(
+ datasource, mapped_column, operator, sample_values
+ )
+
+ if operator not in PREVIEWABLE_OPERATORS:
+ # Checked before `mirrors`, which lets `TEMPORAL_RANGE` through when the
+ # transform is declared monotonic -- and the single sample value would
+ # then reach `handle_comparison_filter`, which has no case for a range
+ # and raises. The request schema rejects it too; this keeps the function
+ # honest for any other caller.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is mirrored as a pair of bounds, which "
+ "a preview of a single value cannot describe.",
+ operator=operator.value,
+ ),
+ }
+
+ if not mapping.mirrors(operator):
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is only mirrored when the transform "
+ "preserves ordering, which this one is not declared to do.",
+ operator=operator.value,
+ ),
+ }
+
+ value: Any = sample_values if operator == FilterOperator.IN else sample_values[0]
Review Comment:
Fixed. `_probe_input` coerces the samples through `filter_values_handler` — the same function the query path uses — before the probe, so `typeof(:value)` on a numeric column previews what the chart emits, and the two now share a `_probe_cache_key` entry instead of missing each other's.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "hughhhh (via GitHub)" <gi...@apache.org>.
hughhhh commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4319659878
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/DatasourceEditor.tsx:
##########
@@ -1250,6 +1356,124 @@ function DatasourceEditor({
[],
);
+ // Which column's row expand to open, for the "map a different column" links.
+ // Consumed by the Columns tab, which scrolls the row into view and expands it.
+ //
+ // Carries a nonce because the request is an event, not a state: clicking the
+ // same link twice -- after collapsing the row by hand in between -- asks for
+ // the same column name, and a bare string would make the second
+ // `setColumnToReveal` a no-op. React would bail out of the render, nothing
+ // downstream would see a change, and the row would stay shut.
+ const [columnToReveal, setColumnToReveal] = useState<{
+ name: string;
+ nonce: number;
+ } | null>(null);
+
+ const handlePartitionColumnChange = useCallback(
+ (columnName: string | null) => {
+ setDatasource(prev => ({
+ ...prev,
+ partition_column: columnName,
+ partition_mapped_column: nextMappedColumnOverride(
+ prev.partition_mapped_column,
+ columnName,
+ ),
+ }));
+ if (columnName) {
+ setDatabaseColumns(prev =>
+ applyPartitionColumnDefaults(prev, columnName),
Review Comment:
Fixed. Everything past the `await` reads `currentColumnsRef.current` and `datasourceRef.current` rather than the closure, so the response merges against the live column state instead of the snapshot taken when the sync started.
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/DatasourceEditor.tsx:
##########
@@ -1250,6 +1373,143 @@ function DatasourceEditor({
[],
);
+ // Which column's row expand to open, for the "map a different column" links.
+ // Consumed by the Columns tab, which scrolls the row into view and expands it.
+ //
+ // Carries a nonce because the request is an event, not a state: clicking the
+ // same link twice -- after collapsing the row by hand in between -- asks for
+ // the same column name, and a bare string would make the second
+ // `setColumnToReveal` a no-op. React would bail out of the render, nothing
+ // downstream would see a change, and the row would stay shut.
+ const [columnToReveal, setColumnToReveal] = useState<{
+ name: string;
+ nonce: number;
+ } | null>(null);
+
+ // What the mapped column's own preview said, relayed up from its row expand
+ // so the dataset-level banner cannot claim a mirror that panel has already
+ // refused. Reported rather than lifted: the transform the preview judges is
+ // the debounced local one that panel owns. `null` means no verdict yet.
+ const [previewMirrors, setPreviewMirrors] = useState<boolean | null>(null);
+
+ const handlePartitionColumnChange = useCallback(
+ (columnName: string | null) => {
+ setDatasource(prev => ({
+ ...prev,
+ partition_column: columnName,
+ partition_mapped_column: nextMappedColumnOverride(
+ prev.partition_mapped_column,
+ columnName,
+ ),
+ }));
+ if (columnName) {
+ setDatabaseColumns(prev =>
+ applyPartitionColumnDefaults(prev, columnName),
+ );
+ }
+ },
+ [],
+ );
+
+ const handleNavigateToColumn = useCallback((columnName: string) => {
+ setActiveTabKey(TABS_KEYS.COLUMNS);
Review Comment:
Fixed. The tabs are controlled with `activeKey={activeTabKey}` rather than `defaultActiveKey`, so `handleNavigateToColumn` actually moves the user to the Columns tab.
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/DatasourceEditor.tsx:
##########
@@ -1250,6 +1356,124 @@ function DatasourceEditor({
[],
);
+ // Which column's row expand to open, for the "map a different column" links.
+ // Consumed by the Columns tab, which scrolls the row into view and expands it.
+ //
+ // Carries a nonce because the request is an event, not a state: clicking the
+ // same link twice -- after collapsing the row by hand in between -- asks for
+ // the same column name, and a bare string would make the second
+ // `setColumnToReveal` a no-op. React would bail out of the render, nothing
+ // downstream would see a change, and the row would stay shut.
+ const [columnToReveal, setColumnToReveal] = useState<{
+ name: string;
+ nonce: number;
+ } | null>(null);
+
+ const handlePartitionColumnChange = useCallback(
+ (columnName: string | null) => {
+ setDatasource(prev => ({
+ ...prev,
+ partition_column: columnName,
+ partition_mapped_column: nextMappedColumnOverride(
+ prev.partition_mapped_column,
+ columnName,
+ ),
+ }));
+ if (columnName) {
+ setDatabaseColumns(prev =>
+ applyPartitionColumnDefaults(prev, columnName),
+ );
+ }
+ },
+ [],
+ );
+
+ const handleNavigateToColumn = useCallback((columnName: string) => {
+ setActiveTabKey(TABS_KEYS.COLUMNS);
+ // Filter to the column as well as expanding it: on a wide table the row
+ // would otherwise open somewhere below the fold, which reads as the link
+ // having done nothing.
+ setColumnSearchTerm(columnName);
+ setColumnToReveal(previous => ({
+ name: columnName,
+ nonce: (previous?.nonce ?? 0) + 1,
+ }));
+ }, []);
+
+ const handleMoveMappingHere = useCallback(
+ (columnName: string) => {
+ setDatabaseColumns(prev =>
+ applyMappingMove(
+ prev,
+ columnName,
+ defaultTransformFor(
+ datasource,
+ prev.find(column => column.column_name === columnName),
+ ),
+ ),
+ );
+ // Always explicit from here: the owner picked this column, so the mapping
+ // must not drift back the next time the default datetime column moves.
+ setDatasource(prev => ({ ...prev, partition_mapped_column: columnName }));
+ },
+ [datasource],
+ );
+
+ const handleRemoveMapping = useCallback(() => {
+ // Every column, not just the one that resolved as mapped: with the override
+ // gone the mapping falls back to the default datetime column, so a
+ // transform left anywhere else would come straight back to life -- which is
+ // the one thing "remove" has to rule out. `main_dttm_col` can name a
+ // calculated column, so both lists are cleared.
+ setDatabaseColumns(prev => clearMappingTransforms(prev));
+ setCalculatedColumns(prev => clearMappingTransforms(prev));
+ // The partition column stays designated; only the mapping goes away, which
+ // is the 1g state -- hidden from Explore, nothing mirrored onto it, and the
+ // panel's warning saying so.
+ setDatasource(prev => ({ ...prev, partition_mapped_column: null }));
+ }, []);
+
+ const handleMonotonicChange = useCallback(
+ (columnName: string, isMonotonic: boolean) => {
+ setDatabaseColumns(prev =>
+ prev.map(column =>
+ column.column_name === columnName
+ ? { ...column, partition_transform_is_monotonic: isMonotonic }
+ : column,
+ ),
+ );
+ },
+ [],
+ );
+
+ const handleMainDttmColChange = useCallback(
+ (value?: string) => {
+ // Without an override the mapped column *is* the default datetime column,
+ // so re-pointing it moves the mapping. The value transform stays behind
+ // and is cleared: it was written about the old column, and the mapping
+ // arrives inert rather than mirroring an expression nobody checked
+ // against its new home. Tested on the partition column plus the absent
+ // override rather than on `mappedColumnIsImplicit`, which needs a
+ // datetime column already set and so misses the transition that sets the
+ // first one.
+ if (datasource.partition_column && !datasource.partition_mapped_column) {
Review Comment:
Fixed. The clearing branch is now behind `isFeatureEnabled(FeatureFlag.PartitionFilterMapping)`, so with the feature off a datetime-column change leaves the stored transform and monotonicity flag alone.
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/DatasourceEditor.tsx:
##########
@@ -617,100 +674,160 @@ function ColumnCollectionTable({
/>
);
- return (
- <CollectionTable
- tableColumns={tableColumns}
- sortColumns={tableColumns}
- allowDeletes
- allowAddItem={allowAddItem}
- itemGenerator={itemGenerator}
- collection={columns}
- columnLabelTooltips={columnLabelTooltips}
- filterTerm={filterTerm}
- filterFields={filterFields}
- stickyHeader
- expandFieldset={
- <FormContainer>
- <Fieldset compact>
- {showExpression && (
- <Field
- fieldKey="expression"
- label={t('SQL expression')}
- control={
- <TextAreaControl
- language="sql"
- offerEditInModal={false}
- maxLines={25}
- debounceDelay={300}
- />
- }
- />
- )}
- <Field
- fieldKey="verbose_name"
- label={t('Label')}
- control={
- <TextControl
- controlId="verbose_name"
- placeholder={t('Label')}
- />
- }
+ const partitionMappingEnabled =
+ isFeatureEnabled(FeatureFlag.PartitionFilterMapping) && Boolean(datasource);
+ const partitionColumn = partitionMappingEnabled
+ ? datasource?.partition_column
+ : null;
+
+ // The two `itemRenderers` variants below differ only in which widget edits
+ // the name, so the certified badge and the PARTITION tag are shared here
+ // rather than written out four times.
+ const renderColumnName =
+ (EditControl: 'editableTitle' | 'textControl') =>
+ (
+ v: unknown,
+ onItemChange: (value: any) => void,
+ _: unknown,
+ record: Column,
+ ): ReactNode => (
+ <StyledLabelWrapper>
+ {record.is_certified && (
+ <CertifiedBadge
+ certifiedBy={record.certified_by}
+ details={record.certification_details}
+ />
+ )}
+ {editableColumnName ? (
+ EditControl === 'editableTitle' ? (
+ <EditableTitle
+ canEdit
+ title={v as string}
+ onSaveTitle={onItemChange}
/>
- <Field
- fieldKey="description"
- label={t('Description')}
- control={
- <TextControl
- controlId="description"
- placeholder={t('Description')}
+ ) : (
+ <TextControl value={v as string} onChange={onItemChange} />
+ )
+ ) : (
+ (v as ReactNode)
+ )}
+ {partitionColumn === record.column_name && (
+ <Tooltip
+ title={t(
+ 'Filters on the mapped column are mirrored onto this column so the engine can prune partitions.',
+ )}
+ >
+ <Label data-test="partition-tag">
+ <Icons.FilterOutlined iconSize="s" /> {t('PARTITION')}
+ </Label>
+ </Tooltip>
+ )}
+ </StyledLabelWrapper>
+ );
+
+ return (
+ <StyledColumnsTableWrapper>
+ <CollectionTable
+ tableColumns={tableColumns}
+ sortColumns={tableColumns}
+ allowDeletes
+ allowAddItem={allowAddItem}
+ itemGenerator={itemGenerator}
+ collection={columns}
+ columnLabelTooltips={columnLabelTooltips}
+ filterTerm={filterTerm}
+ filterFields={filterFields}
+ rowClassName={record =>
+ partitionColumn === record.column_name ? 'partition-column-row' : ''
+ }
+ expandItemWhere={
Review Comment:
Fixed. The `expandItemWhere` and reveal props are back on the collection table, so Customize the value transform opens the mapped column's row rather than only filtering to it.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4342087594
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/utils.test.ts:
##########
@@ -0,0 +1,1082 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import {
+ applyImplicitMappingMove,
+ applyMappingMove,
+ clearMappingTransforms,
+ clearUnmappedTransforms,
+ clearUnmappedTransformsAcrossMove,
+ defaultTransformFor,
+ mappedColumnIsImplicit,
+ mappingIsActive,
+ nextMappedColumnOverride,
+ partitionMappingErrors,
+ partitionRowState,
+ previewOperatorFor,
+ sampleValuesFor,
+ resolveMappedColumn,
+ suggestedMappedColumn,
+ transformCanPreview,
+ valueTransformIssues,
+} from './utils';
+import type { PartitionMappingColumn } from './types';
+
+const COLUMNS = [
+ {
+ column_name: 'event_time',
+ type: 'TIMESTAMP',
+ is_dttm: true,
+ filterable: true,
+ groupby: true,
+ },
+ { column_name: 'dt_epoch', type: 'BIGINT', filterable: true, groupby: true },
+ { column_name: 'country', type: 'TEXT', filterable: true, groupby: true },
+];
+
+/** Mapping `event_time` onto the `dt_epoch` partition, with no override. */
+const MAPPED_TO_EVENT_TIME = {
+ main_dttm_col: 'event_time',
+ partition_column: 'dt_epoch',
+ partition_mapped_column: null,
+};
+
+test('the mapped column follows the default datetime column', () => {
+ const datasource = {
+ main_dttm_col: 'event_time',
+ partition_column: 'dt_epoch',
+ partition_mapped_column: null,
+ };
+
+ expect(resolveMappedColumn(datasource)).toBe('event_time');
+ expect(mappedColumnIsImplicit(datasource)).toBe(true);
+});
+
+test('an explicit override wins over the default datetime column', () => {
+ const datasource = {
+ main_dttm_col: 'event_time',
+ partition_column: 'region_key',
+ partition_mapped_column: 'country',
+ };
+
+ expect(resolveMappedColumn(datasource)).toBe('country');
+ expect(mappedColumnIsImplicit(datasource)).toBe(false);
+});
+
+test('there is no mapped column without a partition column', () => {
+ expect(
+ resolveMappedColumn({
+ main_dttm_col: 'event_time',
+ partition_column: null,
+ }),
+ ).toBeNull();
+});
+
+test('a partition column with no datetime column maps to nothing', () => {
+ // Wireframe 1g: a partition column is designated but nothing mirrors onto it.
+ const datasource = { main_dttm_col: null, partition_column: 'dt_epoch' };
+
+ expect(resolveMappedColumn(datasource)).toBeNull();
+ expect(mappingIsActive(datasource, COLUMNS)).toBe(false);
+});
+
+test('a mapping without a transform is configured but inert', () => {
+ const datasource = {
+ main_dttm_col: 'event_time',
+ partition_column: 'dt_epoch',
+ };
+
+ expect(mappingIsActive(datasource, COLUMNS)).toBe(false);
+});
+
+test('a mapping with a transform is active', () => {
+ const datasource = {
+ main_dttm_col: 'event_time',
+ partition_column: 'dt_epoch',
+ };
+ const columns = COLUMNS.map(column =>
+ column.column_name === 'event_time'
+ ? { ...column, partition_value_transform: 'unix_timestamp(:value)' }
+ : column,
+ );
+
+ expect(mappingIsActive(datasource, columns)).toBe(true);
+});
+
+test('a whitespace-only transform does not count as active', () => {
+ const datasource = {
+ main_dttm_col: 'event_time',
+ partition_column: 'dt_epoch',
+ };
+ const columns = COLUMNS.map(column =>
+ column.column_name === 'event_time'
+ ? { ...column, partition_value_transform: ' ' }
+ : column,
+ );
+
+ expect(mappingIsActive(datasource, columns)).toBe(false);
+});
+
+test('each column gets one of the three row treatments', () => {
+ const datasource = {
+ main_dttm_col: 'event_time',
+ partition_column: 'dt_epoch',
+ };
+
+ expect(partitionRowState(datasource, 'event_time')).toBe('mapped');
+ expect(partitionRowState(datasource, 'country')).toBe('unmapped');
+ expect(partitionRowState(datasource, 'dt_epoch')).toBe('partition');
+});
+
+test('no column has a row treatment without a partition column', () => {
+ expect(partitionRowState({ main_dttm_col: 'event_time' }, 'event_time')).toBe(
+ 'none',
+ );
+});
+
+test('moving the mapping discards the previous transform', () => {
+ // Both cardinalities are one, so reassignment replaces rather than
+ // accumulating a second mapping.
+ const columns = [
+ {
+ column_name: 'event_time',
+ is_dttm: true,
+ partition_value_transform: 'unix_timestamp(:value)',
+ partition_transform_is_monotonic: true,
+ },
+ { column_name: 'country' },
+ ];
+
+ const moved = applyMappingMove(MAPPED_TO_EVENT_TIME, columns, 'country', '');
+
+ expect(moved[0]).toMatchObject({
+ partition_value_transform: null,
+ partition_transform_is_monotonic: false,
+ });
+});
+
+test('moving the mapping clears a transform on any column, not just the last one', () => {
+ // Reaching "no mapping" and then mapping a new column must not leave the
+ // old transform behind to come back to life later.
+ const columns = [
+ {
+ column_name: 'event_time',
+ partition_value_transform: 'unix_timestamp(:value)',
+ partition_transform_is_monotonic: true,
+ },
+ { column_name: 'country' },
+ ];
+
+ const moved = applyMappingMove(
+ MAPPED_TO_EVENT_TIME,
+ columns,
+ 'country',
+ 'lower(:value)',
+ );
+
+ expect(moved[0].partition_value_transform).toBeNull();
+ expect(moved[1].partition_value_transform).toBe('lower(:value)');
+});
+
+test('moving the mapping pre-fills the new column when we have a default', () => {
+ const columns: PartitionMappingColumn[] = [
+ { column_name: 'event_time', is_dttm: true },
+ ];
+
+ const moved = applyMappingMove(
+ { main_dttm_col: null, partition_column: 'dt_epoch' },
+ columns,
+ 'event_time',
+ 'unix_timestamp(:value)',
+ );
+
+ expect(moved[0].partition_value_transform).toBe('unix_timestamp(:value)');
+});
+
+test('moving the mapping does not pick up a leftover transform', () => {
+ // The mapping has one mirrored column, so a transform on any *other* column
+ // is a leftover some writer stranded there -- not an expression written about
+ // this column. Picking it up made "Move mapping to this column" a live
+ // mapping with no typing, emitting predicates nobody authored while the
+ // pruning indicator stayed green: NEW-R11-01.
+ const columns = [
+ { column_name: 'event_time', is_dttm: true },
+ {
+ column_name: 'country',
+ partition_value_transform: 'lower(:value)',
+ partition_transform_is_monotonic: true,
+ },
+ ];
+
+ const moved = applyMappingMove(MAPPED_TO_EVENT_TIME, columns, 'country', '');
+
+ expect(moved[1]).toMatchObject({
+ partition_value_transform: null,
+ partition_transform_is_monotonic: false,
+ });
+});
+
+test('moving the mapping installs the engine default over a leftover', () => {
+ // The move is not refused, only disarmed: it arrives holding whatever the
+ // engine offers, which is the same thing a clean column would get.
+ const columns = [
+ { column_name: 'event_time', is_dttm: true },
+ {
+ column_name: 'other_time',
+ is_dttm: true,
+ partition_value_transform: 'to_unixtime(:value)',
+ partition_transform_is_monotonic: true,
+ },
+ ];
+
+ const moved = applyMappingMove(
+ MAPPED_TO_EVENT_TIME,
+ columns,
+ 'other_time',
+ 'unix_timestamp(:value)',
+ );
+
+ expect(moved[1]).toMatchObject({
+ partition_value_transform: 'unix_timestamp(:value)',
+ partition_transform_is_monotonic: false,
+ });
+});
+
+test('re-selecting the column already mapped keeps its transform', () => {
+ const columns = [
+ {
+ column_name: 'event_time',
+ partition_value_transform: 'unix_timestamp(:value)',
+ partition_transform_is_monotonic: true,
+ },
+ ];
+
+ const moved = applyMappingMove(
+ MAPPED_TO_EVENT_TIME,
+ columns,
+ 'event_time',
+ '',
+ );
+
+ expect(moved[0]).toMatchObject({
+ partition_value_transform: 'unix_timestamp(:value)',
+ partition_transform_is_monotonic: true,
+ });
+});
+
+test('removing a mapping clears the transform on every column, not just the mapped one', () => {
+ // Removing the override drops the mapping back onto the default datetime
+ // column, so a transform left anywhere else is not dormant -- it is the next
+ // mapping, armed and invisible.
+ const columns = [
+ {
+ column_name: 'event_time',
+ partition_value_transform: 'unix_timestamp(:value)',
+ partition_transform_is_monotonic: true,
+ },
+ {
+ column_name: 'event_time2',
+ partition_value_transform: 'unix_timestamp(:value)',
+ partition_transform_is_monotonic: true,
+ },
+ ];
+
+ const cleared = clearMappingTransforms(columns);
+
+ expect(cleared).toMatchObject([
+ {
+ partition_value_transform: null,
+ partition_transform_is_monotonic: false,
+ },
+ {
+ partition_value_transform: null,
+ partition_transform_is_monotonic: false,
+ },
+ ]);
+});
+
+test('clearing a mapping nothing holds hands back the same columns', () => {
+ // Callers clear unconditionally, and column state's identity is what triggers
+ // the editor's validation pass -- a fresh array every time would run it on
+ // every unrelated edit.
+ const columns = [{ column_name: 'event_time' }, { column_name: 'country' }];
+
+ expect(clearMappingTransforms(columns)).toBe(columns);
+});
+
+test('a transform on a column the mapping does not mirror is cleared', () => {
+ // The editor is not the only writer: a PUT, an `override_columns` sync and an
+ // import all reach the columns directly, so a dataset can arrive already
+ // violating the invariant. The mapped column's own transform stays.
+ const columns = [
+ {
+ column_name: 'event_time',
+ partition_value_transform: 'unix_timestamp(:value)',
+ partition_transform_is_monotonic: true,
+ },
+ {
+ column_name: 'other_time',
+ partition_value_transform: 'to_unixtime(:value)',
+ partition_transform_is_monotonic: true,
+ },
+ ];
+
+ const cleared = clearUnmappedTransforms(MAPPED_TO_EVENT_TIME, columns);
+
+ expect(cleared[0]).toMatchObject({
+ partition_value_transform: 'unix_timestamp(:value)',
+ partition_transform_is_monotonic: true,
+ });
+ expect(cleared[1]).toMatchObject({
+ partition_value_transform: null,
+ partition_transform_is_monotonic: false,
+ });
+});
+
+test('with no mapping at all, no column may hold a transform', () => {
+ const columns = [
+ {
+ column_name: 'event_time',
+ partition_value_transform: 'unix_timestamp(:value)',
+ },
+ ];
+
+ expect(
+ clearUnmappedTransforms({ main_dttm_col: 'event_time' }, columns)[0]
+ .partition_value_transform,
+ ).toBeNull();
+});
+
+test('a sync that re-points the mapping cannot arm what the new column holds', () => {
+ // NEW-R12-01. The mapping sits explicitly on `country`; `event_time` is the
+ // default datetime column and is holding a transform some earlier writer
+ // stranded there. A column sync drops `country`, so the override is repaired
+ // to null and the mapping falls back to `event_time`.
+ //
+ // Asked only about the mapping the repair leaves behind, the invariant reads
+ // `event_time` as the mapped column and keeps its transform -- which then
+ // goes live from a sync nobody typed into: 181 rows instead of 183, 0 instead
+ // of 1 for an equality, and the pruning indicator still green. It has to be
+ // asked on both sides of the move.
+ const before = {
+ main_dttm_col: 'event_time',
+ partition_column: 'dt_epoch',
+ partition_mapped_column: 'country',
+ };
+ const after = { ...before, partition_mapped_column: null };
+ const columns = [
+ {
+ column_name: 'event_time',
+ partition_value_transform: 'unix_timestamp(:value)',
+ partition_transform_is_monotonic: true,
+ },
+ ];
+
+ // The bug, stated as the single-sided answer this replaced.
+ expect(clearUnmappedTransforms(after, columns)[0]).toMatchObject({
+ partition_value_transform: 'unix_timestamp(:value)',
+ });
+
+ expect(
+ clearUnmappedTransformsAcrossMove(before, after, columns)[0],
+ ).toMatchObject({
+ partition_value_transform: null,
+ partition_transform_is_monotonic: false,
+ });
+});
+
+test('a sync that moves nothing leaves the mapped transform alone', () => {
+ // The limit of the rule above: with both sides agreeing on the mapped column
+ // there is no move, and a sync must not cost the owner the transform they
+ // wrote. Only a transform parked elsewhere goes.
+ const datasource = {
+ main_dttm_col: 'event_time',
+ partition_column: 'dt_epoch',
+ partition_mapped_column: null,
+ };
+ const columns = [
+ {
+ column_name: 'event_time',
+ partition_value_transform: 'unix_timestamp(:value)',
+ partition_transform_is_monotonic: true,
+ },
+ {
+ column_name: 'other_time',
+ partition_value_transform: 'to_unixtime(:value)',
+ },
+ ];
+
+ const kept = clearUnmappedTransformsAcrossMove(
+ datasource,
+ datasource,
+ columns,
+ );
+
+ expect(kept[0]).toMatchObject({
+ partition_value_transform: 'unix_timestamp(:value)',
+ partition_transform_is_monotonic: true,
+ });
+ expect(kept[1].partition_value_transform).toBeNull();
+});
+
+test('clearing strays when there are none hands back the same columns', () => {
+ // Same contract as `clearMappingTransforms`, and for the same reason: the
+ // editor's validation pass keys off column state's identity.
+ const columns = [
+ {
+ column_name: 'event_time',
+ partition_value_transform: 'unix_timestamp(:value)',
+ },
+ { column_name: 'country' },
+ ];
+
+ expect(clearUnmappedTransforms(MAPPED_TO_EVENT_TIME, columns)).toBe(columns);
+});
+
+test('the value transform does not follow the default datetime column', () => {
+ // A transform states how *this* column relates to the partition column, so
+ // re-asserting it on a different one turns mirroring on with an expression
+ // nobody wrote for it -- and the rows it prunes are silently wrong.
+ const columns = [
+ {
+ column_name: 'event_time',
+ is_dttm: true,
+ partition_value_transform: 'unix_timestamp(:value)',
+ partition_transform_is_monotonic: true,
+ },
+ { column_name: 'event_time2', is_dttm: true },
+ ];
+
+ const moved = applyImplicitMappingMove(columns, 'event_time', 'event_time2');
+
+ expect(moved[0]).toMatchObject({
+ partition_value_transform: null,
+ partition_transform_is_monotonic: false,
+ });
+ // The destination never held a mapping, so it is handed back untouched --
+ // which is the same thing as holding no transform.
+ expect(moved[1].partition_value_transform ?? null).toBeNull();
+ expect(moved[1].partition_transform_is_monotonic ?? false).toBe(false);
+});
+
+test('following the default datetime column leaves no transform behind anywhere', () => {
+ const columns = [
+ {
+ column_name: 'event_time',
+ partition_value_transform: 'unix_timestamp(:value)',
+ },
+ { column_name: 'event_time2' },
+ {
+ column_name: 'legacy_time',
+ partition_value_transform: 'to_unixtime(:value)',
+ partition_transform_is_monotonic: true,
+ },
+ ];
+
+ const moved = applyImplicitMappingMove(columns, 'event_time', 'event_time2');
+
+ expect(moved[2]).toMatchObject({
+ partition_value_transform: null,
+ partition_transform_is_monotonic: false,
+ });
+});
+
+test('moving the default datetime column onto a column this list has no row for clears too', () => {
+ // A calculated column can be the default datetime column but never renders a
+ // transform editor, so a transform left live there is one the owner has no
+ // way to see or undo.
+ const columns = [
+ {
+ column_name: 'event_time',
+ partition_value_transform: 'unix_timestamp(:value)',
+ partition_transform_is_monotonic: true,
+ },
+ ];
+
+ const moved = applyImplicitMappingMove(columns, 'event_time', 'calc_time');
+
+ expect(moved[0]).toMatchObject({
+ partition_value_transform: null,
+ partition_transform_is_monotonic: false,
+ });
+});
+
+test('moving the default datetime column when nothing holds a mapping is not a change', () => {
+ // `clearMappingTransforms` hands back the same array when no column held
+ // anything, and the editor's validation effect keys off column identity.
+ const columns = [
+ { column_name: 'event_time' },
+ { column_name: 'event_time2' },
+ ];
+
+ expect(applyImplicitMappingMove(columns, 'event_time', 'event_time2')).toBe(
+ columns,
+ );
+});
+
+test('re-selecting the same default datetime column leaves the mapping alone', () => {
+ const columns = [
+ {
+ column_name: 'event_time',
+ partition_value_transform: 'unix_timestamp(:value)',
+ },
+ ];
+
+ expect(applyImplicitMappingMove(columns, 'event_time', 'event_time')).toBe(
+ columns,
+ );
+});
+
+test('clearing the default datetime column clears the mapping transform with it', () => {
+ // With no default datetime column and no override there is no mapped column,
+ // so the transform has nowhere to live and must not wait for one.
+ const columns = [
+ {
+ column_name: 'event_time',
+ partition_value_transform: 'unix_timestamp(:value)',
+ partition_transform_is_monotonic: true,
+ },
+ ];
+
+ const moved = applyImplicitMappingMove(columns, 'event_time', undefined);
+
+ expect(moved[0]).toMatchObject({
+ partition_value_transform: null,
+ partition_transform_is_monotonic: false,
+ });
+});
+
+test('only temporal columns get a pre-filled transform', () => {
+ const datasource = {
+ partition_value_transform_default: 'unix_timestamp(:value)',
+ };
+
+ expect(defaultTransformFor(datasource, COLUMNS[0])).toBe(
+ 'unix_timestamp(:value)',
+ );
+ expect(defaultTransformFor(datasource, COLUMNS[2])).toBe('');
+});
+
+test('a temporal column stored as a number or as text gets no pre-fill', () => {
+ // The engine default takes a timestamp. On an epoch `BIGINT` both Hive and
+ // Impala reject `unix_timestamp(:value)`, so the pre-fill left the mapping
+ // broken until the owner replaced it.
+ const datasource = {
+ partition_value_transform_default: 'unix_timestamp(:value)',
+ };
+ expect(
+ defaultTransformFor(datasource, {
+ column_name: 'event_time',
+ type: 'BIGINT',
+ is_dttm: true,
+ python_date_format: 'epoch_s',
+ }),
+ ).toBe('');
+ expect(
+ defaultTransformFor(datasource, {
+ column_name: 'ds',
+ type: 'STRING',
+ is_dttm: true,
+ python_date_format: '%Y%m%d',
+ }),
+ ).toBe('');
+ expect(
+ defaultTransformFor(datasource, {
+ column_name: 'event_time',
+ type: 'DATETIME',
+ is_dttm: true,
+ }),
+ ).toBe('unix_timestamp(:value)');
+ // An undeclared type keeps the default, as before.
+ expect(
+ defaultTransformFor(datasource, {
+ column_name: 'event_time',
+ is_dttm: true,
+ }),
+ ).toBe('unix_timestamp(:value)');
+});
+
+test('a mapping onto an array partition column is never active', () => {
+ // SC-128852: the banner said filters would apply to `region_keys TEXT[]`,
Review Comment:
Nit: Remove the internal ticket reference from this public test comment.
```suggestion
// The banner said filters would apply to `region_keys TEXT[]`,
```
##########
tests/unit_tests/connectors/sqla/partition_mapping_test.py:
##########
@@ -0,0 +1,3801 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Unit tests for ``superset.connectors.sqla.partition_mapping``."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from decimal import Decimal
+from importlib import import_module
+from typing import Any, cast
+from unittest.mock import MagicMock, patch, PropertyMock
+
+import pandas as pd
+import pytest
+from dateutil.relativedelta import relativedelta
+from flask import Flask
+from pytest_mock import MockerFixture
+from sqlalchemy.dialects import mysql, postgresql
+
+from superset.config import DISALLOWED_SQL_FUNCTIONS
+from superset.connectors.sqla.models import SqlaTable, TableColumn
+from superset.connectors.sqla.partition_mapping import (
+ _mirror_verdict_cache_key,
+ _placeholder_is_bindable,
+ _probe_cache_key,
+ _reads_as_temporal,
+ _render_literal,
+ _render_predicate,
+ BARE_WALL_CLOCK_KEYWORDS,
+ build_mirrored_predicates,
+ build_probe_sql,
+ contains_executable_comment,
+ contains_jinja,
+ contains_value_placeholder,
+ declares_array_type,
+ drop_unmapped_value_transforms,
+ equality_mirrors_safely,
+ evaluate_transform,
+ find_non_deterministic_functions,
+ grain_bucket_width,
+ GRAIN_BUCKET_WIDTHS,
+ is_bare_expression,
+ is_parseable,
+ is_transform_active,
+ is_unfinished,
+ known_mirror_verdict,
+ literal_round_trips,
+ MappingValidationIssue,
+ mirror_operator,
+ MIRRORABLE_ALWAYS,
+ MIRRORABLE_IF_MONOTONIC,
+ mirrorable_operators,
+ NON_DETERMINISTIC_FUNCTIONS,
+ parse_error_detail,
+ placeholder_is_executable,
+ PROBE_CACHE_VERSION,
+ probe_sql_is_evaluable,
+ probed_value_type_error,
+ RawProbeValue,
+ resolve_partition_mapping,
+ stored_expression_error,
+ validate_partition_mapping,
+ validate_transform,
+)
+from superset.constants import TimeGrain
+from superset.db_engine_specs.base import BaseEngineSpec
+from superset.db_engine_specs.mysql import MySQLEngineSpec
+from superset.db_engine_specs.oracle import OracleEngineSpec
+from superset.db_engine_specs.postgres import PostgresEngineSpec
+from superset.models.core import Database
+from superset.sql.parse import SQLStatement
+from superset.utils.core import FilterOperator, GenericDataType, override_user
+
+
+@pytest.fixture(autouse=True)
+def real_probe_cache(app: Flask) -> Any:
+ """
+ The test app runs a null cache, which would make every cache assertion here
+ vacuously pass. Swap in a real in-memory one for the duration.
+ """
+ from flask_caching import Cache
+
+ from superset.extensions import cache_manager
+
+ cache = Cache(config={"CACHE_TYPE": "SimpleCache", "CACHE_DEFAULT_TIMEOUT": 300})
+ cache.init_app(app)
+ original = cache_manager._cache # noqa: SLF001
+ cache_manager._cache = cache # noqa: SLF001
+ yield
+ cache_manager._cache = original # noqa: SLF001
+
+
+@pytest.fixture(autouse=True)
+def enable_partition_filter_mapping(app: Flask) -> Any:
+ """The feature ships off; every test here exercises it on."""
+ original = app.config["DEFAULT_FEATURE_FLAGS"].get("PARTITION_FILTER_MAPPING")
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = True
+ yield
+ if original is None:
+ del app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"]
+ else:
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = original
+
+
+def _table(**kwargs: Any) -> SqlaTable:
+ database = Database(database_name="test_db", sqlalchemy_uri="sqlite://")
+ defaults: dict[str, Any] = {
+ "table_name": "web_events",
+ "database": database,
+ "main_dttm_col": "event_time",
+ "columns": [
+ TableColumn(column_name="event_time", is_dttm=True, type="TIMESTAMP"),
+ TableColumn(
+ column_name="dt_epoch",
+ type="BIGINT",
+ partition_value_transform=None,
+ ),
+ TableColumn(column_name="country", type="VARCHAR"),
+ TableColumn(column_name="region_key", type="VARCHAR"),
+ ],
+ }
+ defaults.update(kwargs)
+ return SqlaTable(**defaults)
+
+
+def _mapped_table(
+ *,
+ partition_column: str = "dt_epoch",
+ mapped_column: str = "event_time",
+ transform: str | None = "unix_timestamp(:value)",
+ monotonic: bool = True,
+ partition_mapped_column: str | None = None,
+ main_dttm_col: str | None = "event_time",
+) -> SqlaTable:
+ table = _table(main_dttm_col=main_dttm_col)
+ table.partition_column = partition_column
+ table.partition_mapped_column = partition_mapped_column
+ for column in table.columns:
+ if column.column_name == mapped_column:
+ column.partition_value_transform = transform
+ column.partition_transform_is_monotonic = monotonic
+ return table
+
+
+# ---------------------------------------------------------------------------
+# §2 — operator safety matrix
+# ---------------------------------------------------------------------------
+
+
+def test_equality_and_in_are_always_mirrorable() -> None:
+ """``=`` and ``IN`` are safe for any function ``T``."""
+ assert MIRRORABLE_ALWAYS == {FilterOperator.EQUALS, FilterOperator.IN}
+
+
+def test_range_operators_require_a_monotonic_transform() -> None:
+ assert MIRRORABLE_IF_MONOTONIC == {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+ }
+
+
+def test_mirrorable_operators_excludes_ranges_when_not_monotonic() -> None:
+ assert mirrorable_operators(is_monotonic=False) == MIRRORABLE_ALWAYS
+
+
+def test_mirrorable_operators_includes_ranges_when_monotonic() -> None:
+ assert mirrorable_operators(is_monotonic=True) == (
+ MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+ )
+
+
+@pytest.mark.parametrize(
+ "operator",
+ [
+ FilterOperator.NOT_EQUALS,
+ FilterOperator.NOT_IN,
+ FilterOperator.LIKE,
+ FilterOperator.ILIKE,
+ FilterOperator.NOT_LIKE,
+ FilterOperator.NOT_ILIKE,
+ FilterOperator.IS_NULL,
+ FilterOperator.IS_NOT_NULL,
+ FilterOperator.IS_TRUE,
+ FilterOperator.IS_FALSE,
+ ],
+)
+def test_negations_and_pattern_matches_are_never_mirrorable(
+ operator: FilterOperator,
+) -> None:
+ """
+ ``T`` is not injective, so ``col != v`` does **not** imply ``T(col) != T(v)``:
+ mirroring it would drop rows the original filter keeps.
+ """
+ assert operator not in mirrorable_operators(is_monotonic=True)
+
+
+def test_equality_is_dropped_when_the_engine_does_not_compare_byte_exactly() -> None:
+ """
+ "Safe for any function ``T``" reasons about value equality: ``T`` is a
+ function, so ``col = v`` gives ``T(col) = T(v)``. The engine reasons about
+ *SQL* equality, and the two part company under a case-insensitive
+ collation -- a stored ``'us'`` satisfies a filter for ``'US'`` while the
+ mirror ``hex('US')`` excludes the row, and the chart loses it silently.
+ """
+ assert mirrorable_operators(is_monotonic=False, equality_is_safe=False) == set()
+
+
+def test_ranges_survive_an_unsafe_equality() -> None:
+ """
+ Range mirroring already rests on the owner declaring ``T``
+ order-preserving with respect to the column's own order -- an assertion
+ about the very comparison semantics this gate checks for. Equality has no
+ such declaration behind it, which is why only equality is withdrawn.
+ """
+ assert (
+ mirrorable_operators(is_monotonic=True, equality_is_safe=False)
+ == MIRRORABLE_IF_MONOTONIC
+ )
+
+
+@pytest.mark.parametrize(
+ "operator,expected",
+ [
+ (FilterOperator.GREATER_THAN, FilterOperator.GREATER_THAN_OR_EQUALS),
+ (FilterOperator.LESS_THAN, FilterOperator.LESS_THAN_OR_EQUALS),
+ (
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ ),
+ (FilterOperator.LESS_THAN_OR_EQUALS, FilterOperator.LESS_THAN_OR_EQUALS),
+ (FilterOperator.EQUALS, FilterOperator.EQUALS),
+ (FilterOperator.IN, FilterOperator.IN),
+ ],
+)
+def test_a_strict_bound_mirrors_non_strictly(
+ operator: FilterOperator, expected: FilterOperator
+) -> None:
+ """
+ Order-preserving means non-decreasing, not injective, so ``col < v``
+ implies only ``T(col) <= T(v)``. A day-key transform maps a whole day onto
+ one value and a strict mirror drops the boundary bucket. The non-strict
+ cases are already safe and pass through, which is what makes applying this
+ twice harmless.
+ """
+ assert mirror_operator(operator) == expected
+
+
+def test_relaxing_a_bound_stays_inside_the_mirrorable_set() -> None:
+ """
+ The substitution is about strictness, not about which filters mirror. The
+ Explore indicator reads `mirrorable_operators`, so leaving that set alone is
+ what keeps the glyph from promising pruning the SQL does not do -- and it is
+ also what guarantees `handle_comparison_filter` is never handed an operator
+ it has no case for.
+ """
+ assert {
+ mirror_operator(operator) for operator in MIRRORABLE_IF_MONOTONIC
+ } <= MIRRORABLE_IF_MONOTONIC
+
+
+def _column(type_: str) -> TableColumn:
+ database = Database(database_name="t", sqlalchemy_uri="sqlite://")
+ table = SqlaTable(table_name="t", database=database)
+ return TableColumn(column_name="c", type=type_, table=table)
+
+
+@pytest.mark.parametrize(
+ "type_, binary, expected",
+ [
+ ("VARCHAR", True, True),
+ ("VARCHAR", False, False),
+ # Numeric and temporal comparison is exact everywhere.
+ ("BIGINT", False, True),
+ ("TIMESTAMP", False, True),
+ ("DOUBLE", False, True),
+ ],
+)
+def test_equality_mirrors_safely_only_guards_string_columns(
+ app: Flask, type_: str, binary: bool, expected: bool
+) -> None:
+ class _Spec(BaseEngineSpec):
+ binary_string_comparison = binary
+
+ with app.app_context():
+ assert equality_mirrors_safely(_column(type_), _Spec) is expected
+
+
+@pytest.mark.parametrize(
+ "type_, expected",
+ [
+ # The padded types: `'US'` and `'US '` are equal in the column, and
+ # `lower()` of the two is not.
+ ("CHAR(2)", False),
+ ("CHAR", False),
+ ("CHARACTER(2)", False),
+ ("NCHAR(2)", False),
+ # What PostgreSQL reflection reports for a `CHAR(n)` column.
+ ("BPCHAR", False),
+ ("bpchar(2)", False),
+ ("NATIONAL CHARACTER(2)", False),
+ # The variable-width types start with the same letters and must not be
+ # caught by it.
+ ("VARCHAR(2)", True),
+ ("NVARCHAR(2)", True),
+ ("CHARACTER VARYING(2)", True),
+ ("TEXT", True),
+ ],
+)
+def test_a_padded_character_column_declines_equality_on_a_byte_exact_engine(
+ app: Flask, type_: str, expected: bool
+) -> None:
+ """
+ `binary_string_comparison` speaks for the engine's default comparison,
+ which PostgreSQL declares -- and a `CHAR(2)` there still matches a filter
+ for `'US '` against a stored `'US'`, so the mirror `lower('US ')` excludes
+ the row. Padding is a property of the type, so it is asked per column.
+ """
+
+ class _Spec(BaseEngineSpec):
+ binary_string_comparison = True
+
+ with app.app_context():
+ assert equality_mirrors_safely(_column(type_), _Spec) is expected
+
+
+def test_redshift_does_not_opt_in_to_byte_exact_comparison() -> None:
+ """
+ Redshift ignores trailing blanks for `VARCHAR` as well as `CHAR`, so the
+ `True` it inherits from `PostgresBaseEngineSpec` would be wrong.
+ """
+ from superset.db_engine_specs.redshift import RedshiftEngineSpec
+
+ assert RedshiftEngineSpec.binary_string_comparison is False
+
+
+@pytest.mark.parametrize(
+ "type_",
+ [
+ # PostgreSQL's case-insensitive text type matches no type pattern, so
+ # the spec cannot classify it -- and its whole purpose is the
+ # comparison this gate is about.
+ "citext",
+ # A column with no declared type at all.
+ "",
+ "SOME_EXTENSION_TYPE",
+ ],
+)
+def test_equality_mirrors_safely_fails_closed_on_an_unresolvable_type(
+ app: Flask, type_: str
+) -> None:
+ """
+ The gate exists to stop a silent wrong answer, so a column whose type it
+ cannot read is treated as the risky case rather than waved through.
+
+ `type_generic` answers `None` for these -- neither string nor not-string --
+ and the old reading waved them through, which for `citext` admitted exactly
+ the case-insensitive equality the gate is for. Only the exception branch
+ failed closed, though the docstring claimed otherwise.
+ """
+ with app.app_context():
+ assert equality_mirrors_safely(_column(type_), PostgresEngineSpec) is False
+
+
+def test_equality_mirrors_safely_reads_past_the_temporal_flag(app: Flask) -> None:
+ """
+ `TableColumn.type_generic` answers `TEMPORAL` for anything carrying
+ `is_dttm`, so a `VARCHAR` flagged temporal skipped the string check
+ entirely: on MySQL a filter for `'2026-01-01T00:00:00'` matches a stored
+ `'...t00:00:00'` while the mirror `hex('...T...')` excludes it.
+ """
+ with app.app_context():
+ flagged = _column("VARCHAR")
+ flagged.is_dttm = True
+ assert flagged.type_generic == GenericDataType.TEMPORAL
+ # Declines where plain text declines...
+ assert equality_mirrors_safely(flagged, MySQLEngineSpec) is False
+ # ...and is admitted where plain text is admitted.
+ assert equality_mirrors_safely(flagged, PostgresEngineSpec) is True
+
+ # A column that really is temporal is unaffected.
+ real = _column("TIMESTAMP")
+ real.is_dttm = True
+ assert equality_mirrors_safely(real, MySQLEngineSpec) is True
+
+
+def test_no_mapped_column_leaves_the_matrix_alone(app: Flask) -> None:
+ """Nothing to reason about, and the resolver bails out on it anyway."""
+ with app.app_context():
+ assert equality_mirrors_safely(None, BaseEngineSpec) is True
+
+
+@pytest.mark.parametrize(
+ "module, spec_name",
+ [
+ ("presto", "PrestoEngineSpec"),
+ ("hive", "HiveEngineSpec"),
+ ("trino", "TrinoEngineSpec"),
+ ("impala", "ImpalaEngineSpec"),
+ ("postgres", "PostgresEngineSpec"),
+ ("bigquery", "BigQueryEngineSpec"),
+ ("sqlite", "SqliteEngineSpec"),
+ ],
+)
+def test_the_byte_exact_engines_opt_in(module: str, spec_name: str) -> None:
+ """
+ The engines this feature targets compare text byte-exactly, so the gate
+ must not cost them the second canonical mapping (`lower(:value)` onto a
+ lowercased key).
+ """
+ spec = getattr(import_module(f"superset.db_engine_specs.{module}"), spec_name)
+ assert spec.binary_string_comparison is True
+
+
+@pytest.mark.parametrize("module, spec_name", [("mysql", "MySQLEngineSpec")])
+def test_a_case_insensitive_engine_does_not_opt_in(module: str, spec_name: str) -> None:
+ """
+ MySQL's default collation is `utf8mb4_0900_ai_ci`, which is exactly the
+ case the reviewer raised.
+ """
+ spec = getattr(import_module(f"superset.db_engine_specs.{module}"), spec_name)
+ assert spec.binary_string_comparison is False
+
+
+def test_the_base_spec_does_not_opt_in() -> None:
+ """A spec that has not said so does not mirror string equality."""
+ assert BaseEngineSpec.binary_string_comparison is False
+
+
+# ---------------------------------------------------------------------------
+# Time grain bucket widths
+# ---------------------------------------------------------------------------
+
+
+@pytest.mark.parametrize("grain", list(TimeGrain))
+def test_every_builtin_grain_has_a_known_bucket_width(
+ app: Flask, grain: TimeGrain
+) -> None:
+ """
+ The widening is only sound for a grain whose bucket width we know, so a
+ grain added upstream without a width here would silently stop mirroring.
+ This is the test that notices.
+ """
+ with app.app_context():
+ assert grain_bucket_width(grain.value, "sqlite") is not None
+
+
+def test_a_calendar_grain_widens_by_a_calendar_month(app: Flask) -> None:
+ """A month is not thirty days, and the month it lands in decides its width."""
+ with app.app_context():
+ width = grain_bucket_width(TimeGrain.MONTH.value, "sqlite")
+
+ assert width is not None
+ assert datetime(2026, 1, 31) + width == datetime(2026, 2, 28)
+ assert datetime(2026, 2, 1) + width == datetime(2026, 3, 1)
+
+
+def test_a_fractional_grain_has_a_width(app: Flask) -> None:
+ """
+ ``PT0.5H`` and ``P0.25Y`` are why the widths are written out rather than
+ parsed -- and the anchored week grains are intervals ``parse_duration``
+ rejects outright.
+ """
+ with app.app_context():
+ assert grain_bucket_width(TimeGrain.HALF_HOUR.value, "sqlite") == relativedelta(
+ minutes=30
+ )
+ assert grain_bucket_width(
+ TimeGrain.WEEK_ENDING_SATURDAY.value, "sqlite"
+ ) == relativedelta(days=7)
+
+
+def test_an_unknown_grain_has_no_known_width(app: Flask) -> None:
+ with app.app_context():
+ assert grain_bucket_width("P13X", "sqlite") is None
+ assert grain_bucket_width(None, "sqlite") is None
+
+
+def test_an_addon_grain_has_no_known_width(app: Flask) -> None:
+ """An operator-declared grain carries whatever duration string they typed."""
+ with app.app_context():
+ app.config["TIME_GRAIN_ADDONS"] = {"PT2S": "2 second"}
+ try:
+ assert grain_bucket_width("PT2S", "sqlite") is None
+ finally:
+ app.config["TIME_GRAIN_ADDONS"] = {}
+
+
+def test_a_builtin_grain_an_operator_redefined_has_no_known_width(
+ app: Flask,
+) -> None:
+ """
+ ``TIME_GRAIN_ADDON_EXPRESSIONS`` replaces a built-in grain's SQL for one
+ engine, so its duration no longer bounds the displacement *there* -- but it
+ still does on every other engine.
+ """
+ with app.app_context():
+ app.config["TIME_GRAIN_ADDON_EXPRESSIONS"] = {
+ "sqlite": {"P1D": "DATETIME({col}, 'start of year')"}
+ }
+ try:
+ assert grain_bucket_width(TimeGrain.DAY.value, "sqlite") is None
+ assert grain_bucket_width(TimeGrain.DAY.value, "hive") is not None
+ finally:
+ app.config["TIME_GRAIN_ADDON_EXPRESSIONS"] = {}
+
+
+def test_the_width_table_is_keyed_on_grain_durations(app: Flask) -> None:
+ """Keys are the ISO duration a filter carries, not the enum member name."""
+ assert GRAIN_BUCKET_WIDTHS[TimeGrain.DAY] == relativedelta(days=1)
+ assert set(GRAIN_BUCKET_WIDTHS) == {grain.value for grain in TimeGrain}
+
+
+# ---------------------------------------------------------------------------
+# §4.1 — resolving the effective mapping, and the defensive bail-outs
+# ---------------------------------------------------------------------------
+
+
+def test_resolve_returns_the_mapping_when_everything_lines_up(app: Flask) -> None:
+ with app.app_context():
+ mapping = resolve_partition_mapping(_mapped_table())
+
+ assert mapping is not None
+ assert mapping.partition_column == "dt_epoch"
+ assert mapping.mapped_column == "event_time"
+ assert mapping.value_transform == "unix_timestamp(:value)"
+ assert mapping.is_monotonic is True
+
+
+def test_effective_mapped_column_follows_main_dttm_col(app: Flask) -> None:
+ """No explicit override: the mapping follows the default datetime column."""
+ with app.app_context():
+ mapping = resolve_partition_mapping(_mapped_table())
+
+ assert mapping is not None
+ assert mapping.mapped_column == "event_time"
+
+
+def test_explicit_override_wins_over_main_dttm_col(app: Flask) -> None:
+ table = _mapped_table(
+ mapped_column="country",
+ transform="lower(:value)",
+ monotonic=False,
+ partition_mapped_column="country",
+ )
+ table.partition_column = "region_key"
+
+ with app.app_context():
+ mapping = resolve_partition_mapping(table)
+
+ assert mapping is not None
+ assert mapping.mapped_column == "country"
+ assert mapping.partition_column == "region_key"
+ assert mapping.is_monotonic is False
+
+
+def test_resolve_returns_none_when_the_feature_flag_is_off(app: Flask) -> None:
+ table = _mapped_table()
+ with app.app_context():
+ with patch(
+ "superset.connectors.sqla.partition_mapping.feature_flag_manager."
+ "is_feature_enabled",
+ return_value=False,
+ ):
+ assert resolve_partition_mapping(table) is None
+
+
+def test_an_array_partition_column_resolves_no_mapping(app: Flask) -> None:
+ """
+ SC-128852, page 3: with only the per-value refusal the chart stopped
Review Comment:
Nit: Remove the internal ticket reference from this public test comment.
```suggestion
With only the per-value refusal the chart stopped
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4286686414
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,3417 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Writing the value into the probe
+--------------------------------
+The probe evaluates the transform at a *literal*, because it runs with no bound
+parameters at all -- so every value is written into SQL text by the driver's
+literal renderer and read back by the engine's lexer, and the two do not always
+agree. SQLAlchemy's default renderer doubles apostrophes and leaves backslashes
+alone; Hive honours backslash escapes and not doubling, so ``'O''Brien'`` is
+read there as two adjacent literals and ``'x\\''`` ends four characters into a
+value the filter carries whole. A disagreement is either a mirror built from a
+value nobody filtered on -- dropping rows the filter keeps -- or, where the
+value closes its own quote, an expression of the filterer's choosing running in
+the probe.
+
+Which side is right is not knowable from the driver: it is a per-session server
+setting (``standard_conforming_strings``, ``NO_BACKSLASH_ESCAPES``,
+``spark.sql.parser.escapedStringLiterals``), and SQLAlchemy's own view of it is
+only correct on a dialect that has connected. So escaping is not what makes
+this safe. `literal_round_trips` renders the literal and reads it back in the
+engine's own dialect instead, and a value that does not survive the trip is not
+mirrored -- the usual trade, pruning for correctness. `probe_sql_is_evaluable`
+re-reads the finished statement behind it.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: The opening and closing delimiters of each kind of Jinja block. The probe
+#: would render these in a different context at a different time from the chart
+#: query, so a transform holding one is rejected at save time.
+JINJA_BLOCK_DELIMITERS = (("{{", "}}"), ("{%", "%}"), ("{#", "#}"))
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: A PostgreSQL Unicode-escaped identifier, ``U&"..."``.
+#:
+#: The second construct that breaks the premise above, and in the same way:
+#: ``U&"\\0071uery_to_xml"(...)`` parses as an anonymous function whose name is
+#: the *literal* ``\\0071uery_to_xml``, so the function denylist is matching a
+#: name the engine never sees -- PostgreSQL decodes the escape and runs
+#: ``query_to_xml``, handing a dataset owner rows from outside their RLS scope
+#: through the preview's ``emitted_predicate``.
+#:
+#: Normalizing the escapes and re-checking would be the other repair, and is
+#: worse: it means reimplementing one engine's identifier decoding well enough
+#: to be a security boundary. Refusing the construct is exact, and costs
+#: nothing real -- a transform is a scalar function of ``:value``, and there is
+#: no reason to name a function or column through an escape sequence.
+#:
+#: Refused on every engine, like the executable comment, so a transform stored
+#: on SQLite cannot detonate when the dataset is re-pointed at PostgreSQL. The
+#: ``&`` may be separated from the ``U`` by nothing at all, but whitespace or a
+#: comment between the prefix and the string is not accepted by PostgreSQL
+#: either, so the strict form is the whole surface.
+#:
+#: Matched in raw text, so the prefix is refused inside a string literal too.
+#: That is the same trade the executable comment makes and has the same
+#: justification: a gate whose contract is to fire *before* the parse cannot
+#: ask the parse whether the text was quoted. ``concat(:value, 'u&"x"')`` is
+#: refused, which costs an owner nothing anyone writes.
+UNICODE_ESCAPED_IDENTIFIER_RE = re.compile(r'\bU&"', re.IGNORECASE)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate: a transform such as
+#: ``datediff(day, :value, LOCALTIMESTAMP)`` for a relative partition key is
+#: evaluated once and then keeps emitting yesterday's answer, so the chart
+#: silently drops rows after midnight.
+#:
+#: Matched by SQL function name, so every engine's spelling of "now" has to be
+#: named -- the ANSI four were not enough. Listed rather than delegated to the
+#: engine specs because the risk is the same everywhere and a spec that had not
+#: got round to declaring its own would fail open; a name no engine has is
+#: inert, so over-listing costs nothing.
+NON_DETERMINISTIC_FUNCTIONS = {
+ # ANSI, and the engines that spell it this way.
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "LOCALTIME",
+ "LOCALTIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+ # PostgreSQL. `now()` is statement-stable; these two are not even that.
+ "CLOCK_TIMESTAMP",
+ "STATEMENT_TIMESTAMP",
+ "TIMEOFDAY",
+ # MySQL and MariaDB.
+ "CURDATE",
+ "CURTIME",
+ "SYSDATE",
+ "UTC_DATE",
+ "UTC_TIME",
+ "UTC_TIMESTAMP",
+ "UUID_SHORT",
+ # Oracle.
+ "SYSTIMESTAMP",
+ "SYS_GUID",
+ # SQL Server.
+ "GETDATE",
+ "GETUTCDATE",
+ "SYSDATETIME",
+ "SYSUTCDATETIME",
+ "SYSDATETIMEOFFSET",
+ "NEWID",
+ # BigQuery.
+ "CURRENT_DATETIME",
+ "GENERATE_UUID",
+ # Snowflake.
+ "RANDSTR",
+ "UUID_STRING",
+ # ClickHouse.
+ "NOW64",
+ "RANDCANONICAL",
+ "GENERATEUUIDV4",
+ # H2 and Derby, which the test fixtures use.
+ "RANDOM_UUID",
+}
+
+#: The wall-clock names an engine evaluates with no parentheses at all.
+#:
+#: These parse as *column references*, not functions, so the name-based walk
+#: below cannot see them: `datediff(UTC_DATE, :value)` on MySQL and
+#: `:value - SYSDATE` on Oracle both cleared the gate and froze probe time into
+#: a cached mirror.
+#:
+#: A subset of `NON_DETERMINISTIC_FUNCTIONS` rather than the whole of it,
+#: because refusing a bare name costs an owner a column genuinely called that.
+#: Only the names SQL lets you write without ``()`` are listed -- the datetime
+#: keywords -- so `rand`, `uuid` and `newid`, which always need parentheses and
+#: are plausible column names, stay out.
+BARE_WALL_CLOCK_KEYWORDS = frozenset(
+ {
+ "current_date",
+ "current_time",
+ "current_timestamp",
+ "localtime",
+ "localtimestamp",
+ "utc_date",
+ "utc_time",
+ "utc_timestamp",
+ "sysdate",
+ "systimestamp",
+ }
+)
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+class Unmirrorable:
+ """
+ A filter no mirror can stand in for, and why.
+
+ Returned by `ExploreMixin.mirror_probe_request` for a value the engine
+ compares more coarsely than the filter carries, one it cannot render as a
+ literal, one whose rendered literal the engine would not read back as the
+ same value, one in a time frame the transform would discard, or an ``IN``
+ list with a member of any of those kinds. An object rather than `None`,
+ because `None` is a filter value in its own right.
+
+ The reason rides along because the preview has to explain the decline to
+ the owner, and the two declines want different advice: "the engine compares
+ less of this value than you typed, so map a column it compares in full" is
+ sound guidance for a `DATE` column and actively misleading for an
+ offset-bearing bound on a `TIMESTAMP` one, which already is such a column.
+ Carried rather than re-derived so the preview's explanation cannot come
+ apart from the chart path's decision.
+
+ Lives here rather than beside that method so the preview can read it too:
+ `superset.models.helpers` imports this module, so these can only cross the
+ boundary in this direction. Both callers recognise the same instances -- a
+ preview that answered "valid" for a request the chart path declines is the
+ drift this is here to prevent.
+ """
+
+ __slots__ = ("reason",)
+
+ def __init__(self, reason: str) -> None:
+ self.reason = reason
+
+ def __repr__(self) -> str:
+ return f"<Unmirrorable {self.reason}>"
+
+
+#: The ordinary decline: whatever the mirror cannot be built from, with the
+#: engine's own comparison resolution as the reason an owner can act on.
+UNMIRRORABLE = Unmirrorable("resolution")
+
+#: A value carrying a UTC offset, declined whatever the column's resolution.
+#: A transform such as ``CAST(:value AS TIMESTAMP)`` drops the offset, so even
+#: an engine that compares the whole instant would be probed in the wrong
+#: frame -- which is not something mapping a different column fixes.
+UNMIRRORABLE_OFFSET = Unmirrorable("offset")
+
+#: A value the driver and the engine would not spell the same way, declined
+#: whatever the column's resolution and whatever the operator. Nothing about
+#: the column or the transform fixes it -- see `literal_round_trips` -- so the
+#: advice the resolution reason carries would send an owner after the wrong
+#: thing entirely.
+UNMIRRORABLE_ESCAPING = Unmirrorable("escaping")
+
+
+def is_unmirrorable(value: Any) -> bool:
+ """Whether `mirror_probe_request` declined this request."""
+ return isinstance(value, Unmirrorable)
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def _native_generic_type(
+ column: "TableColumn",
+) -> utils.GenericDataType | None:
+ """
+ What the engine spec makes of ``column``'s declared type.
+
+ `TableColumn.type_generic` answers ``TEMPORAL`` for every column carrying
+ ``is_dttm``, which is the right answer for a chart's time axis and the
+ wrong one for a comparison: an epoch ``BIGINT`` is a number to the engine
+ however it is labelled here. Falls back to the flag where the spec has no
+ answer, so a type Superset cannot resolve is no worse off than before.
+ """
+ try:
+ column_spec = column.db_engine_spec.get_column_spec(
+ column.type, db_extra=column.db_extra
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ column_spec = None
+ if column_spec is not None and column_spec.generic_type is not None:
+ return column_spec.generic_type
+ try:
+ return column.type_generic
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+#: Declared types whose comparison ignores trailing blanks.
+#:
+#: The fixed-width character types, which the SQL standard has compare as
+#: though both sides were padded to the same length -- so ``'US'`` and
+#: ``'US '`` are equal in a ``CHARACTER(3)``, while ``lower()`` of the two is
+#: not. Spelled out rather than matched by prefix because the variable-width
+#: names start with the same letters: ``VARCHAR`` and ``CHARACTER VARYING``
+#: compare the blanks and must not land here.
+PADDED_CHARACTER_TYPES = frozenset(
+ {
+ "CHAR",
+ "NCHAR",
+ # PostgreSQL's own name for ``CHARACTER``, which is what reflection
+ # reports for a ``CHAR(n)`` column there.
+ "BPCHAR",
+ "CHARACTER",
+ "NATIONAL CHAR",
+ "NATIONAL CHARACTER",
+ }
+)
+
+
+def _is_padded_character_type(column: TableColumn) -> bool:
+ """
+ Whether ``column``'s declared type compares without its trailing blanks.
+
+ Read off the declared type rather than the engine spec's resolved one: the
+ specs map ``CHAR`` and ``VARCHAR`` onto the same `sqlalchemy.String`, so
+ the distinction this needs is gone by then. The length suffix is dropped
+ and the name matched against `PADDED_CHARACTER_TYPES`, so an unfamiliar
+ spelling answers ``False`` and the engine-level flag decides as before --
+ this gate adds a decline rather than lifting one. A column with no
+ declared type has nothing to read, and answers the same way.
+ """
+ if not isinstance(column.type, str):
+ return False
+ native = re.sub(r"\s+", " ", column.type.strip().upper())
+ return native.split("(")[0].strip() in PADDED_CHARACTER_TYPES
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ Padding is asked about per column, because it is a property of the *type*
+ rather than of the engine. ``binary_string_comparison`` speaks for an
+ engine's default text comparison, and on PostgreSQL -- which declares it
+ -- a ``CHAR(2)`` still matches a filter for ``'US '`` against a stored
+ ``'US'``, because the standard says a padded character type compares
+ without its trailing blanks. The mirror ``region_key = lower('US ')`` then
+ excludes the row. So a fixed-width character type declines whatever the
+ engine says, and an engine that ignores trailing blanks on its *variable*
+ types says so by not declaring the flag at all (see `RedshiftEngineSpec`).
+
+ The type asked for is the engine spec's reading of the column's declared
+ type, not `TableColumn.type_generic`, which answers ``TEMPORAL`` for
+ anything carrying ``is_dttm``. A ``VARCHAR`` flagged temporal is still text
+ to the engine: on MySQL a filter for ``'2026-01-01T00:00:00'`` matches a
+ stored ``'...t00:00:00'``, while the mirror ``p = hex('...T...')`` excludes
+ it -- and asking the semantic flag skipped the check entirely.
+
+ A type the spec cannot classify declines, which is what the paragraph above
+ promises and what only the exception branch used to do. PostgreSQL's
+ ``citext`` matches no type pattern, so it answered ``None`` -- neither
+ string nor not-string -- and was waved through, which is precisely wrong
+ for a type whose whole purpose is case-insensitive comparison. Declining
+ costs the pruning; admitting it costs rows.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ # Ahead of the generic-type question, which a padded type can lose: the
+ # specs map ``CHARACTER`` onto no generic type at all on some engines, and
+ # a fixed-width character type is a string whether or not Superset can say
+ # so from the name.
+ if _is_padded_character_type(column):
+ return False
+ generic_type = _native_generic_type(column)
+ if generic_type is None:
+ return False
+ if generic_type != utils.GenericDataType.STRING:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_unicode_escaped_identifier(transform: str | None) -> bool:
+ """Whether the transform names something through a ``U&"..."`` escape.
+
+ See `UNICODE_ESCAPED_IDENTIFIER_RE`. Answered on raw text for the same
+ reason as the comment above: the parse reports a name the engine does not
+ use, which is exactly what makes the denylist blind to it.
+ """
+ return (
+ bool(transform)
+ and UNICODE_ESCAPED_IDENTIFIER_RE.search(transform or "") is not None
+ )
+
+
+#: Sequence pseudo-columns, which advance a sequence when they are *read*.
+#:
+#: ``orders_seq.NEXTVAL`` parses as a qualified column reference, not a
+#: function call, so neither `SQLStatement.is_mutating` -- which walks function
+#: names -- nor the function denylist can see it. The probe would then run
+#: ``SELECT orders_seq.NEXTVAL + 1 FROM DUAL`` and advance the sequence, again
+#: on every cache expiry, for a dataset editor holding neither SQL Lab nor a
+#: DML grant. Reading one is a write however the parser classifies it.
+#:
+#: The function spelling (``nextval('s')`` on PostgreSQL) is a different shape
+#: and is caught as a function; this is only about the suffix form.
+SEQUENCE_PSEUDO_COLUMNS = frozenset({"nextval", "currval"})
+
+#: The same thing written as a call.
+#:
+#: Only the suffix form parses as a column; `nextval('s')` on PostgreSQL and
+#: DuckDB, `NEXTVAL(s)`/`SETVAL(s, 1)` on MySQL and MariaDB, and SQL Server's
+#: `NEXT VALUE FOR s` all parse as functions. `SQLStatement.is_mutating` walks
+#: function names on PostgreSQL alone -- deliberately, since the same names are
+#: read-only elsewhere -- so every other engine let these through.
+#:
+#: Matched on the name whatever the engine, because advancing a sequence is a
+#: write wherever it happens and a transform has no reason to call one.
+SEQUENCE_FUNCTIONS = frozenset(
+ {"nextval", "setval", "next_value_for", "nextvalfor", "prevval", "lastval"}
+)
+
+
+def references_sequence(statement: SQLStatement) -> bool:
+ """Whether the statement reads or advances a sequence.
+
+ Both spellings: the pseudo-column suffix, which parses as a column (see
+ `SEQUENCE_PSEUDO_COLUMNS`), and the call, which parses as a function (see
+ `SEQUENCE_FUNCTIONS`).
+
+ Answered on the parse rather than on raw text, because position is what
+ makes it the construct: a column or alias merely *called* ``nextval`` is
+ an ordinary column, and a string literal holding the word is text.
+ """
+ return bool(
+ statement.get_column_names() & SEQUENCE_PSEUDO_COLUMNS
+ or statement.get_disallowed_functions(set(SEQUENCE_FUNCTIONS))
+ )
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """
+ Whether the transform contains a balanced Jinja block.
+
+ A block is an opening delimiter followed, anywhere later, by its closing
+ one -- the same thing ``{{.*?}}`` and its two siblings match under
+ ``re.DOTALL``. Scanned with `str.find` rather than that pattern, because a
+ lazy match retried from every opening delimiter is quadratic in a run of
+ them, and this runs on stored transforms with no length bound of its own:
+ `is_transform_active` reads whatever the column holds. The earliest opening
+ delimiter is the only one worth trying, since any closing delimiter after a
+ later one is also after it.
+ """
+ if not transform:
+ return False
+ for opening, closing in JINJA_BLOCK_DELIMITERS:
+ start = transform.find(opening)
+ if start != -1 and transform.find(closing, start + len(opening)) != -1:
+ return True
+ return False
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+
+ Three spellings have to be looked for, because one name reaches the parse
+ three ways: as a function call, as a zero-argument call a dialect resolves
+ itself, and -- for the datetime keywords -- as a bare word that parses as a
+ column reference.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ # The parenthesis-free spellings, which parse as columns rather than
+ # functions and so are invisible to the walk above. See
+ # `BARE_WALL_CLOCK_KEYWORDS`.
+ found |= {
+ name.upper() for name in BARE_WALL_CLOCK_KEYWORDS & statement.get_column_names()
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error( # noqa: C901
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ And it must be a *read*. Shape is a separate question from effect: a bare
+ scalar expression can still write, so `SQLStatement.is_mutating` is asked
+ too -- the same question SQL Lab and the chart executor ask before letting
+ SQL run. See the gate itself for what that reaches and what it does not.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ # Also ahead of the parse, and for a stronger reason than cost: every gate
+ # below reasons about the parse tree, and this is the one construct that
+ # makes the parse tree describe a different statement from the one the
+ # engine runs. Checked here as well as in `validate_transform` because this
+ # is the door a row written by an earlier release still comes through.
+ if contains_executable_comment(transform):
+ return str(
+ _(
+ "A partition value transform cannot contain a MySQL "
+ "executable comment, which the database executes and every "
+ "validator reads as a comment."
+ )
+ )
+
+ if contains_unicode_escaped_identifier(transform):
+ return str(
+ _(
+ "A partition value transform cannot name anything through a "
+ 'U&"..." escape sequence, which the database decodes and '
+ "every validator reads literally."
+ )
+ )
+
+ # Same door, same reason: the name the denylist below would match is not
+ # the name the engine resolves. See `UNICODE_ESCAPED_IDENTIFIER_RE`.
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The read-only gate, which nothing above implies. The shape gates ask what
+ # the transform *selects*; this asks what evaluating it *does*, and a bare
+ # scalar expression can still write. `nextval(:value)` on PostgreSQL
+ # advances a sequence: one function call, no clause, no sub-query, and not
+ # in the default `DISALLOWED_SQL_FUNCTIONS` either -- so every gate above
+ # passes it and the probe then runs it. `setval` is the same shape, and
+ # `exp.Execute` and the opaque-`exp.Command` forms arrive the same way.
+ #
+ # The large-object writers (`lo_export`, `lowrite`, `lo_from_bytea`, ...)
+ # are caught here too, and the shipped denylist happens to name them as
+ # well -- but that is config an operator can replace, while this is not.
+ #
+ # `is_mutating` is the same question SQL Lab, `get_virtual_table_metadata`
+ # and the chart executor ask before letting SQL run, so a transform is held
+ # to the bar the rest of Superset already sets rather than to one invented
+ # here. Unconditional rather than gated on `Database.allow_dml`: a transform
+ # is a scalar function of `:value` by definition, so there is no legitimate
+ # mutating one, and the probe runs on a cache schedule nobody chose -- a
+ # write would repeat every time the entry expired.
+ #
+ # It bears saying what this does not reach. A user-defined function whose
+ # body writes is a plain call no parser can tell from `lower(:value)`, and
+ # `is_mutating`'s function-name walk is PostgreSQL-only by design, since the
+ # same names are read-only elsewhere. Neither residual is specific to this
+ # feature -- a dataset editor can already have the engine evaluate an
+ # arbitrary expression through a calculated column or a virtual dataset's
+ # SQL -- and closing them means authorizing the preview against the
+ # database, not parsing harder.
+ if statement.is_mutating():
+ return str(
+ _(
+ "A partition value transform cannot change data. It is "
+ "evaluated against the database to check that it mirrors, so "
+ "it has to be a read."
+ )
+ )
+
+ # Not reached by the walk above, which is why it is its own gate: a
+ # sequence pseudo-column is a *column* to the parser and a write to the
+ # engine. See `SEQUENCE_PSEUDO_COLUMNS`.
+ if references_sequence(statement):
+ return str(
+ _(
+ "A partition value transform cannot read a sequence. "
+ "NEXTVAL advances the sequence every time it is evaluated, "
+ "and the transform is evaluated on a cache schedule."
+ )
+ )
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the
+ probe uninspected. Rendering is not what makes that true: a string element
+ is checked by `literal_round_trips` before it is rendered -- the dialect's
+ literal processor and the engine's lexer do not always agree about what a
+ rendered literal says -- and `probe_sql_is_evaluable` re-reads the finished
+ query, which is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def _placeholder_is_bindable(transform: str) -> bool:
+ """
+ Whether SQLAlchemy's ``text()`` can see ``:value`` as a bound parameter.
+
+ `VALUE_PLACEHOLDER_RE` is ``:value\b``, which matches the placeholder in a
+ Postgres cast such as ``:value::bigint``. SQLAlchemy's own bind scan is
+ ``(?<![:\\w$]):([\\w$]+)(?![:\\w$])`` -- note the trailing exclusion -- so a
+ following colon stops it: ``text(":value::bigint")`` reports a parameter
+ named ``valu``, and ``.bindparams(bindparam("value"))`` then raises
+ ``ArgumentError``.
+
+ `_probe` swallows that, so the only symptom was a perfectly valid transform
+ whose mapping silently never pruned, and a preview reporting an engine
+ failure for SQL that was never sent. Every write-side gate passes the
+ transform: it parses, it is a bare expression, and the placeholder *is* in
+ an executable position.
+
+ Answered by attempting the bind itself rather than by pattern-matching
+ ``::`` or reading ``text()``'s private parameter map, so this cannot
+ disagree with what `build_probe_sql` is about to do -- on any dialect, or on
+ a SQLAlchemy whose scan changes.
+ """
+ try:
+ sa.text(transform).bindparams(sa.bindparam("value", value=None))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return False
+ return True
+
+
+def escape_foreign_colons(transform: str) -> str:
+ """
+ ``transform`` with every colon but the ``:value`` placeholder escaped.
+
+ `sqlalchemy.text` reads any ``:word`` as a bind parameter, including one
+ inside a string literal, and an unbound parameter renders as ``NULL``
+ under literal binds rather than raising. So ``:value || \':suffix\'``
+ compiled to ``'us' || 'NULL'``: the mirror asked for a partition value no
+ row holds and the chart dropped rows, with no error for `_probe` to
+ swallow and nothing on screen to say so.
+
+ Escaped rather than refused, because a colon in a literal is ordinary --
+ ``concat(:value, \':\', region)`` builds a composite key -- and the
+ placeholder is the only colon this module means to interpret. `text()`
+ reads ``\\:`` as a literal colon.
+
+ Only the bound path needs this. A `RawProbeValue` or an unbindable
+ placeholder is substituted as text by `parse_skeleton`, which never hands
+ the transform to `text()` at all.
+ """
+ pieces: list[str] = []
+ cursor = 0
+ for match in VALUE_PLACEHOLDER_RE.finditer(transform):
+ pieces.append(transform[cursor : match.start()].replace(":", r"\:"))
+ pieces.append(match.group(0))
+ cursor = match.end()
+ pieces.append(transform[cursor:].replace(":", r"\:"))
+ return "".join(pieces)
+
+
+def literal_round_trips(value: Any, dialect: Dialect | None, engine: str) -> bool:
+ """
+ Whether the engine reads a rendered ``value`` back as that same value.
+
+ The probe runs with no bound parameters, so every value reaches the engine
+ as literal text the driver wrote (see `build_probe_sql`). Whether that text
+ says what the value says is a question about two independent spellings: the
+ driver's escaping, and the engine's lexer. SQLAlchemy's default renderer
+ doubles apostrophes and passes backslashes through; Hive and Spark honour
+ the backslash and not the doubling, so ``'O''Brien'`` is read there as two
+ adjacent literals -- the transform is evaluated at ``OBrien``, and the
+ mirror asks for a partition key that holds none of the rows the filter
+ keeps. The same gap in the other direction lets a value close its own quote
+ and have the rest of it read as SQL.
+
+ Escaping is not the repair. Whether a backslash introduces an escape is a
+ per-session server setting -- ``standard_conforming_strings`` on Postgres,
+ ``NO_BACKSLASH_ESCAPES`` on MySQL, ``escapedStringLiterals`` on Spark -- and
+ nothing in the engine specs exposes it. SQLAlchemy reads it off the server
+ into ``_backslash_escapes`` during ``initialize(connection)``, which the
+ probe's dialect never reaches: `_dialect_for` asks the ``Database`` for a
+ dialect, not for a connection, so Postgres renders ``a\\b`` as
+ ``'a\\\\b'`` and a server with the standard setting reads four
+ characters. An engine-spec flag would have to be defaulted, and either
+ default is wrong for a dozen engines: one leaves the hole open, the other
+ corrupts the probed value.
+
+ So the premise is verified rather than declared, the way
+ `probe_sql_is_evaluable` verifies the finished statement. A value that does
+ not survive the round trip is not mirrored, which costs the query its
+ pruning and nothing else.
+
+ The short-circuit is a proof, not a guess, and it matters for cost: a
+ 200-member ``IN`` list would otherwise parse 200 times on the chart path.
+ If the renderer emitted the value between two quotes and changed nothing in
+ it, and the value carries neither a quote nor a backslash, then no lexer in
+ play can read it as anything but itself. Both exclusions are load-bearing:
+ on Hive ``a\\b`` renders verbatim and reads as ``a`` followed by a
+ backspace.
+
+ :param value: a filter value about to be rendered into the probe
+ :param dialect: the dialect that will render it, as `_dialect_for` reports
+ :param engine: ``database.backend``, whose lexer reads the result
+ :return: whether the two agree about what the literal says
+ """
+ if isinstance(value, RawProbeValue):
+ # Already SQL, with no single value for a parse to be compared against:
+ # its elements are checked before they are rendered, by
+ # `ExploreMixin._array_mirror_probe_value`. A backslash surviving into
+ # the finished text is refused here all the same, as the backstop for a
+ # renderer this module does not own.
+ return "\\" not in value.sql
+ if not isinstance(value, str):
+ # Numbers and instants are not written between delimiters, so there is
+ # no escaping for the two sides to disagree about.
+ return True
+
+ rendered = _compile_literal(sa.literal(value), dialect)
+ if rendered == f"'{value}'" and "'" not in value and "\\" not in value:
+ return True
+
+ try:
+ return (
+ SQLStatement(f"SELECT {rendered}", engine).get_select_literal_value()
+ == value
+ )
+ except SupersetParseError:
+ # A rendered literal the engine's own dialect will not parse is the
+ # strongest form of disagreement there is.
+ return False
+
+
+def value_round_trips(database: Database, value: Any) -> bool:
+ """
+ `literal_round_trips` for a caller holding a database, not a dialect.
+
+ Which renderer and which lexer apply is this module's business, so the two
+ callers outside it -- the chart path's own gate in
+ `ExploreMixin.mirror_probe_request` and the mapping summary Explore reads
+ -- ask in these terms and stay out of it.
+
+ :param database: the database whose driver renders and whose engine reads
+ :param value: a filter value about to be rendered into the probe
+ :return: whether the two agree about what the literal says
+ """
+ return literal_round_trips(value, _dialect_for(database), database.backend)
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text. That is not itself a boundary:
+ the processor's escaping is not always the escaping the engine honours, and
+ a value can close its own quote through the gap. The boundary is
+ `literal_round_trips` on the way in -- which callers must have run, like
+ `stored_expression_error` below -- and `probe_sql_is_evaluable` on the way
+ out.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ bindable = _placeholder_is_bindable(transform)
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ elif bindable:
+ # Every other colon escaped first: `text()` would read one inside a
+ # string literal as a second bind parameter and render it `NULL`.
+ # See `escape_foreign_colons`.
+ clause = sa.text(escape_foreign_colons(transform)).bindparams(
+ sa.bindparam("value", value=value)
+ )
+ rendered = _compile_literal(clause, dialect)
+ else:
+ # `text()` cannot see the placeholder (see
+ # `_placeholder_is_bindable`), so the value is rendered by the
+ # dialect's own literal processor first and substituted as SQL
+ # text. The same two steps in the other order: binding exists to
+ # get the value through that processor, and `_compile_literal`
+ # inlines the result either way, so this is the same string by a
+ # different route -- not a loosening of the "never interpolate a
+ # raw value" rule. `parse_skeleton` substitutes literally, so the
+ # rendered literal arrives here exactly as it was rendered, which
+ # is what makes `literal_round_trips`' verdict on it good for this
+ # branch as much as for the bound one.
+ rendered = parse_skeleton(
+ transform, _compile_literal(sa.literal(value), dialect)
+ )
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Five things have to hold, and all five are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+ * No comment, anywhere. A value that closes its own quote has to hide the
+ text `build_probe_sql` appended after it, and a comment is the only way
+ to do that and still balance the quotes -- so this is what makes the
+ alias check above sufficient rather than merely necessary. Read off the
+ parse rather than the text, so a comment *inside* a literal is data and
+ costs no pruning, and so the question is asked in the engine's own
+ dialect. A transform has no legitimate reason to carry one either; see
+ `EXECUTABLE_COMMENT_RE`.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ # Before the parse, because this gate's whole contract is that what the
+ # parse describes is what the engine will run, and an executable comment is
+ # precisely the text where that stops being true. The transform is already
+ # refused for carrying one; this covers the compiled statement, so no later
+ # change to how values are rendered can reintroduce it behind the gates
+ # below.
+ if contains_executable_comment(sql) or contains_unicode_escaped_identifier(sql):
+ return False
+
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if not isinstance(statement, SQLStatement):
+ # A dialect whose statements this gate cannot take apart -- KQL -- gets
+ # no probe rather than an unchecked one. It never had one: the clause
+ # inspection below is implemented for SQL statements only, and the
+ # alternative to declining here is an `AttributeError` that `_probe`
+ # swallows into the same outcome, less legibly.
+ return False
+ if statement.has_comment():
+ return False
+ if statement.has_subquery():
+ return False
+ if statement.get_clause_names() - {"from"}:
+ return False
+ if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+ """
+ The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+ Parsed rather than string-compared so that the comparison in
+ `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+ not parse answers ``None``, which no statement carrying a FROM can match --
+ the probe then declines, which is the right way for an unreadable engine
+ constant to fail.
+ """
+ if not from_suffix.strip():
+ return None
+ try:
+ return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+ except SupersetParseError:
+ return None
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ # The value side of the premise `probe_sql_is_evaluable` checks on the
+ # finished statement: a value the driver and the engine would spell
+ # differently is not probed at all -- see `literal_round_trips`.
+ #
+ # `ExploreMixin.mirror_probe_request` declines one earlier, with a reason
+ # the preview can explain, and that is the gate an owner sees. This is the
+ # one that cannot be walked around. `_collect_partition_mirror_range`
+ # appends its bounds into the sink without passing through that method at
+ # all, and both paths can hand back a value the gate never saw: on a column
+ # carrying a `python_date_format`, what is probed is
+ # `strftime(that format)` -- text no mapping gate has ever read.
+ #
+ # Above `_run_probe` on purpose. This is a property of one input, not of
+ # the transform, and a verdict recorded here would withdraw the mirror for
+ # every later value of a transform the engine evaluates perfectly well.
+ dialect = _dialect_for(database)
+ if not all(
+ literal_round_trips(value, dialect, database.backend) for value in distinct
+ ):
+ logger.warning(
+ "A filter value is not written the same way by the driver and the "
+ "database, so the partition transform is not probed at it; this "
+ "query will not prune"
+ )
+ return None
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+
+ The verdict is about the *transform*: whether the engine evaluated it at
+ all. A ``NULL`` among the results is not that -- it is this input's answer,
+ and `NULLIF(:value, 0)` returning ``NULL`` for ``n = 0`` says nothing about
+ the same transform on ``n = 2``. Counting it withdrew the promise for the
+ whole transform, and nothing restored it: a *failed* probe is deliberately
+ not cached, so the next chart re-probes and re-records, but a ``NULL`` is a
+ successful probe and *is* cached -- so the false verdict outlived every
+ later hit, and the editor reported a working mapping as not mirroring
+ while the query went on pruning. The per-input skip still happens where it
+ belongs, in the caller's own ``NULL`` guard.
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=values is not None,
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ from_suffix = database.db_engine_spec.select_without_from_suffix
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ from_suffix,
+ )
+ if not probe_sql_is_evaluable(
+ sql, database.backend, len(distinct), from_suffix
+ ):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _execution_identity(database: Database) -> str | None:
+ """
+ Who the warehouse will run the probe as, when that can vary by caller.
+
+ `_probe_cache_key` keys on the `Database` record, which is the *connection*
+ -- not the identity it is opened under. Two hooks make that identity a
+ function of the Superset user instead:
+
+ * ``impersonate_user`` on the database, which hands the effective username
+ to `db_engine_spec.impersonate_user`;
+ * ``DB_CONNECTION_MUTATOR``, which receives the effective username and may
+ return an entirely different account's URL.
+
+ Under either one, a cached probe result computed under user A's grants was
+ served to user B, and the preview echoed it back in ``emitted_predicate``.
+ A transform wrapping a read-capable function the denylist does not name --
+ Oracle's ``DBMS_XMLGEN.GETXML`` is the worked example -- then leaks across
+ users who were never allowed the same rows.
+
+ Returns ``None`` when neither hook is configured, which is the common case
+ and deliberately leaves the key as it was: the cache exists to keep a
+ synchronous warehouse round trip off the chart-query path, and keying every
+ deployment on the username would cost every deployment the hit rate to fix
+ the two that need it.
+
+ The *Superset* username rather than the resolved warehouse account, because
+ it is the input both hooks branch on, and reading it needs no URL parse and
+ puts no credential in the key.
+ """
+ if not (database.impersonate_user or app.config["DB_CONNECTION_MUTATOR"]):
+ return None
+ return get_username()
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _mirror_verdict_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str:
+ """
+ `_probe_cache_key` without the values.
+
+ Whether a transform can be evaluated at all is a property of the transform
+ and the connection, not of the filter that happened to be probing it, so
+ one chart's answer settles the question for the next one.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ # Whether a transform *can* be evaluated is a property of the
+ # transform and the connection -- but under impersonation the
+ # connection is per-user, and a function one account may call can
+ # be refused to another. See `_execution_identity`.
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_verdict:{digest}"
+
+
+def record_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ *,
+ mirrors: bool,
+) -> None:
+ """
+ Remember whether this transform produced a mirror, for the UI to read.
+
+ Advisory only. Nothing in the query path consults it: a probe that failed
+ once is retried on the next chart exactly as it is today, because declining
+ to prune for a whole cache timeout over one transient engine blip is the
+ trade `evaluate_transform` deliberately refuses -- see the comment where it
+ declines to cache a failure.
+
+ What this is for is the *claim*. `is_transform_active` parses the transform
+ and no more, so a transform the database rejects -- a misspelled function
+ is the common case -- is "active", and the editor's banner and Explore's
+ pruning glyph promise a speed-up that never happens. A promise is exactly
+ the thing that may be withheld on one bad answer and restored on a good
+ one, which is why this is a separate entry from the probe's own results
+ rather than a relaxation of that rule.
+
+ Written by `_run_probe`, so the preview endpoint -- which shares the
+ evaluator -- settles the question before the owner has even saved.
+ """
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(
+ _mirror_verdict_cache_key(database, catalog, schema, transform),
+ mirrors,
+ timeout=timeout,
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform verdict", exc_info=True)
+
+
+def known_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> bool | None:
+ """
+ The last verdict `record_mirror_verdict` stored, or `None` if there is none.
+
+ `None` is the honest answer on a cold cache and is deliberately not `False`:
+ reporting a working mapping as broken until something probes it would
+ trade one wrong claim for another. The alternative -- probing from the
+ read side -- would put a warehouse round trip on every Explore and
+ dashboard load, and a failing transform is not cached at all, so it would
+ be a round trip every single time.
+ """
+ try:
+ verdict = cache_manager.cache.get(
+ _mirror_verdict_cache_key(database, catalog, schema, transform)
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return verdict if isinstance(verdict, bool) else None
+
+
+def _compile_literal(element: Any, dialect: Dialect | None) -> str:
+ """
+ Compile with inline literals, undoing the paramstyle's percent doubling.
+
+ Both ``TextClause`` and literal compilation run the dialect's
+ ``post_process_text``, which doubles every ``%`` whenever the identifier
+ preparer asks it to -- true for MySQL and Postgres and for every spec
+ inheriting their paramstyle. That doubling exists so a later DBAPI
+ parameter-interpolation pass can undo it, and the probe has no such pass:
+ it executes with no bound parameters at all. So a transform of
+ ``date_format(:value, '%Y%m%d')`` reaches the warehouse asking for the
+ literal string ``%%Y%%m%%d``, the probe returns that instead of a date, and
+ the mirrored predicate drops every row the filter keeps.
+
+ The same normalization ``Database.compile_sqla_query`` applies for the same
+ reason. ``_double_percents`` is private and not guaranteed on a third-party
+ dialect, hence the ``getattr`` default.
+ """
+ compiled = str(
+ element.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
+ )
+ if dialect is not None and getattr(
+ dialect.identifier_preparer, "_double_percents", False
+ ):
+ compiled = compiled.replace("%%", "%")
+ return compiled
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be *asked* to stand in for itself, and the transform
+ cannot carry Jinja or call a non-deterministic function. Tier 2
+ (``blocking=False``) is everything that merely leaves the mapping inactive
+ -- including a self-mapping nobody asked for, where the partition column
+ merely happens to be the default datetime column.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column == partition_column:
+ # Asked for explicitly, so report it as the mistake it is.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+ elif not partition_mapped_column and main_dttm_col == partition_column:
+ # Resolved onto itself only because the default datetime column happens
+ # to be the partition column -- a state metadata sync could produce
+ # without anyone asking for it. The mapping is inert either way, since
+ # `resolve_partition_mapping` bails out on it, so this reports and lets
+ # the write through: blocking here means a dataset already in the state
+ # can never be saved again, not even to change its description, and
+ # there is no field whose edit would clear the error first.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "%(name)s is both the partition column and the default "
+ "datetime column, so the mapping points at itself and "
+ "stays inactive. Set a mapped column override, or change "
+ "the default datetime column.",
+ name=partition_column,
+ ),
+ blocking=False,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def drop_unmapped_value_transforms(
+ columns: list[dict[str, Any]] | None,
+ *,
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ names_by_id: dict[int, str] | None = None,
+ stored_by_name: dict[str, tuple[str | None, bool]] | None = None,
+) -> list[str]:
+ """
+ Null the value transform on every *incoming* column the mapping cannot mirror.
+
+ The write-side twin of `DatasetDAO.clear_unmapped_partition_transforms`,
+ which answers for the model. A mapping has exactly one mirrored column, so
+ at most one column may carry a transform. One parked on any other column is
+ invisible -- no row but the mapped one renders a transform -- and yet it is
+ stored, and it goes live the moment the mapped column resolves back to it.
+ Clearing an override is enough to do that: a null
+ ``partition_mapped_column`` means "follow ``main_dttm_col``".
+
+ Ungated on the feature flag, unlike its model-level twin, and the difference
+ is what each one discards. That one drops stored configuration, so with the
+ flag off it would be pure loss. This one drops only a value the request in
+ hand is asking to write where the invariant says none may live -- and the
+ flag-off window is precisely when such a value gets parked for later, since
+ the editor hides these fields and the model-level pass declines to run.
+
+ Three writers reach the columns with no effective model-level pass between
+ them, which is why this exists at all: the deprecated
+ ``POST /datasource/save/``, which writes straight through
+ `update_from_object` and so never had one; and a
+ ``PUT /api/v1/dataset/<pk>`` or a dataset import made while the flag is
+ off, where the pass runs on both sides of the write and declines on both.
+
+ Mutates the payload in place, because every caller hands its own request
+ dict straight on to the code that writes it. Returns the names it cleared,
+ so the caller can say so in a log: this is a silent correction to a payload
+ whose author may have meant it.
+
+ A column whose payload mentions neither field is left alone. "Incoming" is
+ the whole scope -- a transform already in storage on a column this request
+ says nothing about is the model-level pass's business, under its own flag.
+
+ The mapped column resolves the way every other reader resolves it,
+ ``partition_mapped_column or main_dttm_col``, and resolves to nothing
+ without a partition column -- in which case no column may hold a transform
+ either.
+
+ :param names_by_id: how to read the name off a payload entry that gives
+ only an ``id``. `DatasetDAO._upsert_columns` identifies an existing
+ column by its primary key and lets ``column_name`` be omitted -- the
+ column keeps the name it has -- so without this an ordinary PUT looked
+ like a payload of nameless columns, none of which matched the mapped
+ one, and every transform in it was dropped. Callers whose writer keys
+ on the name instead (`update_from_object`, the importer) pass nothing.
+ An entry this cannot name is left alone rather than guessed at.
+ :param stored_by_name: ``(transform, is_monotonic)`` as currently stored,
+ per column name, so an *echo* can be told from an introduction. A
+ GET-then-PUT client sends back every column exactly as it received it,
+ so changing the default datetime column away from the mapped one made
+ the payload's unchanged copy of its transform look like a value being
+ parked -- and nulling it destroyed configuration the owner never
+ touched, unrecoverably, with the flag off and the editor's own fields
+ hidden. An unchanged value is the model-level pass's business under its
+ own flag, which is the same line this function's docstring already
+ draws for a column the payload omits. Callers that cannot see storage
+ pass nothing and keep the stricter behaviour.
+ """
+ mapped_column = (
+ (partition_mapped_column or main_dttm_col) if partition_column else None
+ )
+ cleared: list[str] = []
+ for column in columns or []:
+ name = column.get("column_name")
+ if name is None and names_by_id is not None:
+ column_id = column.get("id")
+ if column_id is not None:
+ name = names_by_id.get(column_id)
+ if name is None or name == mapped_column:
+ continue
+ transform = column.get("partition_value_transform")
+ is_monotonic = column.get("partition_transform_is_monotonic")
+ if not transform and not is_monotonic:
+ continue
+ if stored_by_name is not None and name in stored_by_name:
+ stored_transform, stored_monotonic = stored_by_name[name]
+ # A key the entry does not carry is unchanged, not `False`:
+ # `_upsert_columns` writes only the keys present, so echoing the
+ # transform without the declaration is a valid partial update. Read
+ # as a change, it failed the exemption and wrote both fields back
+ # as null -- the loss the exemption exists to prevent.
+ monotonic_echoes = "partition_transform_is_monotonic" not in column or bool(
+ is_monotonic
+ ) == bool(stored_monotonic)
+ transform_echoes = (
+ "partition_value_transform" not in column
+ or transform == stored_transform
+ )
+ if transform_echoes and monotonic_echoes:
+ # An echo, not an introduction. See `stored_by_name`.
+ continue
+ column["partition_value_transform"] = None
+ column["partition_transform_is_monotonic"] = False
+ cleared.append(name)
+ return cleared
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if contains_executable_comment(transform):
+ # Blocking, and checked on raw text next to the Jinja gate because no
+ # parse reports it: sqlglot reads `/*!50000 ... */` as comment data
+ # while MySQL and MariaDB execute it, so every shape gate downstream
+ # inspects a statement the engine will not run. See
+ # `EXECUTABLE_COMMENT_RE`.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform cannot contain a MySQL executable "
+ "comment (/*! ... */ or /*M! ... */). Those are comments "
+ "to every validator and statement text to the database, "
+ "so what would run is not what was checked."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if contains_unicode_escaped_identifier(transform):
+ # Beside the comment gate, for the same reason and on raw text: the
+ # parse reports the escape sequence verbatim as the function's name,
+ # so the function denylist compares against a name PostgreSQL never
+ # uses -- it decodes `U&"\0071uery_to_xml"` and runs `query_to_xml`.
+ # See `UNICODE_ESCAPED_IDENTIFIER_RE`.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ 'A value transform cannot name anything through a U&"..." '
+ "escape sequence. The database decodes it and every "
+ "validator reads it literally, so what would run is not "
+ "what was checked."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_bare_expression(transform, engine):
+ # Blocking, and deliberately placed in `validate_transform` rather than
+ # only at the probe: one issue here closes the PUT, the importer, the
+ # query-time gate through `is_transform_active`, the Explore indicator's
+ # active verdict and the preview endpoint, all of which already consult
+ # this function.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform must be a single SQL expression. It "
+ "cannot carry a FROM, WHERE, GROUP BY or any other clause, "
+ "and it cannot contain a sub-query."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not contains_value_placeholder(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform must contain the :value placeholder, "
+ "which stands for the filter value being mirrored."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not placeholder_is_executable(transform, engine):
+ # Blocking, and for the same reason the shape gate above is: this is
+ # the function the PUT, the importer, `is_transform_active`, the
+ # Explore indicator and the preview all consult, so one issue here
+ # closes every door at once. A placeholder inside a string literal is
+ # a sub-query the engine will run once a filter value closes the quote;
+ # one inside a comment silently eats the probe's own alias.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The :value placeholder must appear where the engine will "
+ "evaluate it. It cannot sit inside a string literal or a "
+ "comment."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if functions := find_non_deterministic_functions(transform, engine):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform calls %(functions)s, whose result "
+ "depends on when and where it runs. The transform is "
+ "evaluated in a separate session and the result is cached, "
+ "so the emitted predicate would freeze a snapshot of that "
+ "moment.",
+ functions=", ".join(sorted(functions)),
+ ),
+ blocking=True,
+ )
+ ]
+
+ return []
+
+
+@lru_cache(maxsize=LRU_CACHE_MAX_SIZE)
+def is_transform_active(transform: str | None, engine: str) -> bool:
+ """
+ Whether Superset will mirror filters through this transform.
+
+ `validate_transform` with the messages discarded, so the Explore indicator
+ cannot advertise a mapping the save path recorded as inactive. Anything
+ cheaper here would be a second, weaker statement of the same rule, free to
+ drift from the one the save path applies.
+
+ Blocking issues count too. Jinja and non-deterministic transforms are
+ rejected on PUT, but `CreateDatasetCommand` and import do not validate the
+ mapping, so one can still reach the database -- and it would never mirror a
+ filter either.
+
+ Memoized because `partition_filter_mapping_summary` is serialized on every
+ Explore and dashboard load and this parses the transform. The key is
+ everything the answer depends on: `validate_transform` reads no session, no
+ locale and no config beyond `SQL_MAX_PARSE_LENGTH`, which bounds the parser
+ rather than changing a verdict within that bound.
+ """
+ return not validate_transform(transform, engine)
+
+
+def preview_partition_mapping( # pylint: disable=too-many-return-statements
+ datasource: SqlaTable,
+ *,
+ mapped_column: str,
+ value_transform: str | None,
+ sample_values: list[str],
+ operator: FilterOperator = FilterOperator.EQUALS,
+ is_monotonic: bool = False,
+ partition_column: str | None = None,
+) -> dict[str, Any]:
+ """
+ Evaluate a candidate mapping and describe the predicate it would emit.
+
+ Shares the evaluator -- and therefore the probe cache -- with the query
+ path, so preview and runtime cannot drift and a previewed transform warms
+ the chart path for free. The predicate itself comes from
+ `build_mirrored_predicates`, the same builder the query path uses, so
+ operator shapes cannot drift either: what the panel shows is what a chart
+ would emit.
+
+ Validation runs first and the engine second: a half-typed transform is by
+ definition unparseable, so most of what a text input produces costs zero
+ queries.
+
+ Every part of the mapping is taken from the request rather than the stored
+ dataset. The editor previews while the owner is still editing -- a mapping
+ that has to be saved before it can be checked is not a preview.
+ """
+ partition_column = partition_column or datasource.partition_column
+ if not partition_column:
+ return {
+ "valid": False,
+ "reason": "unconfigured",
+ "error": _("No partition column is set."),
+ }
+
+ columns_by_name = {str(column.column_name): column for column in datasource.columns}
+ if mapped_column not in columns_by_name:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _("%(name)s is not a column on this dataset.", name=mapped_column),
+ }
+
+ # The bail-out `resolve_partition_mapping` makes at query time, and that
+ # `partition_filter_mapping_summary` repeats for the Explore indicator.
+ # Without it here, preview reports a valid emitted predicate for a mapping
+ # no chart will ever mirror -- the one answer a preview panel must not give.
+ if has_active_advanced_data_type(columns_by_name[mapped_column]):
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _(
+ "%(name)s has an advanced data type, so its filters are "
+ "translated into their own predicate shape and cannot be "
+ "mirrored onto the partition column.",
+ name=mapped_column,
+ ),
+ }
+
+ engine = datasource.database.backend
+ for issue in validate_partition_mapping(
+ column_names=set(columns_by_name),
+ partition_column=str(partition_column),
+ partition_mapped_column=mapped_column,
+ main_dttm_col=datasource.main_dttm_col,
+ transform=value_transform,
+ engine=engine,
+ ):
+ return {
+ "valid": False,
+ # The parse failure is the one an owner sees constantly, and it is
+ # the only one the mockup gives its own headline to.
+ "reason": (
+ "parse"
+ if issue.field == "partition_value_transform"
+ and not is_parseable(value_transform, engine)
+ else "validation"
+ ),
+ "error": str(issue.message),
+ }
+
+ # The policy every other stored expression goes through. The save path
+ # applies it in `UpdateDatasetCommand._validate_partition_mapping`, but
+ # preview evaluates a candidate transform that has not been saved, so
+ # without this the gate had a door around it. See
+ # `stored_expression_error` for what is being kept out and why.
+ if reason := stored_expression_error(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ cast(str, value_transform),
+ ):
+ return {"valid": False, "reason": "validation", "error": reason}
+
+ mapping = PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=mapped_column,
+ value_transform=cast(str, value_transform),
+ is_monotonic=is_monotonic,
+ equality_is_safe=equality_mirrors_safely(
+ columns_by_name[mapped_column], datasource.database.db_engine_spec
+ ),
+ )
+ sample_input = _render_sample_input(
+ datasource, mapped_column, operator, sample_values
+ )
+
+ if operator not in PREVIEWABLE_OPERATORS:
+ # Checked before `mirrors`, which lets `TEMPORAL_RANGE` through when the
+ # transform is declared monotonic -- and the single sample value would
+ # then reach `handle_comparison_filter`, which has no case for a range
+ # and raises. The request schema rejects it too; this keeps the function
+ # honest for any other caller.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is mirrored as a pair of bounds, which "
+ "a preview of a single value cannot describe.",
+ operator=operator.value,
+ ),
+ }
+
+ if operator in MIRRORABLE_ALWAYS and not mapping.equality_is_safe:
+ # Withdrawn by `equality_mirrors_safely`, which no declaration about
+ # ordering can change -- so naming monotonicity here would send the
+ # owner to a checkbox that leaves the answer as it is.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter on this text column is not mirrored: "
+ "the database may treat strings that differ in case or "
+ "trailing spaces as equal, and the mirrored predicate could "
+ "then drop rows the filter keeps.",
+ operator=operator.value,
+ ),
+ }
+
+ if not mapping.mirrors(operator):
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is only mirrored when the transform "
+ "preserves ordering, which this one is not declared to do.",
+ operator=operator.value,
+ ),
+ }
+
+ return _preview_probe(
+ datasource,
+ mapping,
+ columns_by_name[mapped_column],
+ operator,
+ sample_values,
+ sample_input,
+ )
+
+
+def _preview_probe(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ mapped_col: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+ sample_input: str,
+) -> dict[str, Any]:
+ """
+ The half of a preview that needs the warehouse.
+
+ Split out from `preview_partition_mapping` so that the gates which answer
+ from the stored mapping alone stay readable as the single run of guard
+ clauses they are. Everything here has either run a query or decided not to.
+ """
+ value = datasource.mirror_probe_request(
+ operator,
+ _probe_input(datasource, mapped_col, operator, sample_values),
+ mapped_col,
+ )
+ if is_unmirrorable(value):
+ # The same step the chart path applies, so the preview cannot promise a
+ # mirror the query declines -- and it reports the reason that step
+ # recorded rather than deriving one of its own, which is what let the
+ # offset case be explained as a precision loss it is not.
+ if value.reason == "offset":
+ # The transform is fine and the column may well compare the whole
+ # instant; what cannot be mirrored is the frame. Advising a
+ # different column here would send the owner after a column they
+ # already have.
+ return {
+ "valid": False,
+ "reason": "offset",
+ "sample_input": sample_input,
+ "error": _(
+ "A filter value carrying a UTC offset is not mirrored: a "
+ "transform is evaluated in the database's own time frame, "
+ "so the mirrored predicate could ask for a partition the "
+ "matching rows are not in. Write the bound without an "
+ "offset to mirror this filter.",
+ ),
+ }
+ if value.reason == "escaping":
+ # Nothing about the column, the operator or the transform is wrong
+ # here, so none of the advice the other branches carry applies: the
+ # driver and the database disagree about how to write this value
+ # down. Said in terms of the value, which is the only thing the
+ # owner can change.
+ return {
+ "valid": False,
+ "reason": "escaping",
+ "sample_input": sample_input,
+ "error": _(
+ "A filter value containing a quote or a backslash is not "
+ "mirrored on this database: the driver and the database do "
+ "not agree on how to write it into a query, so the "
+ "transform would be evaluated at a value the filter does "
+ "not compare. Filters whose values carry neither still "
+ "mirror.",
+ ),
+ }
+ # The transform is fine and the engine evaluates it, the filter just
+ # carries more of the value than the engine compares on this column --
+ # which is the column's type talking, not a broken expression.
+ return {
+ "valid": False,
+ "reason": "resolution",
+ "sample_input": sample_input,
+ "error": _(
+ "This engine compares less of a %(operator)s value on "
+ "%(column)s than the filter carries, so there is no mirror a "
+ "predicate on the partition column could stand in for. Map a "
+ "column the engine compares in full to mirror this operator.",
+ operator=operator.value,
+ column=mapped_col.column_name,
+ ),
+ }
+ errors: list[str] = []
+ type_errors: list[str] = []
+ predicates = build_mirrored_predicates(
+ datasource,
+ mapping,
+ [(operator, value)],
+ errors=errors,
+ type_errors=type_errors,
+ )
+ if type_errors:
+ # Its own reason, because "the database would not evaluate this" and
+ # "it evaluated and answered with the wrong kind of thing" are
+ # different problems with different fixes, and the owner is the only
+ # one who can tell which transform they meant to write.
+ return {
+ "valid": False,
+ "reason": "type",
+ "sample_input": sample_input,
+ "error": type_errors[0],
+ }
+ if not predicates:
+ return {
+ "valid": False,
+ "reason": "engine",
+ "sample_input": sample_input,
+ "error": (
+ _(
+ "The transform could not be evaluated against the "
+ "database: %(reason)s",
+ reason=errors[0],
+ )
+ if errors
+ else _("The transform could not be evaluated against the database.")
+ ),
+ }
+
+ return {
+ "valid": True,
+ "sample_input": sample_input,
+ "emitted_predicate": _render_predicate(datasource, predicates[0]),
+ }
+
+
+def _probe_input(
+ datasource: SqlaTable,
+ column: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+) -> Any:
+ """
+ The sample values as the query path would bind them.
+
+ The request carries samples as strings, and the probe is keyed on exactly
+ what it is handed, so passing them through raw asks the engine a different
+ question from the one a chart asks. A sample of ``2025`` on a numeric
+ column has to arrive as the integer the chart compares: under a transform
+ of ``typeof(:value)`` the raw string previewed ``'text'`` where the chart
+ emitted ``'integer'``. And because `_probe_cache_key` keys on each value's
+ ``repr``, the two also missed each other's cache entirely -- so the "a
+ previewed transform warms the chart path for free" claim in
+ `preview_partition_mapping`'s docstring did not actually hold.
+
+ Coerced by `filter_values_handler`, the same function the query path uses,
+ rather than by a second implementation of the same rules. Everything the
+ query path then does to the coerced value -- rendering an expression as a
+ literal, widening a bound, declining a comparison the engine resolves too
+ coarsely -- is `ExploreMixin.mirror_probe_request`'s, and the caller hands
+ this result straight to it.
+
+ Ranges are not previewable (see `PREVIEWABLE_OPERATORS`), so the bound
+ conversion `_collect_partition_mirror_range` applies -- a ``datetime`` into
+ the column's stored representation -- has no counterpart here.
+
+ An array column is the exception to `filter_values_handler`: its predicate
+ is built from the raw value, parsed into elements and rendered as the
+ engine's own array literal, so the chart path probes that literal
+ (`ExploreMixin._array_mirror_probe_value`) and this does too. Passing the
+ handled text instead previewed ``length('[1, 2]')`` for a filter whose
+ query probes ``length(array(1, 2))``.
+
+ Answers with a value, or `None` where an engine spec claims array columns
+ without an array literal -- which `mirror_probe_request` then declines, as
+ the chart path declines it. It may also answer with an `Unmirrorable` the
+ array branch raised itself, which `mirror_probe_request` passes through;
+ otherwise the decline is that method's to make, and the caller hands this
+ straight to it.
+ """
+ is_list = operator == FilterOperator.IN
+ column_spec = datasource.db_engine_spec.get_column_spec(native_type=column.type)
+ if (
+ column_spec
+ and column_spec.generic_type == utils.GenericDataType.MULTI_VALUE
+ and operator in MIRRORABLE_ALWAYS
+ ):
+ # `=` and `IN` are the previewable operators the array branch builds a
+ # literal for; a bound on an array column binds the handled value on
+ # the chart path too, so it falls through to the same here.
+ return datasource._array_mirror_probe_value( # noqa: SLF001
+ sample_values if is_list else sample_values[0],
+ operator,
+ datasource.db_engine_spec.get_array_element_type(column.type),
+ datasource.db_engine_spec,
+ )
+ handled = datasource.filter_values_handler(
+ # `list[str]` is not a `list[FilterValue]` to mypy, invariantly, even
+ # though every `str` is a `FilterValue`.
+ values=cast(FilterValues, sample_values if is_list else sample_values[0]),
+ operator=operator,
+ target_generic_type=(
+ column_spec.generic_type if column_spec else utils.GenericDataType.STRING
+ ),
+ target_native_type=column.type,
+ is_list_target=is_list,
+ db_engine_spec=datasource.db_engine_spec,
+ db_extra=datasource.db_extra,
+ )
+ # No `ColumnElement` conversion here: an epoch-milliseconds sample comes back
+ # as engine SQL rather than a value, and `mirror_probe_request` renders it --
+ # the same step, on the same values, as for a chart filter.
+ return handled
+
+
+def _render_sample_input(
+ datasource: SqlaTable,
+ mapped_column: str,
+ operator: FilterOperator,
+ values: list[str],
+) -> str:
+ """
+ The filter being previewed, written the way an owner would read it.
+
+ Display-only -- it is never executed -- but it is still read as SQL, so the
+ column is quoted and the values are rendered by the dialect rather than
+ concatenated raw. A column named ``order date`` would otherwise come out as
+ two bare words.
+ """
+ quoted = datasource.quote_identifier(mapped_column)
+ if operator == FilterOperator.IN:
+ rendered = ", ".join(
+ _render_literal(datasource.database, value) for value in values
+ )
+ return f"{quoted} IN ({rendered})"
+ return (
+ f"{quoted} {operator.value} {_render_literal(datasource.database, values[0])}"
+ )
+
+
+def _render_predicate(datasource: SqlaTable, predicate: ColumnElement[Any]) -> str:
+ """
+ Compile a mirrored predicate to the text a reader would see in View query.
+
+ Every value in it is a probed constant by this point, so ``literal_binds``
+ renders the same literals the chart query carries.
+ """
+ return _compile_literal(predicate, _dialect_for(datasource.database)).replace(
+ "\n", " "
+ )
+
+
+def _render_literal(database: Database, value: Any) -> str:
+ """
+ Render a value the way it appears in the generated SQL.
+
+ Compiled by the dialect rather than formatted by hand. `str()` would render
+ a NULL as the Python repr `None` and leave a date unquoted, neither of which
+ is SQL, and hand-rolled quote-doubling would only ever have been right for
+ strings.
+ """
+ return _compile_literal(sa.literal(value), _dialect_for(database))
+
+
+def build_mirrored_predicates(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ requests: list[tuple[FilterOperator, Any]],
+ *,
+ errors: list[str] | None = None,
+ type_errors: list[str] | None = None,
+) -> list[ColumnElement[Any]]:
+ """
+ Turn collected ``(operator, value)`` mirror requests into predicates.
+
+ ``requests`` is expected to be deduplicated by the caller. Every value is
+ resolved in a single probe round trip -- one per chart query at most -- then
+ emitted as a literal constant, so "View query" shows the reader an ordinary
+ ``WHERE`` clause rather than an inline expression.
+
+ A strict bound is emitted non-strictly; see `mirror_operator`. That happens
+ here, at the one point where a ``FilterOperator`` becomes SQL, rather than
+ at the collection sites in `ExploreMixin`: the preview endpoint calls this
+ directly, so this is what keeps the predicate the editor shows an owner and
+ the predicate the chart carries from disagreeing.
+
+ :param errors: optional sink; see `evaluate_transform`.
+ :param type_errors: optional sink for a probe result the partition column
+ cannot hold -- see `probed_value_type_error`. Separate from ``errors``
+ because the two say different things to an owner: that one is "the
+ database would not evaluate this", and this one is "it evaluated, and
+ answered with the wrong kind of thing".
+ """
+ if not requests:
+ return []
+
+ partition_column = next(
+ (
+ column
+ for column in datasource.columns
+ if column.column_name == mapping.partition_column
+ ),
+ None,
+ )
+ if partition_column is None:
+ return []
+
+ # Flatten every value that needs probing into one list, remembering how many
+ # each request consumed so the results can be handed back out.
+ flat: list[Any] = []
+ spans: list[tuple[FilterOperator, int, int]] = []
+ for operator, value in requests:
+ values = list(value) if operator == FilterOperator.IN else [value]
+ spans.append((operator, len(flat), len(values)))
+ flat.extend(values)
+
+ evaluated = evaluate_transform(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ mapping.value_transform,
+ flat,
+ errors=errors,
+ )
+ if evaluated is None:
+ return []
+
+ if not _bounds_are_ordered(evaluated, spans):
+ return []
+
+ # Declining here is the last chance to decline at all: once these
+ # predicates are in the statement, a value the partition column cannot
+ # hold fails the whole chart rather than its pruning.
+ if reason := probed_value_type_error(partition_column, evaluated):
+ logger.warning(
+ "Partition transform returned a value the partition column cannot "
+ "hold; queries will not prune: %s",
+ reason,
+ )
+ if type_errors is not None:
+ type_errors.append(reason)
+ # Deliberately *not* recorded as a mirror verdict. The transform
+ # evaluated perfectly; what failed is the comparison against this
+ # dataset's partition column -- and `_mirror_verdict_cache_key` is
+ # keyed on database, catalog, schema and transform, with no partition
+ # column in it. Recorded, this dataset-specific outcome answered for
+ # every other dataset sharing the transform: `CAST(:value AS text)`
+ # mirroring happily onto a text key in dataset A was reported
+ # `evaluable: false` -- and its pruning indicator hidden -- because
+ # someone previewed the same transform against a numeric key in
+ # dataset B. A probe cache hit on A never rewrites the verdict, so it
+ # stayed wrong until the entry expired.
+ return []
+
+ sqla_col = datasource.convert_tbl_column_to_sqla_col(partition_column)
+ predicates = _predicates_from_probe(
+ sqla_col, datasource.db_engine_spec, evaluated, spans
+ )
+ if not predicates:
+ return []
+
+ # A comparison against a NULL partition value is NULL, so a row parked in a
+ # NULL partition is dropped by the mirror even when the real filter matches
+ # it -- Hive and Impala's default partition, or a transform that returns
+ # NULL for an input it cannot convert. The mirror only has to be no
+ # narrower than the filter it stands in for, so admitting NULL partitions
+ # keeps those rows. Engines still prune; they read one extra partition.
+ return [sa.or_(sa.and_(*predicates), sqla_col.is_(None))]
+
+
+def _predicates_from_probe(
+ sqla_col: ColumnElement[Any],
+ db_engine_spec: type[BaseEngineSpec],
+ evaluated: list[Any],
+ spans: list[tuple[FilterOperator, int, int]],
+) -> list[ColumnElement[Any]]:
+ """
+ One predicate on the partition column per surviving mirror request.
+
+ A request whose probe answered `None` for any of its values is skipped
+ rather than emitted: `col = NULL` is `NULL`, so it would drop every row the
+ filter keeps. A strict bound is emitted non-strictly; see `mirror_operator`.
+ """
+ predicates: list[ColumnElement[Any]] = []
+ for operator, start, length in spans:
+ chunk = evaluated[start : start + length]
+ if any(value is None for value in chunk):
+ continue
+ if operator == FilterOperator.IN:
+ # The probe answers per value, so a transform over a mixed-number
+ # filter can answer with a mixed-number partition key -- and
+ # `in_` infers the bind type from the first element it is handed.
+ # Without this, probe results of `[33, 29.02]` emit
+ # `IN (33, 29)` and prune away the partition holding `29.02`.
+ predicates.append(sqla_col.in_(normalize_mixed_numbers(chunk)))
+ else:
+ predicates.append(
+ db_engine_spec.handle_comparison_filter(
Review Comment:
A transform that emits a backslash is not covered by the literal round-trip guard: only the filter *inputs* are checked, while the probe *results* in `evaluated` are rendered straight into the chart SQL. On Spark/Hive, a transform like `concat(:value, chr(92), 'b')` maps the safe input `'a'` to the partition key `a\b`, but the emitted `partition_col = 'a\b'` is read by the engine with `\b` as a backspace escape, so the mirror matches no partition and the chart silently drops rows the original filter keeps. Should the evaluated values go through the same `literal_round_trips` check (declining the mirror when they fail) before the predicates are built?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4350197811
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,3583 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Writing the value into the probe
+--------------------------------
+The probe evaluates the transform at a *literal*, because it runs with no bound
+parameters at all -- so every value is written into SQL text by the driver's
+literal renderer and read back by the engine's lexer, and the two do not always
+agree. SQLAlchemy's default renderer doubles apostrophes and leaves backslashes
+alone; Hive honours backslash escapes and not doubling, so ``'O''Brien'`` is
+read there as two adjacent literals and ``'x\\''`` ends four characters into a
+value the filter carries whole. A disagreement is either a mirror built from a
+value nobody filtered on -- dropping rows the filter keeps -- or, where the
+value closes its own quote, an expression of the filterer's choosing running in
+the probe.
+
+Which side is right is not knowable from the driver: it is a per-session server
+setting (``standard_conforming_strings``, ``NO_BACKSLASH_ESCAPES``,
+``spark.sql.parser.escapedStringLiterals``), and SQLAlchemy's own view of it is
+only correct on a dialect that has connected. So escaping is not what makes
+this safe. `literal_round_trips` renders the literal and reads it back in the
+engine's own dialect instead, and a value that does not survive the trip is not
+mirrored -- the usual trade, pruning for correctness. `probe_sql_is_evaluable`
+re-reads the finished statement behind it.
+
+The probe's *answers* make the same trip, in the other direction. The chart
+query is compiled with ``literal_binds``, so a probed partition key is rendered
+into its SQL by the same renderer and read by the same lexer -- and
+``concat(:value, chr(92), 'b')`` turns the unremarkable input ``a`` into the key
+``a\\b``, which Hive reads back as ``a`` followed by a backspace. So
+`_predicates_from_probe` asks `literal_round_trips` about each result too, and
+declines the request rather than emitting a predicate no row can satisfy: the
+mirror is ``AND``-ed onto the query, so a mirror that matches nothing costs the
+chart its rows rather than its pruning.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: The opening and closing delimiters of each kind of Jinja block. The probe
+#: would render these in a different context at a different time from the chart
+#: query, so a transform holding one is rejected at save time.
+JINJA_BLOCK_DELIMITERS = (("{{", "}}"), ("{%", "%}"), ("{#", "#}"))
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: A PostgreSQL Unicode-escaped identifier, ``U&"..."``.
+#:
+#: The second construct that breaks the premise above, and in the same way:
+#: ``U&"\\0071uery_to_xml"(...)`` parses as an anonymous function whose name is
+#: the *literal* ``\\0071uery_to_xml``, so the function denylist is matching a
+#: name the engine never sees -- PostgreSQL decodes the escape and runs
+#: ``query_to_xml``, handing a dataset owner rows from outside their RLS scope
+#: through the preview's ``emitted_predicate``.
+#:
+#: Normalizing the escapes and re-checking would be the other repair, and is
+#: worse: it means reimplementing one engine's identifier decoding well enough
+#: to be a security boundary. Refusing the construct is exact, and costs
+#: nothing real -- a transform is a scalar function of ``:value``, and there is
+#: no reason to name a function or column through an escape sequence.
+#:
+#: Refused on every engine, like the executable comment, so a transform stored
+#: on SQLite cannot detonate when the dataset is re-pointed at PostgreSQL. The
+#: ``&`` may be separated from the ``U`` by nothing at all, but whitespace or a
+#: comment between the prefix and the string is not accepted by PostgreSQL
+#: either, so the strict form is the whole surface.
+#:
+#: Matched in raw text, so the prefix is refused inside a string literal too.
+#: That is the same trade the executable comment makes and has the same
+#: justification: a gate whose contract is to fire *before* the parse cannot
+#: ask the parse whether the text was quoted. ``concat(:value, 'u&"x"')`` is
+#: refused, which costs an owner nothing anyone writes.
+UNICODE_ESCAPED_IDENTIFIER_RE = re.compile(r'\bU&"', re.IGNORECASE)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate: a transform such as
+#: ``datediff(day, :value, LOCALTIMESTAMP)`` for a relative partition key is
+#: evaluated once and then keeps emitting yesterday's answer, so the chart
+#: silently drops rows after midnight.
+#:
+#: Matched by SQL function name, so every engine's spelling of "now" has to be
+#: named -- the ANSI four were not enough. Listed rather than delegated to the
+#: engine specs because the risk is the same everywhere and a spec that had not
+#: got round to declaring its own would fail open; a name no engine has is
+#: inert, so over-listing costs nothing.
+NON_DETERMINISTIC_FUNCTIONS = {
+ # ANSI, and the engines that spell it this way.
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "LOCALTIME",
+ "LOCALTIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+ # PostgreSQL. `now()` is statement-stable; these two are not even that.
+ "CLOCK_TIMESTAMP",
+ "STATEMENT_TIMESTAMP",
+ "TIMEOFDAY",
+ # MySQL and MariaDB.
+ "CURDATE",
+ "CURTIME",
+ "SYSDATE",
+ "UTC_DATE",
+ "UTC_TIME",
+ "UTC_TIMESTAMP",
+ "UUID_SHORT",
+ # Oracle.
+ "SYSTIMESTAMP",
+ "SYS_GUID",
+ # SQL Server.
+ "GETDATE",
+ "GETUTCDATE",
+ "SYSDATETIME",
+ "SYSUTCDATETIME",
+ "SYSDATETIMEOFFSET",
+ "NEWID",
+ # BigQuery.
+ "CURRENT_DATETIME",
+ "GENERATE_UUID",
+ # Snowflake.
+ "RANDSTR",
+ "UUID_STRING",
+ # ClickHouse.
+ "NOW64",
+ "RANDCANONICAL",
+ "GENERATEUUIDV4",
+ # H2 and Derby, which the test fixtures use.
+ "RANDOM_UUID",
+}
+
+#: The wall-clock names an engine evaluates with no parentheses at all.
+#:
+#: These parse as *column references*, not functions, so the name-based walk
+#: below cannot see them: `datediff(UTC_DATE, :value)` on MySQL and
+#: `:value - SYSDATE` on Oracle both cleared the gate and froze probe time into
+#: a cached mirror.
+#:
+#: A subset of `NON_DETERMINISTIC_FUNCTIONS` rather than the whole of it,
+#: because refusing a bare name costs an owner a column genuinely called that.
+#: Only the names SQL lets you write without ``()`` are listed -- the datetime
+#: keywords -- so `rand`, `uuid` and `newid`, which always need parentheses and
+#: are plausible column names, stay out.
+BARE_WALL_CLOCK_KEYWORDS = frozenset(
+ {
+ "current_date",
+ "current_time",
+ "current_timestamp",
+ "localtime",
+ "localtimestamp",
+ "utc_date",
+ "utc_time",
+ "utc_timestamp",
+ "sysdate",
+ "systimestamp",
+ }
+)
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+class Unmirrorable:
+ """
+ A filter no mirror can stand in for, and why.
+
+ Returned by `ExploreMixin.mirror_probe_request` for a value the engine
+ compares more coarsely than the filter carries, one it cannot render as a
+ literal, one whose rendered literal the engine would not read back as the
+ same value, one in a time frame the transform would discard, or an ``IN``
+ list with a member of any of those kinds. An object rather than `None`,
+ because `None` is a filter value in its own right.
+
+ The reason rides along because the preview has to explain the decline to
+ the owner, and the two declines want different advice: "the engine compares
+ less of this value than you typed, so map a column it compares in full" is
+ sound guidance for a `DATE` column and actively misleading for an
+ offset-bearing bound on a `TIMESTAMP` one, which already is such a column.
+ Carried rather than re-derived so the preview's explanation cannot come
+ apart from the chart path's decision.
+
+ Lives here rather than beside that method so the preview can read it too:
+ `superset.models.helpers` imports this module, so these can only cross the
+ boundary in this direction. Both callers recognise the same instances -- a
+ preview that answered "valid" for a request the chart path declines is the
+ drift this is here to prevent.
+ """
+
+ __slots__ = ("reason",)
+
+ def __init__(self, reason: str) -> None:
+ self.reason = reason
+
+ def __repr__(self) -> str:
+ return f"<Unmirrorable {self.reason}>"
+
+
+#: The ordinary decline: whatever the mirror cannot be built from, with the
+#: engine's own comparison resolution as the reason an owner can act on.
+UNMIRRORABLE = Unmirrorable("resolution")
+
+#: A value carrying a UTC offset, declined whatever the column's resolution.
+#: A transform such as ``CAST(:value AS TIMESTAMP)`` drops the offset, so even
+#: an engine that compares the whole instant would be probed in the wrong
+#: frame -- which is not something mapping a different column fixes.
+UNMIRRORABLE_OFFSET = Unmirrorable("offset")
+
+#: A value the driver and the engine would not spell the same way, declined
+#: whatever the column's resolution and whatever the operator. Nothing about
+#: the column or the transform fixes it -- see `literal_round_trips` -- so the
+#: advice the resolution reason carries would send an owner after the wrong
+#: thing entirely.
+UNMIRRORABLE_ESCAPING = Unmirrorable("escaping")
+
+
+def is_unmirrorable(value: Any) -> bool:
+ """Whether `mirror_probe_request` declined this request."""
+ return isinstance(value, Unmirrorable)
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def _native_generic_type(
+ column: "TableColumn",
+) -> utils.GenericDataType | None:
+ """
+ What the engine spec makes of ``column``'s declared type.
+
+ `TableColumn.type_generic` answers ``TEMPORAL`` for every column carrying
+ ``is_dttm``, which is the right answer for a chart's time axis and the
+ wrong one for a comparison: an epoch ``BIGINT`` is a number to the engine
+ however it is labelled here. Falls back to the flag where the spec has no
+ answer, so a type Superset cannot resolve is no worse off than before.
+ """
+ try:
+ column_spec = column.db_engine_spec.get_column_spec(
+ column.type, db_extra=column.db_extra
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ column_spec = None
+ if column_spec is not None and column_spec.generic_type is not None:
+ return column_spec.generic_type
+ try:
+ return column.type_generic
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+#: A declared type naming an array: PostgreSQL's ``TEXT[]`` / ``INTEGER[][]``
+#: / ``int[3]``, and the ``ARRAY<...>`` / ``ARRAY(...)`` / ``Array(...)``
+#: spellings of Hive, Spark, Trino, BigQuery and ClickHouse.
+#: The bracket body is written so no two runs can match the same blanks:
+#: ``\s*\d*\s*`` backtracks polynomially on a long run of spaces.
+_ARRAY_TYPE_RE = re.compile(r"(?:\[\s*(?:\d+\s*)?\])+\s*$|^\s*ARRAY\b", re.IGNORECASE)
+
+
+def declares_array_type(column_type: str | None) -> bool:
+ """
+ Whether a declared column type is an array, whatever the engine spec says.
+
+ The engine spec only reports ``MULTI_VALUE`` where it has opted into
+ ``supports_multivalue_columns``; PostgreSQL has not, and resolves ``TEXT[]``
+ to ``STRING`` and ``INTEGER[]`` to ``NUMERIC``. So an array partition column
+ there cleared the array refusal, previewed valid, and every equality chart
+ on the mapping failed with ``malformed array literal``. The declared type
+ is what the engine will compare, so it is read directly as well.
+ """
+ return bool(column_type and _ARRAY_TYPE_RE.search(column_type))
+
+
+#: Declared types whose comparison ignores trailing blanks.
+#:
+#: The fixed-width character types, which the SQL standard has compare as
+#: though both sides were padded to the same length -- so ``'US'`` and
+#: ``'US '`` are equal in a ``CHARACTER(3)``, while ``lower()`` of the two is
+#: not. Spelled out rather than matched by prefix because the variable-width
+#: names start with the same letters: ``VARCHAR`` and ``CHARACTER VARYING``
+#: compare the blanks and must not land here.
+PADDED_CHARACTER_TYPES = frozenset(
+ {
+ "CHAR",
+ "NCHAR",
+ # PostgreSQL's own name for ``CHARACTER``, which is what reflection
+ # reports for a ``CHAR(n)`` column there.
+ "BPCHAR",
+ "CHARACTER",
+ "NATIONAL CHAR",
+ "NATIONAL CHARACTER",
+ }
+)
+
+
+def _is_padded_character_type(column: TableColumn) -> bool:
+ """
+ Whether ``column``'s declared type compares without its trailing blanks.
+
+ Read off the declared type rather than the engine spec's resolved one: the
+ specs map ``CHAR`` and ``VARCHAR`` onto the same `sqlalchemy.String`, so
+ the distinction this needs is gone by then. The length suffix is dropped
+ and the name matched against `PADDED_CHARACTER_TYPES`, so an unfamiliar
+ spelling answers ``False`` and the engine-level flag decides as before --
+ this gate adds a decline rather than lifting one. A column with no
+ declared type has nothing to read, and answers the same way.
+ """
+ if not isinstance(column.type, str):
+ return False
+ native = re.sub(r"\s+", " ", column.type.strip().upper())
+ return native.split("(")[0].strip() in PADDED_CHARACTER_TYPES
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ Padding is asked about per column, because it is a property of the *type*
+ rather than of the engine. ``binary_string_comparison`` speaks for an
+ engine's default text comparison, and on PostgreSQL -- which declares it
+ -- a ``CHAR(2)`` still matches a filter for ``'US '`` against a stored
+ ``'US'``, because the standard says a padded character type compares
+ without its trailing blanks. The mirror ``region_key = lower('US ')`` then
+ excludes the row. So a fixed-width character type declines whatever the
+ engine says, and an engine that ignores trailing blanks on its *variable*
+ types says so by not declaring the flag at all (see `RedshiftEngineSpec`).
+
+ The type asked for is the engine spec's reading of the column's declared
+ type, not `TableColumn.type_generic`, which answers ``TEMPORAL`` for
+ anything carrying ``is_dttm``. A ``VARCHAR`` flagged temporal is still text
+ to the engine: on MySQL a filter for ``'2026-01-01T00:00:00'`` matches a
+ stored ``'...t00:00:00'``, while the mirror ``p = hex('...T...')`` excludes
+ it -- and asking the semantic flag skipped the check entirely.
+
+ A type the spec cannot classify declines, which is what the paragraph above
+ promises and what only the exception branch used to do. PostgreSQL's
+ ``citext`` matches no type pattern, so it answered ``None`` -- neither
+ string nor not-string -- and was waved through, which is precisely wrong
+ for a type whose whole purpose is case-insensitive comparison. Declining
+ costs the pruning; admitting it costs rows.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ # Ahead of the generic-type question, which a padded type can lose: the
+ # specs map ``CHARACTER`` onto no generic type at all on some engines, and
+ # a fixed-width character type is a string whether or not Superset can say
+ # so from the name.
+ if _is_padded_character_type(column):
+ return False
+ generic_type = _native_generic_type(column)
+ if generic_type is None:
+ return False
+ if generic_type != utils.GenericDataType.STRING:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
Review Comment:
A PostgreSQL `JSONB` column maps to `GenericDataType.STRING`, so this returns the engine's `binary_string_comparison` (true) and equality mirroring is allowed. `JSONB` does not keep input spelling: the stored value `{"a":1}` reads back as `{"a": 1}`. With mapped column `j JSONB`, partition column `p TEXT`, and transform `CAST(:value AS TEXT)`, a filter `j == '{"a":1}'` matches the row, but the probe renders the compact input and adds `p = '{"a":1}' OR p IS NULL`, which excludes the row whose `p` is `{"a": 1}`. Should `JSON`/`JSONB` decline here like the padded character types do?
##########
superset/models/helpers.py:
##########
@@ -4449,36 +4558,777 @@ def dttm_sql_literal(self, dttm: datetime, col: "TableColumn") -> str:
return f"""'{dttm.strftime("%Y-%m-%d %H:%M:%S.%f")}'"""
- def get_time_filter( # pylint: disable=too-many-arguments # noqa: C901
+ def _mirror_probe_value(self, dttm: datetime, col: Optional["TableColumn"]) -> Any:
+ """
+ ``dttm`` in the mapped column's own stored representation.
+
+ The predicate this mirror stands in for compares the column against
+ `dttm_sql_literal(dttm, col)`, so the transform has to be probed with
+ the same value. On a column stored as an epoch integer, ``T`` is a
+ function of an integer: probing it with a `datetime` either returns
+ something unrelated to the partition keys or raises, and a raise costs
+ the dataset its pruning silently.
+
+ Only the ``python_date_format`` branches of `dttm_sql_literal` are
+ reproduced, because only those produce a *value*. `convert_dttm` yields
+ engine-specific SQL text, which cannot be bound as a parameter; its own
+ divergence from the probe is handled by widening the bounds instead
+ (`_engine_literal_resolution`).
+
+ In `dttm_sql_literal`'s own order, though: it asks ``convert_dttm``
+ first and reaches the format only when the engine answers nothing. A
+ column can carry both -- a TIMESTAMP with a ``%Y%m%d``
+ ``python_date_format``, or an entry in
+ ``python_date_format_by_column_name`` -- and applying the format
+ unconditionally probed a value the real predicate never compares.
+ ``event_time >= '2026-01-01 00:00:00'`` mirrored as
+ ``partition_col >= '20260101'``, and a January 15 row keyed
+ ``2026-01-15`` sorts below that string, so the chart lost a row the
+ filter keeps.
+
+ Where the engine does answer, the `datetime` is returned unchanged and
+ the widening path takes over -- which is exactly what already happens
+ for every temporal column that carries no format at all.
+ """
+ if col is None:
+ return dttm
+
+ if col.type and self.db_engine_spec.convert_dttm(
+ col.type, dttm, db_extra=self.db_extra
+ ):
+ # The format is unreachable in `dttm_sql_literal` for this column,
+ # so reproducing it here would describe a different bound.
+ return dttm
+
+ tf = col.python_date_format
+ if not tf and self.db_extra:
+ tf = self.db_extra.get("python_date_format_by_column_name", {}).get(
+ col.column_name
+ )
+ if not tf:
+ return dttm
+
+ if tf in EPOCH_FORMATS:
+ dttm_tz_aware = dttm
+ if dttm_tz_aware.tzinfo is None:
+ dttm_tz_aware = dttm_tz_aware.replace(tzinfo=timezone.utc)
+ return int(dttm_tz_aware.timestamp()) * EPOCH_FORMATS[tf]
+ return dttm.strftime(tf)
+
+ def _engine_literal_resolution(
+ self, dttm: datetime, col: Optional["TableColumn"]
+ ) -> LiteralResolution:
+ """
+ How much of ``dttm`` survives into this engine's literal for ``col``.
+
+ The real predicate compares `dttm_sql_literal(dttm, col)`, so whatever
+ that literal throws away is a bound the engine never sees. A mirror
+ derived from the full precision then describes a *narrower* range than
+ the predicate it stands in for -- and narrower means it drops rows the
+ filter keeps.
+
+ Two things get thrown away in practice:
+
+ - the sub-second part. SQLite renders a timestamp with
+ ``timespec="seconds"``.
+ - the time of day entirely. Every engine spec with a ``types.Date``
+ branch renders ``dttm.date().isoformat()``, so Presto, Trino,
+ BigQuery and some two dozen others answer `DATE '2026-01-01'` for a
+ bound of 10:00 -- and `T(DATE '2026-01-01')` is below the mirror's
+ own lower bound, so the whole first day is dropped.
+
+ Detected rather than enumerated per engine, because the branch depends
+ on the column's type as well as the spec: instants differing only in the
+ part under test render as the same text exactly when the engine has
+ thrown that part away.
+
+ The day test uses two fixed times of day rather than ``dttm`` and one
+ alternative, so a bound that happens to sit on the hour the alternative
+ uses cannot read as "no time at all". Neither probe sits at midnight on
+ purpose: SQLite renders a DATE column at exactly midnight as a bare
+ date, so a midnight probe would differ from its alternative for a
+ reason that has nothing to do with resolution.
+
+ Likewise both sub-second probes carry a non-zero remainder. Comparing
+ against ``dttm`` truncated to the second looks like the obvious test and
+ is wrong for the same formatting-boundary reason.
+
+ A non-temporal column has no answer here, and asking anyway gets a wrong
+ one. SQLite's ``convert_dttm`` renders for ``types.String`` as well as
+ for the date types, so a ``VARCHAR`` mapped column reads as
+ second-resolution -- and a filter value that happens to *look* like an
+ instant then has its bound rounded as though the engine had truncated
+ it. On a VARCHAR ``code`` mapped onto a VARCHAR ``p`` by ``:value``,
+ ``code < '2026-07-06T10:08:11.500000'`` was mirrored as
+ ``p <= '2026-07-06 10:08:12.000000'``; a space sorts before ``T``, so a
+ row holding ``2026-07-06T09:00:00`` fell outside the mirror while
+ matching the filter.
+
+ The guard lives here rather than in each caller so this and
+ `_column_literal_resolution` cannot disagree about which column is
+ coarse -- which is the same reason that helper delegates to this one.
+
+ "Temporal" is the column's generic type, not just its ``is_dttm`` flag.
+ `get_time_filter` renders a bound through ``convert_dttm`` for any
+ ``DATE`` column, flagged or not, so a ``DATE`` column left unflagged
+ still compares a bare day -- and skipping the resolution check there
+ would hand the probe 10:00 for a bound the engine reads as midnight.
+ """
+ if col is None or not col.type or col.type_generic != GenericDataType.TEMPORAL:
+ return LiteralResolution.FULL
+
+ def render(moment: datetime) -> Optional[str]:
+ return self.db_engine_spec.convert_dttm(
+ col.type, moment, db_extra=self.db_extra
+ )
+
+ try:
+ early = render(dttm.replace(hour=1, minute=2, second=3, microsecond=444444))
+ late = render(
+ dttm.replace(hour=22, minute=33, second=44, microsecond=555555)
+ )
+ if early is not None and early == late:
+ return LiteralResolution.DAY
+
+ # Flooring to the second is a no-op on a bound that has no
+ # sub-second part, so there is nothing to detect.
+ if not dttm.microsecond:
+ return LiteralResolution.FULL
+
+ first = render(dttm.replace(microsecond=111111))
+ second = render(dttm.replace(microsecond=222222))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return LiteralResolution.FULL
+
+ if first is not None and first == second:
+ return LiteralResolution.SECOND
+ return LiteralResolution.FULL
+
+ def _round_bounds_outward(
self,
- time_col: "TableColumn",
+ start_dttm: Optional[datetime],
+ end_dttm: Optional[datetime],
+ col: Optional["TableColumn"],
+ ) -> tuple[Optional[datetime], Optional[datetime]]:
+ """
+ The bounds widened to whatever the engine's literal actually resolves to.
+
+ Rounding outward is never narrower than the predicate being mirrored,
+ which is the only property the mirror has to hold.
+ """
+ resolutions = {
+ self._engine_literal_resolution(bound, col)
+ for bound in (start_dttm, end_dttm)
+ if bound is not None
+ }
+
+ if LiteralResolution.DAY in resolutions:
+ # The engine compares a bare date, so the real predicate's lower
+ # bound is the start of that day and its upper bound admits the
+ # whole of the day before. Anything finer excludes rows it keeps.
+ if start_dttm is not None:
+ start_dttm = start_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ )
+ if end_dttm is not None and end_dttm != end_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ ):
+ end_dttm = end_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ ) + timedelta(days=1)
+ elif LiteralResolution.SECOND in resolutions:
+ if start_dttm is not None:
+ start_dttm = start_dttm.replace(microsecond=0)
+ if end_dttm is not None and end_dttm.microsecond:
+ end_dttm = end_dttm.replace(microsecond=0) + timedelta(seconds=1)
+
+ return start_dttm, end_dttm
+
+ def _literal_is_coarser_than(
+ self, dttm: datetime, col: Optional["TableColumn"]
+ ) -> bool:
+ """
+ Whether the engine's literal for ``dttm`` throws away part of it.
+
+ Unlike a range, an equality cannot be widened outward, so the only safe
+ answer when the engine compares less than the full value is to decline
+ the mirror.
+ """
+ resolution = self._engine_literal_resolution(dttm, col)
+ if resolution is LiteralResolution.DAY:
+ return dttm != dttm.replace(hour=0, minute=0, second=0, microsecond=0)
+ if resolution is LiteralResolution.SECOND:
+ return bool(dttm.microsecond)
+ return False
+
+ def _column_literal_resolution(
+ self, col: Optional["TableColumn"]
+ ) -> LiteralResolution:
+ """
+ How much of *any* value this engine compares on ``col``.
+
+ `_engine_literal_resolution` answers about a particular instant, which
+ is what a mirror derived from one needs. Two callers have no instant to
+ ask about -- the summary the Explore glyph reads, and a filter value
+ `_instant_from_filter_value` cannot read as an instant at all -- and
+ both need the column's own answer. Through one helper so that the glyph
+ and the query path cannot disagree about which column is coarse, which
+ is the same reason `mirrorable_operators` is computed once.
+
+ A non-temporal column has no answer, and asking anyway gets a wrong one:
+ SQLite's ``convert_dttm`` renders for ``types.String`` as well as for the
+ date types, so a reference instant makes a ``VARCHAR`` mapped column look
+ second-resolution -- and ``country = 'US'``, the text half of this
+ feature, reads as a value the engine compares coarsely.
+
+ That guard is `_engine_literal_resolution`'s, not this function's. It
+ used to be here, on the belief that the per-instant callers never met
+ the case because they arrive only with a value that parsed as an
+ instant -- which is untrue of a text column holding ISO-shaped text,
+ where the value parses and the column is still not temporal.
+ """
+ return self._engine_literal_resolution(_RESOLUTION_REFERENCE_INSTANT, col)
+
+ def _round_bound_outward(
+ self,
+ instant: datetime,
+ col: Optional["TableColumn"],
+ *,
+ is_upper: bool,
+ ) -> datetime:
+ """
+ One bound widened to whatever the engine resolves ``col`` to.
+
+ `_round_bounds_outward` answers for a since/until pair, because a time
+ range is the shape it was written for. A single comparison is one end of
+ such a pair with the other end absent, and the widening is per-end
+ already -- a lower bound moves back, an upper bound forward.
+
+ Narrowing the return type is the other half of the point: a bound handed
+ in non-`None` comes back non-`None`, and saying so here saves every
+ caller from re-establishing it.
+ """
+ start_dttm, end_dttm = self._round_bounds_outward(
+ None if is_upper else instant,
+ instant if is_upper else None,
+ col,
+ )
+ rounded = end_dttm if is_upper else start_dttm
+ return rounded if rounded is not None else instant
+
+ def _in_column_number_type(self, value: Any, col: Optional["TableColumn"]) -> Any:
+ """
+ A numeric ``value`` in the number type the mapped column stores.
+
+ The engine compares a number against the column in the column's own
+ domain, so ``n = '1.0'`` on an integer ``n`` matches the row holding
+ ``1``. `filter_values_handler` hands over ``1.0``, though, and a
+ transform whose output depends on the representation --
+ ``CAST(:value AS TEXT)`` answers ``'1.0'`` where the row's key is
+ ``'1'`` -- then mirrors to a partition value no matching row holds.
+ Probing at the value the column would hold keeps ``T(col) = T(v)``.
+
+ Integer columns only. A non-integral value on an integer column is
+ returned unchanged -- it matches no row, so its mirror cannot drop one.
+
+ Nothing is converted for an approximate or exact decimal column, even
+ though ``1`` and ``1.0`` are the same number to a ``REAL``. What the
+ transform sees is the *literal*, and how an engine renders one is not
+ something the engine spec exposes: on PostgreSQL ``CAST(1.0 AS TEXT)``
+ is ``'1.0'`` while the ``REAL`` column holding that value renders as
+ ``'1'``, so coercing the value to ``float`` mirrored onto a partition
+ key no matching row holds -- the same failure this helper exists to
+ stop, in the other direction. A ``DECIMAL`` column says it louder,
+ since its text also depends on a scale the spec does not carry. For
+ both, the rendering stays the owner's assumption, like
+ ``p = T(mapped_col)`` itself.
+ """
+ if (
+ col is None
+ or not col.type
+ or isinstance(value, bool)
+ or not isinstance(value, (int, float, Decimal))
+ ):
+ return value
+ try:
+ column_spec = self.db_engine_spec.get_column_spec(
+ col.type, db_extra=self.db_extra
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return value
+ if column_spec is None:
+ return value
+ sqla_type = column_spec.sqla_type
+ type_class = sqla_type if isinstance(sqla_type, type) else type(sqla_type)
+ if issubclass(type_class, sa.Integer):
+ if isinstance(value, int):
+ return value
+ try:
+ return int(value) if value == int(value) else value
+ except (OverflowError, ValueError):
+ # Infinity and NaN have no integer, and match no integer row.
+ return value
+ return value
+
+ def _mirror_probe_input(
+ self,
+ operator: utils.FilterOperator,
+ value: Any,
+ col: Optional["TableColumn"],
+ ) -> Any:
+ """
+ ``value`` in the representation the mirror may probe the transform at.
+
+ A simple filter on a temporal column carries a *string*.
+ `filter_values_handler` rewrites only an all-digit value, which it reads
+ as epoch milliseconds, so ``'2026-07-06 10:08:11'`` reaches here exactly
+ as the chart author typed it and is bound as text. The engine compares
+ that text against the column under its own cast, and on a ``DATE``
+ column the cast drops the time of day: the filter keeps the whole of
+ 2026-07-06 while a mirror probed at 10:08:11 keeps one instant of it,
+ which is narrower than the predicate it stands in for.
+
+ So the text is read back into the instant it denotes -- the only way
+ `_engine_literal_resolution`, which answers about a `datetime`, reaches
+ a filter value at all -- and where the engine compares less of that
+ instant than the filter carries, what to do about it is a property of
+ the *operator*:
+
+ * a bound rounds outward, through the helper the range collector uses.
+ Reading one extra bucket at the edge is the trade this feature makes
+ everywhere else too -- see `mirror_operator` -- and the original
+ predicate is still in the query to exclude the rows that bucket adds.
+ * an equality, or one member of an ``IN`` list, has nowhere to widen to.
+ These entries are ``AND``-ed onto the query, so "or the day either
+ side" is not something this sink can express, and the request is
+ declined with `_UNMIRRORABLE`. The query is then correct and unpruned,
+ which is the one failure mode this feature is allowed.
+
+ An instant carrying a UTC offset is declined for every operator, a
+ bound included. Rounding one outward would first have to place it in the
+ frame the partition column was written in, and guessing that frame is
+ how a mirror ends up a whole offset narrower than the filter -- see the
+ load-bearing assumption in
+ `superset.connectors.sqla.partition_mapping`.
+
+ A *string* `_instant_from_filter_value` cannot read at all is declined on
+ the same terms, and for the same reason one more step back: there is no
+ instant to round. ``'07/06/2026 10:08:11'`` is not ISO 8601, so the
+ parser leaves it alone -- and Postgres casts that same text to a DATE and
+ keeps the whole of July 6 while the probe, handed the string verbatim,
+ evaluates the transform at 10:08:11 and asks for a partition key no row
+ holds. That is exactly the narrowing the ISO-only parser was written to
+ prevent, reached through a value it declines to read, so the decline has
+ to travel with it. Which costs a non-ISO *date* its pruning too, because
+ telling July 6 from June 7 is the guess that started this.
+
+ Only a string. `_as_probe_input` has already run, so the engine SQL
+ `filter_values_handler` returns for an epoch-millisecond bound arrives
+ here as a `RawProbeValue` rather than text -- and that literal was
+ rendered by the engine at the engine's own resolution, so it is the one
+ thing on this path with nothing left to resolve. The escaping gate has
+ run too, on the value as it arrived; a string this method *returns* is a
+ fresh one, which is why `evaluate_transform` asks again.
+
+ Where the engine compares the whole instant, a string is returned
+ exactly as it arrived -- down to the type the probe binds and the cache
+ key it lands on, because every query that was already correct has to
+ stay byte-for-byte correct. A `datetime` is still converted, which it
+ has always needed: on a column stored as an epoch integer the transform
+ is a function of an integer, and a `datetime` is not the value the real
+ predicate compares.
+ """
+ value = self._in_column_number_type(value, col)
+ parsed = _instant_from_filter_value(value)
+ if parsed is None:
+ if (
+ isinstance(value, str)
+ and self._column_literal_resolution(col) is not LiteralResolution.FULL
+ ):
+ return _UNMIRRORABLE
+ return value
+
+ # Ahead of the full-resolution return: a transform such as
+ # `CAST(:value AS TIMESTAMP)` drops the offset, so even an engine that
+ # compares the whole instant would probe it in the wrong frame. Its own
+ # reason, because mapping a column the engine compares in full -- the
+ # advice the resolution decline carries -- does not help here.
+ if parsed.tzinfo is not None:
+ return _UNMIRRORABLE_OFFSET
+
+ if self._engine_literal_resolution(parsed, col) is LiteralResolution.FULL:
+ return (
+ self._mirror_probe_value(parsed, col)
+ if isinstance(value, datetime)
+ else value
+ )
+
+ if operator in LOWER_BOUND_OPERATORS:
+ instant = self._round_bound_outward(parsed, col, is_upper=False)
+ elif operator in UPPER_BOUND_OPERATORS:
+ instant = self._round_bound_outward(parsed, col, is_upper=True)
+ elif self._literal_is_coarser_than(parsed, col):
+ return _UNMIRRORABLE
+ else:
+ instant = parsed
+
+ if instant == parsed and not isinstance(value, datetime):
+ return value
+ return self._mirror_probe_value(instant, col)
+
+ def _collect_partition_mirror_range(
+ self,
+ mapping: Optional["PartitionMapping"],
+ sink: list[tuple[utils.FilterOperator, Any]],
+ column_name: str,
start_dttm: Optional[sa.DateTime],
end_dttm: Optional[sa.DateTime],
- time_grain: Optional[str] = None,
- label: Optional[str] = "__time",
- template_processor: Optional[BaseTemplateProcessor] = None,
- ) -> Optional[ColumnElement]:
- col = (
- time_col.get_timestamp_expression(
- time_grain=time_grain,
- label=label,
- template_processor=template_processor,
+ widen_bounds_by: Optional[relativedelta] = None,
+ ) -> None:
+ """
+ Record a time range for mirroring onto the partition column.
+
+ The bounds are adjusted first, by the same helper `get_time_filter` uses:
+ the mirrored predicate has to describe the same instants as the
+ timestamp predicate it stands in for, or the pruning is wrong by exactly
+ the dataset's timezone offset -- silently.
+
+ Either bound may be `None` for an open-ended range, in which case only
+ the bound that exists is mirrored.
+
+ Both bounds are recorded with the operators the real predicate uses,
+ `>=` and `<`. Relaxing the strict one is `mirror_operator`'s job, at the
+ single point where an operator becomes SQL -- which is also the point
+ the preview endpoint goes through.
+
+ `widen_bounds_by` is one grain bucket width, passed when the filter this
+ stands in for compares a *truncated* column. The real predicate then
+ keeps rows the raw bounds exclude, and widening both ends by one bucket
+ is the smallest range guaranteed to contain all of them -- see the "Time
+ grains" section of `superset.connectors.sqla.partition_mapping`.
+
+ A widened range can also be wide enough to fail `_bounds_are_ordered`
+ against a tighter filter on the same column. That fails open -- no
+ mirroring, no pruning, no dropped rows.
+ """
+ if mapping is None or column_name != mapping.mapped_column:
+ return
+ if not mapping.mirrors(utils.FilterOperator.TEMPORAL_RANGE):
+ return
+
+ # Resolve the column so the offset adjustment sees the same type
+ # `get_time_filter` does -- an offset the column's type cannot represent
+ # is dropped, and the mirrored bounds have to agree with the originals.
+ mapped_col = next(
+ (col for col in self.columns if col.column_name == column_name), None
+ )
+ start_dttm, end_dttm = self.adjust_time_bounds(start_dttm, end_dttm, mapped_col)
+
+ # Adjust first, then widen. `adjust_time_bounds` moves the naive UI
+ # bounds into the frame the column is *stored* in, and the grain
+ # truncation in the real predicate happens in that same frame, so the
+ # bucket width has to be added there too. The two commute for the
+ # hour-offset branch but not for the `ZoneInfo` one, where widening
+ # across a DST boundary first lands an hour out.
+ if widen_bounds_by is not None:
+ if start_dttm is not None:
+ start_dttm -= widen_bounds_by
+ if end_dttm is not None:
+ end_dttm += widen_bounds_by
Review Comment:
`end_dttm += widen_bounds_by` is outside any handler, and adding a bucket width to a datetime near the maximum raises `ValueError`. A mapped `TEMPORAL_RANGE` filter with grain `P1Y` and a range ending `9999-12-31` builds valid bounds for the original predicate, then fails here on year 10000. The comment above says a widened range fails open, but this raises instead, so turning mapping on breaks a chart that ran fine without it. Should the widening skip the mirror on overflow rather than propagate?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,3583 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Writing the value into the probe
+--------------------------------
+The probe evaluates the transform at a *literal*, because it runs with no bound
+parameters at all -- so every value is written into SQL text by the driver's
+literal renderer and read back by the engine's lexer, and the two do not always
+agree. SQLAlchemy's default renderer doubles apostrophes and leaves backslashes
+alone; Hive honours backslash escapes and not doubling, so ``'O''Brien'`` is
+read there as two adjacent literals and ``'x\\''`` ends four characters into a
+value the filter carries whole. A disagreement is either a mirror built from a
+value nobody filtered on -- dropping rows the filter keeps -- or, where the
+value closes its own quote, an expression of the filterer's choosing running in
+the probe.
+
+Which side is right is not knowable from the driver: it is a per-session server
+setting (``standard_conforming_strings``, ``NO_BACKSLASH_ESCAPES``,
+``spark.sql.parser.escapedStringLiterals``), and SQLAlchemy's own view of it is
+only correct on a dialect that has connected. So escaping is not what makes
+this safe. `literal_round_trips` renders the literal and reads it back in the
+engine's own dialect instead, and a value that does not survive the trip is not
+mirrored -- the usual trade, pruning for correctness. `probe_sql_is_evaluable`
+re-reads the finished statement behind it.
+
+The probe's *answers* make the same trip, in the other direction. The chart
+query is compiled with ``literal_binds``, so a probed partition key is rendered
+into its SQL by the same renderer and read by the same lexer -- and
+``concat(:value, chr(92), 'b')`` turns the unremarkable input ``a`` into the key
+``a\\b``, which Hive reads back as ``a`` followed by a backspace. So
+`_predicates_from_probe` asks `literal_round_trips` about each result too, and
+declines the request rather than emitting a predicate no row can satisfy: the
+mirror is ``AND``-ed onto the query, so a mirror that matches nothing costs the
+chart its rows rather than its pruning.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: The opening and closing delimiters of each kind of Jinja block. The probe
+#: would render these in a different context at a different time from the chart
+#: query, so a transform holding one is rejected at save time.
+JINJA_BLOCK_DELIMITERS = (("{{", "}}"), ("{%", "%}"), ("{#", "#}"))
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: A PostgreSQL Unicode-escaped identifier, ``U&"..."``.
+#:
+#: The second construct that breaks the premise above, and in the same way:
+#: ``U&"\\0071uery_to_xml"(...)`` parses as an anonymous function whose name is
+#: the *literal* ``\\0071uery_to_xml``, so the function denylist is matching a
+#: name the engine never sees -- PostgreSQL decodes the escape and runs
+#: ``query_to_xml``, handing a dataset owner rows from outside their RLS scope
+#: through the preview's ``emitted_predicate``.
+#:
+#: Normalizing the escapes and re-checking would be the other repair, and is
+#: worse: it means reimplementing one engine's identifier decoding well enough
+#: to be a security boundary. Refusing the construct is exact, and costs
+#: nothing real -- a transform is a scalar function of ``:value``, and there is
+#: no reason to name a function or column through an escape sequence.
+#:
+#: Refused on every engine, like the executable comment, so a transform stored
+#: on SQLite cannot detonate when the dataset is re-pointed at PostgreSQL. The
+#: ``&`` may be separated from the ``U`` by nothing at all, but whitespace or a
+#: comment between the prefix and the string is not accepted by PostgreSQL
+#: either, so the strict form is the whole surface.
+#:
+#: Matched in raw text, so the prefix is refused inside a string literal too.
+#: That is the same trade the executable comment makes and has the same
+#: justification: a gate whose contract is to fire *before* the parse cannot
+#: ask the parse whether the text was quoted. ``concat(:value, 'u&"x"')`` is
+#: refused, which costs an owner nothing anyone writes.
+UNICODE_ESCAPED_IDENTIFIER_RE = re.compile(r'\bU&"', re.IGNORECASE)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate: a transform such as
+#: ``datediff(day, :value, LOCALTIMESTAMP)`` for a relative partition key is
+#: evaluated once and then keeps emitting yesterday's answer, so the chart
+#: silently drops rows after midnight.
+#:
+#: Matched by SQL function name, so every engine's spelling of "now" has to be
+#: named -- the ANSI four were not enough. Listed rather than delegated to the
+#: engine specs because the risk is the same everywhere and a spec that had not
+#: got round to declaring its own would fail open; a name no engine has is
+#: inert, so over-listing costs nothing.
+NON_DETERMINISTIC_FUNCTIONS = {
+ # ANSI, and the engines that spell it this way.
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "LOCALTIME",
+ "LOCALTIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+ # PostgreSQL. `now()` is statement-stable; these two are not even that.
+ "CLOCK_TIMESTAMP",
+ "STATEMENT_TIMESTAMP",
+ "TIMEOFDAY",
+ # MySQL and MariaDB.
+ "CURDATE",
+ "CURTIME",
+ "SYSDATE",
+ "UTC_DATE",
+ "UTC_TIME",
+ "UTC_TIMESTAMP",
+ "UUID_SHORT",
+ # Oracle.
+ "SYSTIMESTAMP",
+ "SYS_GUID",
+ # SQL Server.
+ "GETDATE",
+ "GETUTCDATE",
+ "SYSDATETIME",
+ "SYSUTCDATETIME",
+ "SYSDATETIMEOFFSET",
+ "NEWID",
+ # BigQuery.
+ "CURRENT_DATETIME",
+ "GENERATE_UUID",
+ # Snowflake.
+ "RANDSTR",
+ "UUID_STRING",
+ # ClickHouse.
+ "NOW64",
+ "RANDCANONICAL",
+ "GENERATEUUIDV4",
+ # H2 and Derby, which the test fixtures use.
+ "RANDOM_UUID",
+}
+
+#: The wall-clock names an engine evaluates with no parentheses at all.
+#:
+#: These parse as *column references*, not functions, so the name-based walk
+#: below cannot see them: `datediff(UTC_DATE, :value)` on MySQL and
+#: `:value - SYSDATE` on Oracle both cleared the gate and froze probe time into
+#: a cached mirror.
+#:
+#: A subset of `NON_DETERMINISTIC_FUNCTIONS` rather than the whole of it,
+#: because refusing a bare name costs an owner a column genuinely called that.
+#: Only the names SQL lets you write without ``()`` are listed -- the datetime
+#: keywords -- so `rand`, `uuid` and `newid`, which always need parentheses and
+#: are plausible column names, stay out.
+BARE_WALL_CLOCK_KEYWORDS = frozenset(
+ {
+ "current_date",
+ "current_time",
+ "current_timestamp",
+ "localtime",
+ "localtimestamp",
+ "utc_date",
+ "utc_time",
+ "utc_timestamp",
+ "sysdate",
+ "systimestamp",
+ }
+)
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+class Unmirrorable:
+ """
+ A filter no mirror can stand in for, and why.
+
+ Returned by `ExploreMixin.mirror_probe_request` for a value the engine
+ compares more coarsely than the filter carries, one it cannot render as a
+ literal, one whose rendered literal the engine would not read back as the
+ same value, one in a time frame the transform would discard, or an ``IN``
+ list with a member of any of those kinds. An object rather than `None`,
+ because `None` is a filter value in its own right.
+
+ The reason rides along because the preview has to explain the decline to
+ the owner, and the two declines want different advice: "the engine compares
+ less of this value than you typed, so map a column it compares in full" is
+ sound guidance for a `DATE` column and actively misleading for an
+ offset-bearing bound on a `TIMESTAMP` one, which already is such a column.
+ Carried rather than re-derived so the preview's explanation cannot come
+ apart from the chart path's decision.
+
+ Lives here rather than beside that method so the preview can read it too:
+ `superset.models.helpers` imports this module, so these can only cross the
+ boundary in this direction. Both callers recognise the same instances -- a
+ preview that answered "valid" for a request the chart path declines is the
+ drift this is here to prevent.
+ """
+
+ __slots__ = ("reason",)
+
+ def __init__(self, reason: str) -> None:
+ self.reason = reason
+
+ def __repr__(self) -> str:
+ return f"<Unmirrorable {self.reason}>"
+
+
+#: The ordinary decline: whatever the mirror cannot be built from, with the
+#: engine's own comparison resolution as the reason an owner can act on.
+UNMIRRORABLE = Unmirrorable("resolution")
+
+#: A value carrying a UTC offset, declined whatever the column's resolution.
+#: A transform such as ``CAST(:value AS TIMESTAMP)`` drops the offset, so even
+#: an engine that compares the whole instant would be probed in the wrong
+#: frame -- which is not something mapping a different column fixes.
+UNMIRRORABLE_OFFSET = Unmirrorable("offset")
+
+#: A value the driver and the engine would not spell the same way, declined
+#: whatever the column's resolution and whatever the operator. Nothing about
+#: the column or the transform fixes it -- see `literal_round_trips` -- so the
+#: advice the resolution reason carries would send an owner after the wrong
+#: thing entirely.
+UNMIRRORABLE_ESCAPING = Unmirrorable("escaping")
+
+
+def is_unmirrorable(value: Any) -> bool:
+ """Whether `mirror_probe_request` declined this request."""
+ return isinstance(value, Unmirrorable)
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def _native_generic_type(
+ column: "TableColumn",
+) -> utils.GenericDataType | None:
+ """
+ What the engine spec makes of ``column``'s declared type.
+
+ `TableColumn.type_generic` answers ``TEMPORAL`` for every column carrying
+ ``is_dttm``, which is the right answer for a chart's time axis and the
+ wrong one for a comparison: an epoch ``BIGINT`` is a number to the engine
+ however it is labelled here. Falls back to the flag where the spec has no
+ answer, so a type Superset cannot resolve is no worse off than before.
+ """
+ try:
+ column_spec = column.db_engine_spec.get_column_spec(
+ column.type, db_extra=column.db_extra
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ column_spec = None
+ if column_spec is not None and column_spec.generic_type is not None:
+ return column_spec.generic_type
+ try:
+ return column.type_generic
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+#: A declared type naming an array: PostgreSQL's ``TEXT[]`` / ``INTEGER[][]``
+#: / ``int[3]``, and the ``ARRAY<...>`` / ``ARRAY(...)`` / ``Array(...)``
+#: spellings of Hive, Spark, Trino, BigQuery and ClickHouse.
+#: The bracket body is written so no two runs can match the same blanks:
+#: ``\s*\d*\s*`` backtracks polynomially on a long run of spaces.
+_ARRAY_TYPE_RE = re.compile(r"(?:\[\s*(?:\d+\s*)?\])+\s*$|^\s*ARRAY\b", re.IGNORECASE)
+
+
+def declares_array_type(column_type: str | None) -> bool:
+ """
+ Whether a declared column type is an array, whatever the engine spec says.
+
+ The engine spec only reports ``MULTI_VALUE`` where it has opted into
+ ``supports_multivalue_columns``; PostgreSQL has not, and resolves ``TEXT[]``
+ to ``STRING`` and ``INTEGER[]`` to ``NUMERIC``. So an array partition column
+ there cleared the array refusal, previewed valid, and every equality chart
+ on the mapping failed with ``malformed array literal``. The declared type
+ is what the engine will compare, so it is read directly as well.
+ """
+ return bool(column_type and _ARRAY_TYPE_RE.search(column_type))
+
+
+#: Declared types whose comparison ignores trailing blanks.
+#:
+#: The fixed-width character types, which the SQL standard has compare as
+#: though both sides were padded to the same length -- so ``'US'`` and
+#: ``'US '`` are equal in a ``CHARACTER(3)``, while ``lower()`` of the two is
+#: not. Spelled out rather than matched by prefix because the variable-width
+#: names start with the same letters: ``VARCHAR`` and ``CHARACTER VARYING``
+#: compare the blanks and must not land here.
+PADDED_CHARACTER_TYPES = frozenset(
+ {
+ "CHAR",
+ "NCHAR",
+ # PostgreSQL's own name for ``CHARACTER``, which is what reflection
+ # reports for a ``CHAR(n)`` column there.
+ "BPCHAR",
+ "CHARACTER",
+ "NATIONAL CHAR",
+ "NATIONAL CHARACTER",
+ }
+)
+
+
+def _is_padded_character_type(column: TableColumn) -> bool:
+ """
+ Whether ``column``'s declared type compares without its trailing blanks.
+
+ Read off the declared type rather than the engine spec's resolved one: the
+ specs map ``CHAR`` and ``VARCHAR`` onto the same `sqlalchemy.String`, so
+ the distinction this needs is gone by then. The length suffix is dropped
+ and the name matched against `PADDED_CHARACTER_TYPES`, so an unfamiliar
+ spelling answers ``False`` and the engine-level flag decides as before --
+ this gate adds a decline rather than lifting one. A column with no
+ declared type has nothing to read, and answers the same way.
+ """
+ if not isinstance(column.type, str):
+ return False
+ native = re.sub(r"\s+", " ", column.type.strip().upper())
+ return native.split("(")[0].strip() in PADDED_CHARACTER_TYPES
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ Padding is asked about per column, because it is a property of the *type*
+ rather than of the engine. ``binary_string_comparison`` speaks for an
+ engine's default text comparison, and on PostgreSQL -- which declares it
+ -- a ``CHAR(2)`` still matches a filter for ``'US '`` against a stored
+ ``'US'``, because the standard says a padded character type compares
+ without its trailing blanks. The mirror ``region_key = lower('US ')`` then
+ excludes the row. So a fixed-width character type declines whatever the
+ engine says, and an engine that ignores trailing blanks on its *variable*
+ types says so by not declaring the flag at all (see `RedshiftEngineSpec`).
+
+ The type asked for is the engine spec's reading of the column's declared
+ type, not `TableColumn.type_generic`, which answers ``TEMPORAL`` for
+ anything carrying ``is_dttm``. A ``VARCHAR`` flagged temporal is still text
+ to the engine: on MySQL a filter for ``'2026-01-01T00:00:00'`` matches a
+ stored ``'...t00:00:00'``, while the mirror ``p = hex('...T...')`` excludes
+ it -- and asking the semantic flag skipped the check entirely.
+
+ A type the spec cannot classify declines, which is what the paragraph above
+ promises and what only the exception branch used to do. PostgreSQL's
+ ``citext`` matches no type pattern, so it answered ``None`` -- neither
+ string nor not-string -- and was waved through, which is precisely wrong
+ for a type whose whole purpose is case-insensitive comparison. Declining
+ costs the pruning; admitting it costs rows.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ # Ahead of the generic-type question, which a padded type can lose: the
+ # specs map ``CHARACTER`` onto no generic type at all on some engines, and
+ # a fixed-width character type is a string whether or not Superset can say
+ # so from the name.
+ if _is_padded_character_type(column):
+ return False
+ generic_type = _native_generic_type(column)
+ if generic_type is None:
+ return False
+ if generic_type != utils.GenericDataType.STRING:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_unicode_escaped_identifier(transform: str | None) -> bool:
+ """Whether the transform names something through a ``U&"..."`` escape.
+
+ See `UNICODE_ESCAPED_IDENTIFIER_RE`. Answered on raw text for the same
+ reason as the comment above: the parse reports a name the engine does not
+ use, which is exactly what makes the denylist blind to it.
+ """
+ return (
+ bool(transform)
+ and UNICODE_ESCAPED_IDENTIFIER_RE.search(transform or "") is not None
+ )
+
+
+#: Sequence pseudo-columns, which advance a sequence when they are *read*.
+#:
+#: ``orders_seq.NEXTVAL`` parses as a qualified column reference, not a
+#: function call, so neither `SQLStatement.is_mutating` -- which walks function
+#: names -- nor the function denylist can see it. The probe would then run
+#: ``SELECT orders_seq.NEXTVAL + 1 FROM DUAL`` and advance the sequence, again
+#: on every cache expiry, for a dataset editor holding neither SQL Lab nor a
+#: DML grant. Reading one is a write however the parser classifies it.
+#:
+#: The function spelling (``nextval('s')`` on PostgreSQL) is a different shape
+#: and is caught as a function; this is only about the suffix form.
+SEQUENCE_PSEUDO_COLUMNS = frozenset({"nextval", "currval"})
+
+#: The same thing written as a call.
+#:
+#: Only the suffix form parses as a column; `nextval('s')` on PostgreSQL and
+#: DuckDB, `NEXTVAL(s)`/`SETVAL(s, 1)` on MySQL and MariaDB, and SQL Server's
+#: `NEXT VALUE FOR s` all parse as functions. `SQLStatement.is_mutating` walks
+#: function names on PostgreSQL alone -- deliberately, since the same names are
+#: read-only elsewhere -- so every other engine let these through.
+#:
+#: Matched on the name whatever the engine, because advancing a sequence is a
+#: write wherever it happens and a transform has no reason to call one.
+SEQUENCE_FUNCTIONS = frozenset(
+ {"nextval", "setval", "next_value_for", "nextvalfor", "prevval", "lastval"}
+)
+
+
+def references_sequence(statement: SQLStatement) -> bool:
+ """Whether the statement reads or advances a sequence.
+
+ Both spellings: the pseudo-column suffix, which parses as a column (see
+ `SEQUENCE_PSEUDO_COLUMNS`), and the call, which parses as a function (see
+ `SEQUENCE_FUNCTIONS`).
+
+ Answered on the parse rather than on raw text, because position is what
+ makes it the construct: a column or alias merely *called* ``nextval`` is
+ an ordinary column, and a string literal holding the word is text.
+ """
+ return bool(
+ statement.get_column_names() & SEQUENCE_PSEUDO_COLUMNS
+ or statement.get_disallowed_functions(set(SEQUENCE_FUNCTIONS))
+ )
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """
+ Whether the transform contains a balanced Jinja block.
+
+ A block is an opening delimiter followed, anywhere later, by its closing
+ one -- the same thing ``{{.*?}}`` and its two siblings match under
+ ``re.DOTALL``. Scanned with `str.find` rather than that pattern, because a
+ lazy match retried from every opening delimiter is quadratic in a run of
+ them, and this runs on stored transforms with no length bound of its own:
+ `is_transform_active` reads whatever the column holds. The earliest opening
+ delimiter is the only one worth trying, since any closing delimiter after a
+ later one is also after it.
+ """
+ if not transform:
+ return False
+ for opening, closing in JINJA_BLOCK_DELIMITERS:
+ start = transform.find(opening)
+ if start != -1 and transform.find(closing, start + len(opening)) != -1:
+ return True
+ return False
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
Review Comment:
The gate counts a `:value` that sits inside a quoted identifier as a bare column reference, because the stand-in becomes `"superset_pfm_value_standin"` and parses as one `exp.Column`. At probe time the value is bound inside those identifier quotes, so a sample value containing `"` can close the identifier and add its own expression. On DuckDB, a transform like `list_extract(list_transform([0], lambda "'x", "y'": ":value"), 1)` with a sample value of `x" + nextval(chr(115)) + "y` compiles to a single-projection probe with no comment or subquery, so the final shape check accepts it and `nextval` advances a sequence even though writing `nextval` directly is refused. A dataset editor without SQL Lab access can reach this through the preview endpoint. Should a placeholder inside a delimited identifier be rejected here, the same way one inside a string literal or comment is?
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/tests/DatasourceEditorPartitionMapping.test.tsx:
##########
@@ -0,0 +1,649 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import fetchMock from 'fetch-mock';
+import {
+ screen,
+ waitFor,
+ userEvent,
+ selectOption,
+} from 'spec/helpers/testing-library';
+import { isFeatureEnabled, FeatureFlag } from '@superset-ui/core';
+import type { DatasetObject } from 'src/features/datasets/types';
+import {
+ createProps,
+ DATASOURCE_ENDPOINT,
+ setupDatasourceEditorMocks,
+ cleanupAsyncOperations,
+ fastRender,
+ dismissDatasourceWarning,
+ type DatasourceEditorProps,
+} from './DatasourceEditor.test.utils';
+
+jest.mock('@superset-ui/core', () => ({
+ ...jest.requireActual('@superset-ui/core'),
+ isFeatureEnabled: jest.fn(),
+}));
+
+const PREVIEW_URL = 'glob:*/api/v1/dataset/*/partition_mapping/preview/';
+
+type EditorColumn = DatasetObject['columns'][number] & {
+ partition_value_transform?: string | null;
+ partition_transform_is_monotonic?: boolean;
+};
+
+/** The saved columns from the editor's most recent `onChange`. */
+const lastSavedColumns = (props: DatasourceEditorProps): EditorColumn[] => {
+ const { calls } = props.onChange.mock;
+ return calls[calls.length - 1][0].columns as EditorColumn[];
+};
+
+const columnNamed = (columns: EditorColumn[], name: string) =>
+ columns.find(column => column.column_name === name);
+
+/**
+ * The validation errors from the editor's most recent `onChange`.
+ *
+ * What DatasourceModal disables Save on, so this is the save gate as the modal
+ * sees it.
+ */
+const lastValidationErrors = (props: DatasourceEditorProps): string[] => {
+ const { calls } = props.onChange.mock;
+ return (calls[calls.length - 1][1] ?? []) as string[];
+};
+
+beforeEach(() => {
+ fetchMock.get(DATASOURCE_ENDPOINT, [], { name: DATASOURCE_ENDPOINT });
+ setupDatasourceEditorMocks();
+ // The transform field previews on a debounce as soon as it is mounted with a
+ // previewable transform; without this the request escapes the test.
+ fetchMock.post(PREVIEW_URL, { result: { valid: true } });
+ // Only this flag: a blanket `true` also turns on advanced data types and
+ // dataset folders, which change the DOM these tests read.
+ jest
+ .mocked(isFeatureEnabled)
+ .mockImplementation(flag => flag === FeatureFlag.PartitionFilterMapping);
+});
+
+afterEach(async () => {
+ await cleanupAsyncOperations();
+ fetchMock.clearHistory().removeRoutes();
+ jest.mocked(isFeatureEnabled).mockReset();
+});
+
+test('removing the mapping does not leave the default datetime column mirroring', async () => {
+ // `ds` is the default datetime column and holds a transform of its own while
+ // the mapping sits explicitly on `state`. A dataset reaches that state by
+ // re-pointing the default datetime column, or through the import/PUT API,
+ // and until now nothing cleaned it up: clearing the override dropped the
+ // mapping back onto `ds`, where the leftover transform switched mirroring
+ // straight back on under a different column.
+ const props = createProps();
+ props.datasource.main_dttm_col = 'ds';
+ props.datasource.partition_column = 'num';
+ props.datasource.partition_mapped_column = 'state';
+ const seeded = props.datasource.columns as EditorColumn[];
+ columnNamed(seeded, 'ds')!.partition_value_transform =
+ 'unix_timestamp(:value)';
+ columnNamed(seeded, 'ds')!.partition_transform_is_monotonic = true;
+ columnNamed(seeded, 'state')!.partition_value_transform = 'lower(:value)';
+
+ fastRender(props);
+ await dismissDatasourceWarning();
+ await userEvent.click(await screen.findByTestId('collection-tab-Columns'));
+
+ // The mapping is live on `state` before the click.
+ expect(
+ await screen.findByText(/will automatically apply an equivalent filter/),
+ ).toBeInTheDocument();
+
+ await userEvent.type(
+ await screen.findByPlaceholderText('Search columns by name'),
+ 'state',
+ );
+ await userEvent.click((await screen.findAllByLabelText(/expand row/i))[0]);
+ await userEvent.click(await screen.findByText('Remove mapping'));
+
+ // Nothing mirrors any more, and the panel says so rather than quietly
+ // re-pointing at `ds`.
+ expect(
+ await screen.findByText(/No value transform is set on ds/),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByText(/will automatically apply an equivalent filter/),
+ ).not.toBeInTheDocument();
+
+ await waitFor(() => {
+ expect(
+ lastSavedColumns(props).every(
+ column =>
+ !column.partition_value_transform &&
+ !column.partition_transform_is_monotonic,
+ ),
+ ).toBe(true);
+ });
+});
+
+test('moving the mapping onto a column does not arm a transform parked there', async () => {
+ // NEW-R11-01. `state` holds a transform while the mapping sits on `ds`, a
+ // state the editor cannot produce but the deprecated `POST /datasource/save/`
+ // and a PUT made with the feature flag off both can. Moving the mapping onto
+ // `state` used to pick that leftover up -- one click, no typing, and the
+ // mapping went live emitting `num = lower(...)` for every filter, with the
+ // pruning indicator still green and the row counts quietly short.
+ const props = createProps();
+ props.datasource.main_dttm_col = 'ds';
+ props.datasource.partition_column = 'num';
+ props.datasource.partition_mapped_column = null;
+ const seeded = props.datasource.columns as EditorColumn[];
+ columnNamed(seeded, 'ds')!.partition_value_transform =
+ 'unix_timestamp(:value)';
+ columnNamed(seeded, 'ds')!.partition_transform_is_monotonic = true;
+ columnNamed(seeded, 'state')!.partition_value_transform = 'lower(:value)';
+ columnNamed(seeded, 'state')!.partition_transform_is_monotonic = true;
+
+ fastRender(props);
+ await dismissDatasourceWarning();
+ await userEvent.click(await screen.findByTestId('collection-tab-Columns'));
+
+ await userEvent.type(
+ await screen.findByPlaceholderText('Search columns by name'),
+ 'state',
+ );
+ await userEvent.click((await screen.findAllByLabelText(/expand row/i))[0]);
+ await userEvent.click(await screen.findByTestId('move-mapping-here'));
+
+ // `state` is a VARCHAR, so there is no engine default to pre-fill either: the
+ // mapping arrives inert, and the field's own required marker says why rather
+ // than a mirror switching itself on.
+ await waitFor(() => {
+ expect(columnNamed(lastSavedColumns(props), 'state')).toMatchObject({
+ partition_value_transform: null,
+ partition_transform_is_monotonic: false,
+ });
+ });
+ // And the column it came from does not keep its own either -- one mapping,
+ // one transform.
+ expect(columnNamed(lastSavedColumns(props), 'ds')).toMatchObject({
+ partition_value_transform: null,
+ partition_transform_is_monotonic: false,
+ });
+ expect(lastValidationErrors(props)).toEqual(
+ expect.arrayContaining([
+ expect.stringContaining('A value transform is required on state'),
+ ]),
+ );
+});
+
+test('re-pointing the default datetime column leaves the value transform behind', async () => {
+ // With no override the mapped column *is* `main_dttm_col`, so the mapping
+ // moves either way. The transform does not travel with it: it was written
+ // about the old column, and asserting it on a new one mirrors an expression
+ // nobody checked there. It must not stay behind on the old column either --
+ // invisible but saved, and ready to go live again.
+ const props = createProps();
+ props.datasource.main_dttm_col = 'ds';
+ props.datasource.partition_column = 'num';
+ props.datasource.partition_mapped_column = null;
+ const seeded = props.datasource.columns as EditorColumn[];
+ columnNamed(seeded, 'ds')!.partition_value_transform =
+ 'unix_timestamp(:value)';
+ columnNamed(seeded, 'ds')!.partition_transform_is_monotonic = true;
+ seeded.push({
+ id: 99,
+ type: 'DATETIME',
+ filterable: false,
+ is_dttm: true,
+ is_active: true,
+ expression: '',
+ groupby: false,
+ column_name: 'ingest_time',
+ } as EditorColumn);
+
+ fastRender(props);
+ await dismissDatasourceWarning();
+ await userEvent.click(await screen.findByTestId('collection-tab-Columns'));
+ await screen.findByTestId('default-datetime-column-select');
+
+ await selectOption('ingest_time', 'Default datetime column');
+
+ await waitFor(() => {
+ const columns = lastSavedColumns(props);
+ // The new default never held a mapping, so it is handed back untouched --
+ // which is the same thing as holding no transform.
+ const arrived = columnNamed(columns, 'ingest_time');
+ expect(arrived?.partition_value_transform ?? null).toBeNull();
+ expect(arrived?.partition_transform_is_monotonic ?? false).toBe(false);
+ expect(columnNamed(columns, 'ds')).toMatchObject({
+ partition_value_transform: null,
+ partition_transform_is_monotonic: false,
+ });
+ });
+
+ // The mapping is designated but inert, and the editor says so rather than
+ // promising a mirror it is not performing.
+ expect(
+ await screen.findByText(/No value transform is set on ingest_time/),
+ ).toBeInTheDocument();
+});
+
+test('the mapping will not follow the default datetime column onto a calculated column', async () => {
+ // A calculated column can be the default datetime column, but its row never
+ // renders the transform editor -- carrying a transform there would make a
+ // live mapping with no UI to see or undo it. The mapping goes inert instead,
+ // and nothing is left behind on the old column either.
+ const props = createProps();
+ props.datasource.main_dttm_col = 'ds';
+ props.datasource.partition_column = 'num';
+ props.datasource.partition_mapped_column = null;
+ const seeded = props.datasource.columns as EditorColumn[];
+ columnNamed(seeded, 'ds')!.partition_value_transform =
+ 'unix_timestamp(:value)';
+ seeded.push({
+ id: 98,
+ type: 'DATETIME',
+ filterable: false,
+ is_dttm: true,
+ is_active: true,
+ expression: 'DATE_TRUNC("day", ds)',
+ groupby: false,
+ column_name: 'ds_day',
+ } as EditorColumn);
+
+ fastRender(props);
+ await dismissDatasourceWarning();
+ await userEvent.click(await screen.findByTestId('collection-tab-Columns'));
+ await screen.findByTestId('default-datetime-column-select');
+
+ await selectOption('ds_day', 'Default datetime column');
+
+ await waitFor(() => {
+ expect(
+ lastSavedColumns(props).every(
+ column => !column.partition_value_transform,
+ ),
+ ).toBe(true);
+ });
+
+ expect(
+ await screen.findByText(/No value transform is set on ds_day/),
+ ).toBeInTheDocument();
+});
+
+test('a mapping onto a bare non-temporal column blocks the save', async () => {
+ // `state` is a VARCHAR, so it has no engine default to fall back on and the
+ // transform field marks itself required. Until now that marker was decorative:
+ // the save went through, the PUT filed it as a non-blocking issue, and the
+ // mapping sat inactive with nothing saying so at the field.
+ const props = createProps();
+ props.datasource.main_dttm_col = 'ds';
+ props.datasource.partition_column = null;
+ props.datasource.partition_mapped_column = 'state';
+
+ fastRender(props);
+ await dismissDatasourceWarning();
+ await userEvent.click(await screen.findByTestId('collection-tab-Columns'));
+ await screen.findByTestId('partition-column-select');
+
+ await selectOption('num', 'Partition column');
+
+ await waitFor(() => {
+ expect(lastValidationErrors(props)).toEqual([
+ expect.stringContaining('A value transform is required on state'),
+ ]);
+ });
+});
+
+test('a mapping onto the default datetime column does not block the save', async () => {
+ // The other side of the check: a temporal column with no transform is the
+ // "saved but inactive" case the PRD asks for, so picking a partition column
+ // must not strand the owner with a disabled Save button.
+ const props = createProps();
+ props.datasource.main_dttm_col = 'ds';
+ props.datasource.partition_column = null;
+ props.datasource.partition_mapped_column = null;
+
+ fastRender(props);
+ await dismissDatasourceWarning();
+ await userEvent.click(await screen.findByTestId('collection-tab-Columns'));
+ await screen.findByTestId('partition-column-select');
+
+ await selectOption('num', 'Partition column');
+
+ await waitFor(() => {
+ expect(props.onChange).toHaveBeenCalled();
+ });
+ expect(lastValidationErrors(props)).toEqual([]);
+});
+
+test('with the feature off, re-pointing the default datetime column keeps the transform', async () => {
+ // The transform controls, the validation and the partition picker are all
+ // flag-gated, but the "Default datetime column" select is not -- it predates
+ // this feature. So with the flag off an owner could re-point it, never see a
+ // mapping control, and silently lose stored configuration on save. The
+ // backend gate does not cover it: the cleared value travels as an explicit
+ // null inside the `columns` payload, which `update_columns` writes whatever
+ // the flag says.
+ jest.mocked(isFeatureEnabled).mockImplementation(() => false);
+
+ const props = createProps();
+ props.datasource.main_dttm_col = 'ds';
+ props.datasource.partition_column = 'num';
+ props.datasource.partition_mapped_column = null;
+ const seeded = props.datasource.columns as EditorColumn[];
+ columnNamed(seeded, 'ds')!.partition_value_transform =
+ 'unix_timestamp(:value)';
+ columnNamed(seeded, 'ds')!.partition_transform_is_monotonic = true;
+ seeded.push({
+ id: 99,
+ type: 'DATETIME',
+ filterable: false,
+ is_dttm: true,
+ is_active: true,
+ expression: '',
+ groupby: false,
+ column_name: 'ingest_time',
+ } as EditorColumn);
+
+ fastRender(props);
+ await dismissDatasourceWarning();
+ await userEvent.click(await screen.findByTestId('collection-tab-Columns'));
+ await screen.findByTestId('default-datetime-column-select');
+
+ await selectOption('ingest_time', 'Default datetime column');
+
+ await waitFor(() => {
+ expect(props.onChange).toHaveBeenCalled();
+ });
+ expect(columnNamed(lastSavedColumns(props), 'ds')).toMatchObject({
+ partition_value_transform: 'unix_timestamp(:value)',
+ partition_transform_is_monotonic: true,
+ });
+});
+
+test('DatasourceEditor source pins syncMetadata to the live column state', () => {
+ // Source-pin, for the same reason the sibling pin in `DatasourceEditor.test.tsx`
+ // exists: this file's own note records that the sync button cannot be
+ // triggered from jest -- `fetchSyncedColumns` goes through `SupersetClient`,
+ // and the request never settles under the test harness, so neither toast
+ // fires and there is no observable outcome to assert on.
+ //
+ // What the pin locks is the merge base. `datasource.columns` is the
+ // mount-time snapshot and never moves: no `setDatasource` call writes
+ // `columns`, and the props-sync effect only re-seeds the two column states.
+ // `updateColumns` passes an unchanged column through verbatim, so merging a
+ // sync against that snapshot restores whatever the dataset held when the
+ // modal opened -- the transform and monotonicity flag the owner just
+ // cleared, a `filterable`/`groupby` flag they just toggled, any description
+ // edited this session. The merge semantics themselves are covered in
+ // `utils/partitionMapping.test.ts`.
+ // eslint-disable-next-line global-require
+ const { readFileSync } = require('fs');
+ // eslint-disable-next-line global-require
+ const { join } = require('path');
+ const src = readFileSync(
+ join(__dirname, '..', 'DatasourceEditor.tsx'),
+ 'utf8',
+ );
+
+ // The merge reads the live state, not the mount-time snapshot -- and reads
+ // it through the ref, so an invocation already in flight when the owner
+ // changes something sees the change too. A closure capture could not: the
+ // callback's `currentColumns` is fixed when the sync starts.
+ expect(src).toMatch(/const columnChanges = updateColumns\(\s*liveColumns,/);
+ expect(src).not.toMatch(
+ /const columnChanges = updateColumns\(\s*datasource\.columns,/,
+ );
+ expect(src).toMatch(
+ /const liveColumns = currentColumnsRef\.current;\s*const liveDatasource = datasourceRef\.current;/,
+ );
+
+ // And the live state is both column collections, memoized on both, with the
+ // refs tracking that memo and the datasource.
+ expect(src).toMatch(
+ /const currentColumns = useMemo\(\s*[\s\S]{0,900}?\(\) => \[\.\.\.databaseColumns, \.\.\.calculatedColumns\],\s*\[databaseColumns, calculatedColumns\],/,
+ );
+ expect(src).toMatch(
+ /currentColumnsRef\.current = currentColumns;\s*datasourceRef\.current = datasource;/,
+ );
+});
+
+test('DatasourceEditor source pins the sync to the mapping it leaves behind', () => {
+ // Source-pin, for the reason the pin above gives: the sync button cannot be
+ // driven from jest, because `fetchSyncedColumns` goes through
+ // `SupersetClient` and the request never settles under the harness. The
+ // behaviour of the helper it pins is covered directly in
+ // `components/PartitionFilterMapping/utils.test.ts`.
+ //
+ // What this locks is that the invariant is asked on *both sides* of the
+ // move. A sync that drops the mapped column makes
+ // `clearDanglingPartitionMapping` null the override, which re-points the
+ // mapping at the default datetime column -- so asked only against the
+ // repaired mapping, that column reads as the mapped one and a transform some
+ // earlier writer stranded on it is kept, and goes live from a sync nobody
+ // typed into (NEW-R11-01, then NEW-R12-01 when the first fix answered for the
+ // repaired side alone).
+ // eslint-disable-next-line global-require
+ const { readFileSync } = require('fs');
+ // eslint-disable-next-line global-require
+ const { join } = require('path');
+ const src = readFileSync(
+ join(__dirname, '..', 'DatasourceEditor.tsx'),
+ 'utf8',
+ );
+
+ // The repair is resolved into the mapping the move lands on -- off the live
+ // datasource, so a mapping removed while the sync was in flight is the one
+ // the move starts from.
+ expect(src).toMatch(
+ /const syncedDatasource = \{ \.\.\.liveDatasource, \.\.\.clearedMapping \};/,
+ );
+ // Both sides are passed, in that order, and before the columns are set.
+ expect(src).toMatch(
+ /clearUnmappedTransformsAcrossMove\(\s*liveDatasource,\s*syncedDatasource,\s*columnChanges\.finalColumns,?\s*\)[\s\S]{0,400}?setColumns\(\{/,
Review Comment:
These sync tests read `DatasourceEditor.tsx` as text and match regexes, so they pin the source's shape rather than its behavior. If `syncMetadata` cleared unmapped transforms unconditionally, a sync with `PARTITION_FILTER_MAPPING` off would silently drop a stored transform and its monotonicity flag, and these assertions would stay green. The existing flag-off test covers changing the default datetime column, not syncing. Could a render test cover this: flag off, a stored non-mapped transform, a mocked `fetchSyncedColumns` resolved, and an assertion that the resulting `onChange` payload keeps both fields?
##########
superset-frontend/src/components/Chart/DrillDetail/DrillDetailPane.tsx:
##########
@@ -144,6 +144,13 @@ export default function DrillDetailPane({
return resultsPages.get(lastPageIndex.current);
}, [pageIndex, resultsPages]);
+ // A lower-bound total only covers the rows up to the current page, so count
+ // one row past it to keep the next page reachable.
+ const recordCount =
Review Comment:
`recordCount` is derived only from the page currently shown. With 120 matching rows and 50-row pages, visiting page 3 caches an exact total of 120, but going back to page 1 uses that page's cached lower bound (50), so `recordCount` becomes 51. Page 3 disappears from the pager and the label reverts to "50+ rows" even though the exact total is already known. Should the highest known bound, or the exact total once seen, be kept separately from the displayed page?
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/PartitionColumnFields.tsx:
##########
@@ -0,0 +1,367 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { useMemo } from 'react';
+import { t } from '@apache-superset/core/translation';
+import { css, useTheme } from '@apache-superset/core/theme';
+import { Alert } from '@apache-superset/core/components';
+import {
+ Button,
+ Flex,
+ Icons,
+ InfoTooltip,
+ Label,
+ Select,
+ Tooltip,
+ Typography,
+} from '@superset-ui/core/components';
+import {
+ mappedColumnIsImplicit,
+ mappingIsActive,
+ partitionMappingErrors,
+ resolveMappedColumn,
+ suggestedMappedColumn,
+} from './utils';
+import type {
+ PartitionMappingColumn,
+ PartitionMappingDatasource,
+ PartitionMappingIssue,
+} from './types';
+
+interface PartitionColumnFieldsProps {
+ datasource: PartitionMappingDatasource;
+ /**
+ * Physical columns: what the partition-column dropdown may offer, and where
+ * a replacement mapped column may be suggested from. A calculated column
+ * belongs in neither -- the engine cannot partition on an expression, and
+ * the mapping picker only renders on a physical column's row.
+ */
+ columns: PartitionMappingColumn[];
+ /**
+ * Every column on the dataset, physical and calculated. What *exists* is a
+ * different question from what may be picked, and validation asks the first:
+ * the backend accepts a calculated column as the mapped-column override, so
+ * checking existence against the physical columns alone reported a column
+ * that is really there as missing -- and blocked Save with no way out, since
+ * the dropdown cannot offer it back.
+ */
+ allColumns: PartitionMappingColumn[];
+ onPartitionColumnChange: (columnName: string | null) => void;
+ /** Open the given column's row expand in the Columns table. */
+ onNavigateToColumn: (columnName: string) => void;
+ /**
+ * Whether the mapped column's own preview says the transform mirrors, or
+ * `null`/undefined when no verdict is in yet. The checks this section can
+ * make are all static -- a transform the database rejects clears every one
+ * of them -- so without the preview's answer the banner claimed a speed-up
+ * the query never delivers.
+ */
+ previewMirrors?: boolean | null;
+}
+
+/**
+ * "Partition column" and the computed "Maps to partition" (wireframes 1a, 1g).
+ *
+ * "Maps to partition" is deliberately read-only. It reflects
+ * `partition_mapped_column ?? main_dttm_col`, and a peer dropdown would let it
+ * drift from the default datetime column silently. The only way to override it
+ * is from the target column's own row, where a transform has to be supplied
+ * alongside.
+ */
+export default function PartitionColumnFields({
+ datasource,
+ columns,
+ allColumns,
+ onPartitionColumnChange,
+ onNavigateToColumn,
+ previewMirrors,
+}: PartitionColumnFieldsProps) {
+ const theme = useTheme();
+
+ const options = useMemo(
+ () =>
+ columns.map(column => ({
+ value: column.column_name,
+ label: column.column_name,
+ customLabel: (
+ <Flex align="center" gap={theme.sizeUnit}>
+ <span>{column.column_name}</span>
+ {column.type && <Label>{column.type}</Label>}
+ </Flex>
+ ),
+ })),
+ [columns, theme.sizeUnit],
+ );
+
+ const mappedColumn = resolveMappedColumn(datasource);
+ const isImplicit = mappedColumnIsImplicit(datasource);
+ const mappedColumnRow = allColumns.find(
+ column => column.column_name === mappedColumn,
+ );
+ const liveTransform = mappedColumnRow?.partition_value_transform ?? null;
+ // Range operators -- the time range among them -- only mirror under a
+ // transform declared order-preserving, so without it the banner must not
+ // promise the time range a partition filter it will not get.
+ const isMonotonic = Boolean(
+ mappedColumnRow?.partition_transform_is_monotonic,
+ );
+ // The stored refusal, but only while the box still holds the expression it
+ // was about. It is a verdict on one transform, and it outlived it: reopen a
+ // dataset whose stored `no_such_fn(:value)` failed its last probe, replace it
+ // with something that works, watch the row's own preview come back valid --
+ // and the banner still said nothing would mirror, because this read a summary
+ // computed when the editor opened.
+ const storedVerdictApplies =
+ liveTransform === datasource.partition_filter_mapping?.evaluated_transform;
+ // The static checks are necessary, not sufficient: an unparseable expression
+ // or a function the database does not have needs the engine to spot, and the
+ // mapped column's row already asks it. Deferring to that answer where there
+ // is one is what keeps this banner and that panel from contradicting each
+ // other.
+ const isActive =
+ mappingIsActive(datasource, allColumns) &&
+ previewMirrors !== false &&
+ !(
+ storedVerdictApplies &&
+ datasource.partition_filter_mapping?.evaluable === false
+ );
+ const { partition_column: partitionColumn } = datasource;
+
+ // `field` is what the issues carry it for: a message about the partition
+ // column belongs under the partition column, not only in the Save button's
+ // tooltip, where an owner has to guess which of the two selects is at fault.
+ const issues = useMemo(
+ () => partitionMappingErrors(datasource, allColumns),
+ [datasource, allColumns],
+ );
+ const issueFor = (field: PartitionMappingIssue['field']) =>
+ issues.find(issue => issue.field === field);
+ // Non-blocking issues are saveable, so they read as warnings. The implicit
+ // self-mapping is the one that reaches here: the owner can save through it,
+ // and danger styling on a message beside an enabled Save button says the
+ // opposite of what the button is doing.
+ const issueType = (issue: PartitionMappingIssue) =>
+ issue.blocking === false ? 'warning' : 'danger';
+ const partitionColumnIssue = issueFor('partition_column');
+ const mappedColumnIssue = issueFor('partition_mapped_column');
+
+ // "Map a different column instead" normally opens the currently-mapped
+ // column's row, which is where the picker lives. When the mapped column *is*
+ // the partition column -- the self-mapping the backend rejects, and reachable
+ // in one click because the picker offers every column -- that row renders no
+ // mapping section at all, so the one guided way out of the broken state led
+ // nowhere. Offer a column that is not the partition column instead.
+ //
+ // Null only when there is no mapped column at all, which is also when the
+ // block below does not render -- but a dataset whose every column is the
+ // partition column would otherwise be offered a link to nothing, so the link
+ // is guarded rather than the type asserted away.
+ const differentColumnTarget =
+ mappedColumn && mappedColumn !== partitionColumn
+ ? mappedColumn
+ : (suggestedMappedColumn(columns, partitionColumn) ?? mappedColumn);
+
+ return (
+ <Flex vertical gap={theme.sizeUnit} data-test="partition-column-fields">
+ <Flex align="center" gap={theme.sizeUnit}>
+ <Typography.Text>{t('Partition column')}</Typography.Text>
+ <InfoTooltip
+ tooltip={t(
+ 'The physical column the engine partitions on. Filters on the mapped column are mirrored onto it so the engine can prune partitions.',
+ )}
+ />
+ </Flex>
+ <Select
+ ariaLabel={t('Partition column')}
+ options={options}
+ value={partitionColumn ?? undefined}
+ onChange={value => onPartitionColumnChange((value as string) ?? null)}
+ onClear={() => onPartitionColumnChange(null)}
+ placeholder={t('None')}
+ allowClear
+ data-test="partition-column-select"
+ />
+ {partitionColumnIssue && (
+ <Typography.Text
+ type={issueType(partitionColumnIssue)}
+ data-test="partition-column-error"
+ >
+ {partitionColumnIssue.message}
+ </Typography.Text>
+ )}
+ <Typography.Text type="secondary">
+ {t(
+ 'Column used for partition pruning on this table. Its Is filterable and Is dimension settings decide whether Explore offers it.',
+ )}
+ </Typography.Text>
+
+ {partitionColumn && (
+ <Flex vertical gap={theme.sizeUnit} data-test="maps-to-partition">
+ <Flex align="center" gap={theme.sizeUnit}>
+ <Typography.Text type="secondary">
+ {t('Maps to partition')}
+ </Typography.Text>
+ <InfoTooltip
+ tooltip={t(
+ 'The column whose filters are mirrored. It follows the default datetime column unless a different column holds the mapping.',
+ )}
+ />
+ </Flex>
+
+ {mappedColumn ? (
+ <>
+ <Flex align="center" gap={theme.sizeUnit}>
+ <Label>{mappedColumn}</Label>
+ {isImplicit && (
+ <>
+ <Typography.Text type="secondary">
+ {t('Default datetime column')}
+ </Typography.Text>
+ <Tooltip
+ title={t(
+ 'Set from the default datetime column above, so re-pointing that column moves the mapping with it.',
+ )}
+ >
+ <Icons.LockOutlined
+ iconSize="s"
+ iconColor={theme.colorTextTertiary}
+ />
+ </Tooltip>
+ </>
+ )}
+ </Flex>
+ {mappedColumnIssue && (
+ <Typography.Text
+ type={issueType(mappedColumnIssue)}
+ data-test="partition-mapped-column-error"
+ >
+ {mappedColumnIssue.message}
+ </Typography.Text>
+ )}
+ <Typography.Text type="secondary">
+ {t(
+ 'Filters on this column are mirrored onto the partition column.',
+ )}
+ {differentColumnTarget && (
+ <>
+ {' '}
+ <Button
+ buttonStyle="link"
+ onClick={() => onNavigateToColumn(differentColumnTarget)}
+ data-test="map-a-different-column"
+ >
+ {t('Map a different column instead →')}
+ </Button>
+ </>
+ )}
+ </Typography.Text>
+ {isActive ? (
+ <Alert
+ type="info"
+ showIcon
+ icon={<Icons.FilterOutlined />}
+ message={
+ <span>
+ {isMonotonic
+ ? t(
+ 'Filters on %(mapped)s will automatically apply an equivalent filter to %(partition)s.',
+ {
+ mapped: mappedColumn,
+ partition: partitionColumn,
+ },
+ )
+ : t(
+ 'Equality and list filters on %(mapped)s will automatically apply an equivalent filter to %(partition)s. Time ranges and other range filters are not mirrored until "Transform preserves ordering" is on.',
Review Comment:
This message says equality and list filters on the mapped column will be mirrored, but nothing here checks that those operators are allowed. Take a MySQL dataset mapping a `VARCHAR` through `lower(:value)` with ordering unchecked: `mappingIsActive()` accepts it, while the server's `equality_mirrors_safely()` rejects equality and `IN`, so no operator is mirrorable. The owner is told the mapping works, yet every filter stays unpruned. Could the help text use the server's operator eligibility instead of assuming equality is always available?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(explore): indicate when a filter is mirrored onto a partition column [superset]
Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #43870:
URL: https://github.com/apache/superset/pull/43870#issuecomment-5548909881
## [Codecov](https://app.codecov.io/gh/apache/superset/pull/43870?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
:x: Patch coverage is `95.00000%` with `1 line` in your changes missing coverage. Please review.
:white_check_mark: Project coverage is 79.51%. Comparing base ([`42d68c0`](https://app.codecov.io/gh/apache/superset/commit/42d68c088ff085c88d0ae602e305cfb1b44940a4?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`2e57d43`](https://app.codecov.io/gh/apache/superset/commit/2e57d4338c1e6555346989a297584bcdd5f782b2?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
| [Files with missing lines](https://app.codecov.io/gh/apache/superset/pull/43870?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
|---|---|---|
| [...ls/DndColumnSelectControl/DndAdhocFilterOption.tsx](https://app.codecov.io/gh/apache/superset/pull/43870?src=pr&el=tree&filepath=superset-frontend%2Fsrc%2Fexplore%2Fcomponents%2Fcontrols%2FDndColumnSelectControl%2FDndAdhocFilterOption.tsx&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQtZnJvbnRlbmQvc3JjL2V4cGxvcmUvY29tcG9uZW50cy9jb250cm9scy9EbmRDb2x1bW5TZWxlY3RDb250cm9sL0RuZEFkaG9jRmlsdGVyT3B0aW9uLnRzeA==) | 80.00% | [1 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/43870?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
<details><summary>Additional details and impacted files</summary>
```diff
@@ Coverage Diff @@
## hughhhh/pfm-5-editor-ui #43870 +/- ##
========================================================
Coverage 79.51% 79.51%
========================================================
Files 2901 2902 +1
Lines 168827 168847 +20
Branches 39212 39220 +8
========================================================
+ Hits 134243 134265 +22
+ Misses 32083 32081 -2
Partials 2501 2501
```
| [Flag](https://app.codecov.io/gh/apache/superset/pull/43870/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
|---|---|---|
| [javascript](https://app.codecov.io/gh/apache/superset/pull/43870/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `75.07% <95.00%> (+<0.01%)` | :arrow_up: |
Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
</details>
[:umbrella: View full report in Codecov by Harness](https://app.codecov.io/gh/apache/superset/pull/43870?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
<details><summary> :rocket: New features to boost your workflow: </summary>
- :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
- :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4237969030
##########
superset/db_engine_specs/postgres.py:
##########
@@ -178,6 +178,15 @@ class PostgresBaseEngineSpec(BaseEngineSpec):
engine = ""
engine_name = "PostgreSQL"
+ # The engine's default text comparison is binary, so a mirrored
+ # ``partition_col = T(v)`` agrees with the ``col = v`` it stands in for.
+ binary_string_comparison = True
+
+ # PostgreSQL's date/time input reads the unseparated forms as well as the
+ # ISO ones -- ``'20260115'::date`` is 2026-01-15 -- so a ``YYYYMMDD``
+ # bucketing key mirrors here. Redshift inherits the same input parsing.
+ temporal_literal_formats = ("%Y%m%d", "%Y%m%d%H%M%S")
Review Comment:
`SnowflakeEngineSpec` (and Vertica, HANA, Netezza, Hologres) inherits this. Snowflake's AUTO date input does not accept `YYYYMMDD` and converts all-digit strings as epoch seconds, so the mirror `part_date = '20260115'` misreads. Declare it on `PostgresEngineSpec`/`RedshiftEngineSpec` instead.
##########
superset/config.py:
##########
@@ -2553,6 +2585,24 @@ def engine_context_manager( # pylint: disable=unused-argument
"getMacro",
"getSetting",
},
+ # Oracle functions that run a query handed to them as text. Same blind spot
+ # as PostgreSQL's XML and full-text families above: the statement they
+ # execute is a string, so the expression has no FROM clause and no
+ # sub-query of its own for a table-reference gate to see, and the rows come
+ # back without the dataset grants or row-level security the caller is
+ # subject to.
+ #
+ # Named bare rather than package-qualified: `DBMS_XMLGEN.GETXML(...)`
+ # parses as an anonymous function called `GETXML`, so the package prefix
+ # never reaches the matcher. `getclobval` and `extract` are deliberately
+ # absent -- they read an XMLType the caller already has rather than
+ # building one from a query.
+ "oracle": {
+ "getxml",
+ "getxmltype",
+ "newcontext",
+ "newcontextfromhierarchy",
Review Comment:
`DBURITYPE('/HR/EMPLOYEES/ROW[ID=1]/SALARY').getclob() || :value` clears every transform gate (bare, no sub-query, not mutating, not denied) and reads a table by path string: the same blind spot as `GETXML`, and PUBLIC by default.
```suggestion
"newcontextfromhierarchy",
# Reads a table by path string, e.g. DBURITYPE('/SCHEMA/TABLE/ROW').
"dburitype",
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4227028394
##########
superset/models/helpers.py:
##########
@@ -4292,36 +4389,661 @@ def dttm_sql_literal(self, dttm: datetime, col: "TableColumn") -> str:
return f"""'{dttm.strftime("%Y-%m-%d %H:%M:%S.%f")}'"""
- def get_time_filter( # pylint: disable=too-many-arguments # noqa: C901
+ def _mirror_probe_value(self, dttm: datetime, col: Optional["TableColumn"]) -> Any:
+ """
+ ``dttm`` in the mapped column's own stored representation.
+
+ The predicate this mirror stands in for compares the column against
+ `dttm_sql_literal(dttm, col)`, so the transform has to be probed with
+ the same value. On a column stored as an epoch integer, ``T`` is a
+ function of an integer: probing it with a `datetime` either returns
+ something unrelated to the partition keys or raises, and a raise costs
+ the dataset its pruning silently.
+
+ Only the ``python_date_format`` branches of `dttm_sql_literal` are
+ reproduced, because only those produce a *value*. `convert_dttm` yields
+ engine-specific SQL text, which cannot be bound as a parameter; its own
+ divergence from the probe is handled by widening the bounds instead
+ (`_engine_literal_resolution`).
+
+ In `dttm_sql_literal`'s own order, though: it asks ``convert_dttm``
+ first and reaches the format only when the engine answers nothing. A
+ column can carry both -- a TIMESTAMP with a ``%Y%m%d``
+ ``python_date_format``, or an entry in
+ ``python_date_format_by_column_name`` -- and applying the format
+ unconditionally probed a value the real predicate never compares.
+ ``event_time >= '2026-01-01 00:00:00'`` mirrored as
+ ``partition_col >= '20260101'``, and a January 15 row keyed
+ ``2026-01-15`` sorts below that string, so the chart lost a row the
+ filter keeps.
+
+ Where the engine does answer, the `datetime` is returned unchanged and
+ the widening path takes over -- which is exactly what already happens
+ for every temporal column that carries no format at all.
+ """
+ if col is None:
+ return dttm
+
+ if col.type and self.db_engine_spec.convert_dttm(
+ col.type, dttm, db_extra=self.db_extra
+ ):
+ # The format is unreachable in `dttm_sql_literal` for this column,
+ # so reproducing it here would describe a different bound.
+ return dttm
+
+ tf = col.python_date_format
+ if not tf and self.db_extra:
+ tf = self.db_extra.get("python_date_format_by_column_name", {}).get(
+ col.column_name
+ )
+ if not tf:
+ return dttm
+
+ if tf in EPOCH_FORMATS:
+ dttm_tz_aware = dttm
+ if dttm_tz_aware.tzinfo is None:
+ dttm_tz_aware = dttm_tz_aware.replace(tzinfo=timezone.utc)
+ return int(dttm_tz_aware.timestamp()) * EPOCH_FORMATS[tf]
+ return dttm.strftime(tf)
+
+ def _engine_literal_resolution(
+ self, dttm: datetime, col: Optional["TableColumn"]
+ ) -> LiteralResolution:
+ """
+ How much of ``dttm`` survives into this engine's literal for ``col``.
+
+ The real predicate compares `dttm_sql_literal(dttm, col)`, so whatever
+ that literal throws away is a bound the engine never sees. A mirror
+ derived from the full precision then describes a *narrower* range than
+ the predicate it stands in for -- and narrower means it drops rows the
+ filter keeps.
+
+ Two things get thrown away in practice:
+
+ - the sub-second part. SQLite renders a timestamp with
+ ``timespec="seconds"``.
+ - the time of day entirely. Every engine spec with a ``types.Date``
+ branch renders ``dttm.date().isoformat()``, so Presto, Trino,
+ BigQuery and some two dozen others answer `DATE '2026-01-01'` for a
+ bound of 10:00 -- and `T(DATE '2026-01-01')` is below the mirror's
+ own lower bound, so the whole first day is dropped.
+
+ Detected rather than enumerated per engine, because the branch depends
+ on the column's type as well as the spec: instants differing only in the
+ part under test render as the same text exactly when the engine has
+ thrown that part away.
+
+ The day test uses two fixed times of day rather than ``dttm`` and one
+ alternative, so a bound that happens to sit on the hour the alternative
+ uses cannot read as "no time at all". Neither probe sits at midnight on
+ purpose: SQLite renders a DATE column at exactly midnight as a bare
+ date, so a midnight probe would differ from its alternative for a
+ reason that has nothing to do with resolution.
+
+ Likewise both sub-second probes carry a non-zero remainder. Comparing
+ against ``dttm`` truncated to the second looks like the obvious test and
+ is wrong for the same formatting-boundary reason.
+
+ A non-temporal column has no answer here, and asking anyway gets a wrong
+ one. SQLite's ``convert_dttm`` renders for ``types.String`` as well as
+ for the date types, so a ``VARCHAR`` mapped column reads as
+ second-resolution -- and a filter value that happens to *look* like an
+ instant then has its bound rounded as though the engine had truncated
+ it. On a VARCHAR ``code`` mapped onto a VARCHAR ``p`` by ``:value``,
+ ``code < '2026-07-06T10:08:11.500000'`` was mirrored as
+ ``p <= '2026-07-06 10:08:12.000000'``; a space sorts before ``T``, so a
+ row holding ``2026-07-06T09:00:00`` fell outside the mirror while
+ matching the filter.
+
+ The guard lives here rather than in each caller so this and
+ `_column_literal_resolution` cannot disagree about which column is
+ coarse -- which is the same reason that helper delegates to this one.
+ """
+ if col is None or not col.type or not col.is_dttm:
Review Comment:
Keying on `is_dttm` also skips rounding for a `DATE` column not flagged temporal: `get_time_filter` still renders a 10:00 TEMPORAL_RANGE bound as `DATE '2026-01-01'`, but the probe now gets 10:00, so the mirror drops that first day. The generic type keeps the VARCHAR fix:
```suggestion
if (
col is None
or not col.type
or col.type_generic != GenericDataType.TEMPORAL
):
```
##########
superset/migrations/versions/2026-09-23_00-01_a7f3c2e91d84_add_partition_filter_mapping.py:
##########
@@ -0,0 +1,101 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""add partition filter mapping
+
+Adds the four columns behind the ``PARTITION_FILTER_MAPPING`` feature:
+
+- ``tables.partition_column`` -- the physical column the engine partitions on
+- ``tables.partition_mapped_column`` -- explicit override for the column whose
+ filters are mirrored; NULL means "follow ``main_dttm_col``"
+- ``table_columns.partition_value_transform`` -- the ``:value`` expression
+- ``table_columns.partition_transform_is_monotonic`` -- gates range operators
+
+The Continuum shadow tables get the same columns so dataset version history and
+restore keep working.
+
+Revision ID: a7f3c2e91d84
+Revises: 00fab727cd0a
Review Comment:
`Revises:` still names the old parent.
```suggestion
Revises: e4a7c2b9d1f3
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "eschutho (via GitHub)" <gi...@apache.org>.
eschutho commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4233509539
##########
superset/migrations/versions/2026-09-23_00-01_a7f3c2e91d84_add_partition_filter_mapping.py:
##########
@@ -0,0 +1,101 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""add partition filter mapping
+
+Adds the four columns behind the ``PARTITION_FILTER_MAPPING`` feature:
+
+- ``tables.partition_column`` -- the physical column the engine partitions on
+- ``tables.partition_mapped_column`` -- explicit override for the column whose
+ filters are mirrored; NULL means "follow ``main_dttm_col``"
+- ``table_columns.partition_value_transform`` -- the ``:value`` expression
+- ``table_columns.partition_transform_is_monotonic`` -- gates range operators
+
+The Continuum shadow tables get the same columns so dataset version history and
+restore keep working.
+
+Revision ID: a7f3c2e91d84
+Revises: 00fab727cd0a
Review Comment:
Addressed on Hugh's behalf in 8f4085c62a: the docstring now says `Revises: e4a7c2b9d1f3`, matching `down_revision`.
##########
superset/models/helpers.py:
##########
@@ -4292,36 +4389,661 @@ def dttm_sql_literal(self, dttm: datetime, col: "TableColumn") -> str:
return f"""'{dttm.strftime("%Y-%m-%d %H:%M:%S.%f")}'"""
- def get_time_filter( # pylint: disable=too-many-arguments # noqa: C901
+ def _mirror_probe_value(self, dttm: datetime, col: Optional["TableColumn"]) -> Any:
+ """
+ ``dttm`` in the mapped column's own stored representation.
+
+ The predicate this mirror stands in for compares the column against
+ `dttm_sql_literal(dttm, col)`, so the transform has to be probed with
+ the same value. On a column stored as an epoch integer, ``T`` is a
+ function of an integer: probing it with a `datetime` either returns
+ something unrelated to the partition keys or raises, and a raise costs
+ the dataset its pruning silently.
+
+ Only the ``python_date_format`` branches of `dttm_sql_literal` are
+ reproduced, because only those produce a *value*. `convert_dttm` yields
+ engine-specific SQL text, which cannot be bound as a parameter; its own
+ divergence from the probe is handled by widening the bounds instead
+ (`_engine_literal_resolution`).
+
+ In `dttm_sql_literal`'s own order, though: it asks ``convert_dttm``
+ first and reaches the format only when the engine answers nothing. A
+ column can carry both -- a TIMESTAMP with a ``%Y%m%d``
+ ``python_date_format``, or an entry in
+ ``python_date_format_by_column_name`` -- and applying the format
+ unconditionally probed a value the real predicate never compares.
+ ``event_time >= '2026-01-01 00:00:00'`` mirrored as
+ ``partition_col >= '20260101'``, and a January 15 row keyed
+ ``2026-01-15`` sorts below that string, so the chart lost a row the
+ filter keeps.
+
+ Where the engine does answer, the `datetime` is returned unchanged and
+ the widening path takes over -- which is exactly what already happens
+ for every temporal column that carries no format at all.
+ """
+ if col is None:
+ return dttm
+
+ if col.type and self.db_engine_spec.convert_dttm(
+ col.type, dttm, db_extra=self.db_extra
+ ):
+ # The format is unreachable in `dttm_sql_literal` for this column,
+ # so reproducing it here would describe a different bound.
+ return dttm
+
+ tf = col.python_date_format
+ if not tf and self.db_extra:
+ tf = self.db_extra.get("python_date_format_by_column_name", {}).get(
+ col.column_name
+ )
+ if not tf:
+ return dttm
+
+ if tf in EPOCH_FORMATS:
+ dttm_tz_aware = dttm
+ if dttm_tz_aware.tzinfo is None:
+ dttm_tz_aware = dttm_tz_aware.replace(tzinfo=timezone.utc)
+ return int(dttm_tz_aware.timestamp()) * EPOCH_FORMATS[tf]
+ return dttm.strftime(tf)
+
+ def _engine_literal_resolution(
+ self, dttm: datetime, col: Optional["TableColumn"]
+ ) -> LiteralResolution:
+ """
+ How much of ``dttm`` survives into this engine's literal for ``col``.
+
+ The real predicate compares `dttm_sql_literal(dttm, col)`, so whatever
+ that literal throws away is a bound the engine never sees. A mirror
+ derived from the full precision then describes a *narrower* range than
+ the predicate it stands in for -- and narrower means it drops rows the
+ filter keeps.
+
+ Two things get thrown away in practice:
+
+ - the sub-second part. SQLite renders a timestamp with
+ ``timespec="seconds"``.
+ - the time of day entirely. Every engine spec with a ``types.Date``
+ branch renders ``dttm.date().isoformat()``, so Presto, Trino,
+ BigQuery and some two dozen others answer `DATE '2026-01-01'` for a
+ bound of 10:00 -- and `T(DATE '2026-01-01')` is below the mirror's
+ own lower bound, so the whole first day is dropped.
+
+ Detected rather than enumerated per engine, because the branch depends
+ on the column's type as well as the spec: instants differing only in the
+ part under test render as the same text exactly when the engine has
+ thrown that part away.
+
+ The day test uses two fixed times of day rather than ``dttm`` and one
+ alternative, so a bound that happens to sit on the hour the alternative
+ uses cannot read as "no time at all". Neither probe sits at midnight on
+ purpose: SQLite renders a DATE column at exactly midnight as a bare
+ date, so a midnight probe would differ from its alternative for a
+ reason that has nothing to do with resolution.
+
+ Likewise both sub-second probes carry a non-zero remainder. Comparing
+ against ``dttm`` truncated to the second looks like the obvious test and
+ is wrong for the same formatting-boundary reason.
+
+ A non-temporal column has no answer here, and asking anyway gets a wrong
+ one. SQLite's ``convert_dttm`` renders for ``types.String`` as well as
+ for the date types, so a ``VARCHAR`` mapped column reads as
+ second-resolution -- and a filter value that happens to *look* like an
+ instant then has its bound rounded as though the engine had truncated
+ it. On a VARCHAR ``code`` mapped onto a VARCHAR ``p`` by ``:value``,
+ ``code < '2026-07-06T10:08:11.500000'`` was mirrored as
+ ``p <= '2026-07-06 10:08:12.000000'``; a space sorts before ``T``, so a
+ row holding ``2026-07-06T09:00:00`` fell outside the mirror while
+ matching the filter.
+
+ The guard lives here rather than in each caller so this and
+ `_column_literal_resolution` cannot disagree about which column is
+ coarse -- which is the same reason that helper delegates to this one.
+ """
+ if col is None or not col.type or not col.is_dttm:
Review Comment:
Addressed on Hugh's behalf in f1dce85766: `_engine_literal_resolution` now checks `col.type_generic != GenericDataType.TEMPORAL` (which is already TEMPORAL when `is_dttm` is set), so an unflagged DATE column is rounded to the day again and VARCHAR columns are still skipped. Added `test_the_probe_widens_to_the_day_on_a_date_column_not_flagged_temporal`, which fails without the change.
##########
superset/models/helpers.py:
##########
@@ -4292,36 +4389,661 @@ def dttm_sql_literal(self, dttm: datetime, col: "TableColumn") -> str:
return f"""'{dttm.strftime("%Y-%m-%d %H:%M:%S.%f")}'"""
- def get_time_filter( # pylint: disable=too-many-arguments # noqa: C901
+ def _mirror_probe_value(self, dttm: datetime, col: Optional["TableColumn"]) -> Any:
+ """
+ ``dttm`` in the mapped column's own stored representation.
+
+ The predicate this mirror stands in for compares the column against
+ `dttm_sql_literal(dttm, col)`, so the transform has to be probed with
+ the same value. On a column stored as an epoch integer, ``T`` is a
+ function of an integer: probing it with a `datetime` either returns
+ something unrelated to the partition keys or raises, and a raise costs
+ the dataset its pruning silently.
+
+ Only the ``python_date_format`` branches of `dttm_sql_literal` are
+ reproduced, because only those produce a *value*. `convert_dttm` yields
+ engine-specific SQL text, which cannot be bound as a parameter; its own
+ divergence from the probe is handled by widening the bounds instead
+ (`_engine_literal_resolution`).
+
+ In `dttm_sql_literal`'s own order, though: it asks ``convert_dttm``
+ first and reaches the format only when the engine answers nothing. A
+ column can carry both -- a TIMESTAMP with a ``%Y%m%d``
+ ``python_date_format``, or an entry in
+ ``python_date_format_by_column_name`` -- and applying the format
+ unconditionally probed a value the real predicate never compares.
+ ``event_time >= '2026-01-01 00:00:00'`` mirrored as
+ ``partition_col >= '20260101'``, and a January 15 row keyed
+ ``2026-01-15`` sorts below that string, so the chart lost a row the
+ filter keeps.
+
+ Where the engine does answer, the `datetime` is returned unchanged and
+ the widening path takes over -- which is exactly what already happens
+ for every temporal column that carries no format at all.
+ """
+ if col is None:
+ return dttm
+
+ if col.type and self.db_engine_spec.convert_dttm(
+ col.type, dttm, db_extra=self.db_extra
+ ):
+ # The format is unreachable in `dttm_sql_literal` for this column,
+ # so reproducing it here would describe a different bound.
+ return dttm
+
+ tf = col.python_date_format
+ if not tf and self.db_extra:
+ tf = self.db_extra.get("python_date_format_by_column_name", {}).get(
+ col.column_name
+ )
+ if not tf:
+ return dttm
+
+ if tf in EPOCH_FORMATS:
+ dttm_tz_aware = dttm
+ if dttm_tz_aware.tzinfo is None:
+ dttm_tz_aware = dttm_tz_aware.replace(tzinfo=timezone.utc)
+ return int(dttm_tz_aware.timestamp()) * EPOCH_FORMATS[tf]
+ return dttm.strftime(tf)
+
+ def _engine_literal_resolution(
+ self, dttm: datetime, col: Optional["TableColumn"]
+ ) -> LiteralResolution:
+ """
+ How much of ``dttm`` survives into this engine's literal for ``col``.
+
+ The real predicate compares `dttm_sql_literal(dttm, col)`, so whatever
+ that literal throws away is a bound the engine never sees. A mirror
+ derived from the full precision then describes a *narrower* range than
+ the predicate it stands in for -- and narrower means it drops rows the
+ filter keeps.
+
+ Two things get thrown away in practice:
+
+ - the sub-second part. SQLite renders a timestamp with
+ ``timespec="seconds"``.
+ - the time of day entirely. Every engine spec with a ``types.Date``
+ branch renders ``dttm.date().isoformat()``, so Presto, Trino,
+ BigQuery and some two dozen others answer `DATE '2026-01-01'` for a
+ bound of 10:00 -- and `T(DATE '2026-01-01')` is below the mirror's
+ own lower bound, so the whole first day is dropped.
+
+ Detected rather than enumerated per engine, because the branch depends
+ on the column's type as well as the spec: instants differing only in the
+ part under test render as the same text exactly when the engine has
+ thrown that part away.
+
+ The day test uses two fixed times of day rather than ``dttm`` and one
+ alternative, so a bound that happens to sit on the hour the alternative
+ uses cannot read as "no time at all". Neither probe sits at midnight on
+ purpose: SQLite renders a DATE column at exactly midnight as a bare
+ date, so a midnight probe would differ from its alternative for a
+ reason that has nothing to do with resolution.
+
+ Likewise both sub-second probes carry a non-zero remainder. Comparing
+ against ``dttm`` truncated to the second looks like the obvious test and
+ is wrong for the same formatting-boundary reason.
+
+ A non-temporal column has no answer here, and asking anyway gets a wrong
+ one. SQLite's ``convert_dttm`` renders for ``types.String`` as well as
+ for the date types, so a ``VARCHAR`` mapped column reads as
+ second-resolution -- and a filter value that happens to *look* like an
+ instant then has its bound rounded as though the engine had truncated
+ it. On a VARCHAR ``code`` mapped onto a VARCHAR ``p`` by ``:value``,
+ ``code < '2026-07-06T10:08:11.500000'`` was mirrored as
+ ``p <= '2026-07-06 10:08:12.000000'``; a space sorts before ``T``, so a
+ row holding ``2026-07-06T09:00:00`` fell outside the mirror while
+ matching the filter.
+
+ The guard lives here rather than in each caller so this and
+ `_column_literal_resolution` cannot disagree about which column is
+ coarse -- which is the same reason that helper delegates to this one.
+ """
+ if col is None or not col.type or not col.is_dttm:
+ return LiteralResolution.FULL
+
+ def render(moment: datetime) -> Optional[str]:
+ return self.db_engine_spec.convert_dttm(
+ col.type, moment, db_extra=self.db_extra
+ )
+
+ try:
+ early = render(dttm.replace(hour=1, minute=2, second=3, microsecond=444444))
+ late = render(
+ dttm.replace(hour=22, minute=33, second=44, microsecond=555555)
+ )
+ if early is not None and early == late:
+ return LiteralResolution.DAY
+
+ # Flooring to the second is a no-op on a bound that has no
+ # sub-second part, so there is nothing to detect.
+ if not dttm.microsecond:
+ return LiteralResolution.FULL
+
+ first = render(dttm.replace(microsecond=111111))
+ second = render(dttm.replace(microsecond=222222))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return LiteralResolution.FULL
+
+ if first is not None and first == second:
+ return LiteralResolution.SECOND
+ return LiteralResolution.FULL
+
+ def _round_bounds_outward(
self,
- time_col: "TableColumn",
+ start_dttm: Optional[datetime],
+ end_dttm: Optional[datetime],
+ col: Optional["TableColumn"],
+ ) -> tuple[Optional[datetime], Optional[datetime]]:
+ """
+ The bounds widened to whatever the engine's literal actually resolves to.
+
+ Rounding outward is never narrower than the predicate being mirrored,
+ which is the only property the mirror has to hold.
+ """
+ resolutions = {
+ self._engine_literal_resolution(bound, col)
+ for bound in (start_dttm, end_dttm)
+ if bound is not None
+ }
+
+ if LiteralResolution.DAY in resolutions:
+ # The engine compares a bare date, so the real predicate's lower
+ # bound is the start of that day and its upper bound admits the
+ # whole of the day before. Anything finer excludes rows it keeps.
+ if start_dttm is not None:
+ start_dttm = start_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ )
+ if end_dttm is not None and end_dttm != end_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ ):
+ end_dttm = end_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ ) + timedelta(days=1)
+ elif LiteralResolution.SECOND in resolutions:
+ if start_dttm is not None:
+ start_dttm = start_dttm.replace(microsecond=0)
+ if end_dttm is not None and end_dttm.microsecond:
+ end_dttm = end_dttm.replace(microsecond=0) + timedelta(seconds=1)
+
+ return start_dttm, end_dttm
+
+ def _literal_is_coarser_than(
+ self, dttm: datetime, col: Optional["TableColumn"]
+ ) -> bool:
+ """
+ Whether the engine's literal for ``dttm`` throws away part of it.
+
+ Unlike a range, an equality cannot be widened outward, so the only safe
+ answer when the engine compares less than the full value is to decline
+ the mirror.
+ """
+ resolution = self._engine_literal_resolution(dttm, col)
+ if resolution is LiteralResolution.DAY:
+ return dttm != dttm.replace(hour=0, minute=0, second=0, microsecond=0)
+ if resolution is LiteralResolution.SECOND:
+ return bool(dttm.microsecond)
+ return False
+
+ def _column_literal_resolution(
+ self, col: Optional["TableColumn"]
+ ) -> LiteralResolution:
+ """
+ How much of *any* value this engine compares on ``col``.
+
+ `_engine_literal_resolution` answers about a particular instant, which
+ is what a mirror derived from one needs. Two callers have no instant to
+ ask about -- the summary the Explore glyph reads, and a filter value
+ `_instant_from_filter_value` cannot read as an instant at all -- and
+ both need the column's own answer. Through one helper so that the glyph
+ and the query path cannot disagree about which column is coarse, which
+ is the same reason `mirrorable_operators` is computed once.
+
+ A non-temporal column has no answer, and asking anyway gets a wrong one:
+ SQLite's ``convert_dttm`` renders for ``types.String`` as well as for the
+ date types, so a reference instant makes a ``VARCHAR`` mapped column look
+ second-resolution -- and ``country = 'US'``, the text half of this
+ feature, reads as a value the engine compares coarsely.
+
+ That guard is `_engine_literal_resolution`'s, not this function's. It
+ used to be here, on the belief that the per-instant callers never met
+ the case because they arrive only with a value that parsed as an
+ instant -- which is untrue of a text column holding ISO-shaped text,
+ where the value parses and the column is still not temporal.
+ """
+ return self._engine_literal_resolution(_RESOLUTION_REFERENCE_INSTANT, col)
+
+ def _round_bound_outward(
+ self,
+ instant: datetime,
+ col: Optional["TableColumn"],
+ *,
+ is_upper: bool,
+ ) -> datetime:
+ """
+ One bound widened to whatever the engine resolves ``col`` to.
+
+ `_round_bounds_outward` answers for a since/until pair, because a time
+ range is the shape it was written for. A single comparison is one end of
+ such a pair with the other end absent, and the widening is per-end
+ already -- a lower bound moves back, an upper bound forward.
+
+ Narrowing the return type is the other half of the point: a bound handed
+ in non-`None` comes back non-`None`, and saying so here saves every
+ caller from re-establishing it.
+ """
+ start_dttm, end_dttm = self._round_bounds_outward(
+ None if is_upper else instant,
+ instant if is_upper else None,
+ col,
+ )
+ rounded = end_dttm if is_upper else start_dttm
+ return rounded if rounded is not None else instant
+
+ def _mirror_probe_input(
+ self,
+ operator: utils.FilterOperator,
+ value: Any,
+ col: Optional["TableColumn"],
+ ) -> Any:
+ """
+ ``value`` in the representation the mirror may probe the transform at.
+
+ A simple filter on a temporal column carries a *string*.
+ `filter_values_handler` rewrites only an all-digit value, which it reads
+ as epoch milliseconds, so ``'2026-07-06 10:08:11'`` reaches here exactly
+ as the chart author typed it and is bound as text. The engine compares
+ that text against the column under its own cast, and on a ``DATE``
+ column the cast drops the time of day: the filter keeps the whole of
+ 2026-07-06 while a mirror probed at 10:08:11 keeps one instant of it,
+ which is narrower than the predicate it stands in for.
+
+ So the text is read back into the instant it denotes -- the only way
+ `_engine_literal_resolution`, which answers about a `datetime`, reaches
+ a filter value at all -- and where the engine compares less of that
+ instant than the filter carries, what to do about it is a property of
+ the *operator*:
+
+ * a bound rounds outward, through the helper the range collector uses.
+ Reading one extra bucket at the edge is the trade this feature makes
+ everywhere else too -- see `mirror_operator` -- and the original
+ predicate is still in the query to exclude the rows that bucket adds.
+ * an equality, or one member of an ``IN`` list, has nowhere to widen to.
+ These entries are ``AND``-ed onto the query, so "or the day either
+ side" is not something this sink can express, and the request is
+ declined with `_UNMIRRORABLE`. The query is then correct and unpruned,
+ which is the one failure mode this feature is allowed.
+
+ An instant carrying a UTC offset is declined for every operator, a
+ bound included. Rounding one outward would first have to place it in the
+ frame the partition column was written in, and guessing that frame is
+ how a mirror ends up a whole offset narrower than the filter -- see the
+ load-bearing assumption in
+ `superset.connectors.sqla.partition_mapping`.
+
+ A *string* `_instant_from_filter_value` cannot read at all is declined on
+ the same terms, and for the same reason one more step back: there is no
+ instant to round. ``'07/06/2026 10:08:11'`` is not ISO 8601, so the
+ parser leaves it alone -- and Postgres casts that same text to a DATE and
+ keeps the whole of July 6 while the probe, handed the string verbatim,
+ evaluates the transform at 10:08:11 and asks for a partition key no row
+ holds. That is exactly the narrowing the ISO-only parser was written to
+ prevent, reached through a value it declines to read, so the decline has
+ to travel with it. Which costs a non-ISO *date* its pruning too, because
+ telling July 6 from June 7 is the guess that started this.
+
+ Only a string. `_as_probe_input` has already run, so the engine SQL
+ `filter_values_handler` returns for an epoch-millisecond bound arrives
+ here as a `RawProbeValue` rather than text -- and that literal was
+ rendered by the engine at the engine's own resolution, so it is the one
+ thing on this path with nothing left to resolve.
+
+ Where the engine compares the whole instant, a string is returned
+ exactly as it arrived -- down to the type the probe binds and the cache
+ key it lands on, because every query that was already correct has to
+ stay byte-for-byte correct. A `datetime` is still converted, which it
+ has always needed: on a column stored as an epoch integer the transform
+ is a function of an integer, and a `datetime` is not the value the real
+ predicate compares.
+ """
+ parsed = _instant_from_filter_value(value)
+ if parsed is None:
+ if (
+ isinstance(value, str)
+ and self._column_literal_resolution(col) is not LiteralResolution.FULL
+ ):
+ return _UNMIRRORABLE
+ return value
+
+ if (
+ self._engine_literal_resolution(parsed.replace(tzinfo=None), col)
Review Comment:
Addressed on Hugh's behalf in 1ee6c37feb: the offset check in `_mirror_probe_input` now runs before the full-resolution early return, so any value carrying a UTC offset is declined, as the docstring already said. Added a parametrized test (`==` and `>=` on a full-resolution TIMESTAMP column) that checks the probe never runs and no mirror is emitted.
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2730 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+#: Returned by `ExploreMixin.mirror_probe_request` for a filter no mirror can
+#: stand in for: one the engine compares more coarsely than the value carries, a
+#: value it cannot render as a literal, or an ``IN`` list with a member of
+#: either kind. A sentinel rather than `None`, because `None` is a filter value
+#: in its own right.
+#:
+#: Lives here rather than beside that method so the preview can read it too:
+#: `superset.models.helpers` imports this module, so the sentinel can only cross
+#: the boundary in this direction. Both callers have to recognise the same
+#: object -- a preview that answered "valid" for a request the chart path
+#: declines is the drift this is here to prevent.
+UNMIRRORABLE = object()
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
Review Comment:
Addressed on Hugh's behalf in 159185ed03, by coercing the value rather than declining. `_mirror_probe_input` converts a numeric value to the mapped column's number type before probing, where that is lossless: an integral value for an integer column (so `'1.0'` is probed as `1`) and an exactly representable value for a float column (so `1` is probed as `1.0`). Non-integral values on integer columns are left alone because they match no row. DECIMAL is also left alone: its text depends on a scale the engine spec doesn't expose, so it stays an owner assumption like per-column collation. Because the step lives in `mirror_probe_request`, the preview gets it too. New parametrized test covers INTEGER, REAL and DECIMAL.
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2730 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+#: Returned by `ExploreMixin.mirror_probe_request` for a filter no mirror can
+#: stand in for: one the engine compares more coarsely than the value carries, a
+#: value it cannot render as a literal, or an ``IN`` list with a member of
+#: either kind. A sentinel rather than `None`, because `None` is a filter value
+#: in its own right.
+#:
+#: Lives here rather than beside that method so the preview can read it too:
+#: `superset.models.helpers` imports this module, so the sentinel can only cross
+#: the boundary in this direction. Both callers have to recognise the same
+#: object -- a preview that answered "valid" for a request the chart path
+#: declines is the drift this is here to prevent.
+UNMIRRORABLE = object()
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error( # noqa: C901
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ And it must be a *read*. Shape is a separate question from effect: a bare
+ scalar expression can still write, so `SQLStatement.is_mutating` is asked
+ too -- the same question SQL Lab and the chart executor ask before letting
+ SQL run. See the gate itself for what that reaches and what it does not.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ # Also ahead of the parse, and for a stronger reason than cost: every gate
+ # below reasons about the parse tree, and this is the one construct that
+ # makes the parse tree describe a different statement from the one the
+ # engine runs. Checked here as well as in `validate_transform` because this
+ # is the door a row written by an earlier release still comes through.
+ if contains_executable_comment(transform):
+ return str(
+ _(
+ "A partition value transform cannot contain a MySQL "
+ "executable comment, which the database executes and every "
+ "validator reads as a comment."
+ )
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The read-only gate, which nothing above implies. The shape gates ask what
+ # the transform *selects*; this asks what evaluating it *does*, and a bare
+ # scalar expression can still write. `nextval(:value)` on PostgreSQL
+ # advances a sequence: one function call, no clause, no sub-query, and not
+ # in the default `DISALLOWED_SQL_FUNCTIONS` either -- so every gate above
+ # passes it and the probe then runs it. `setval` is the same shape, and
+ # `exp.Execute` and the opaque-`exp.Command` forms arrive the same way.
+ #
+ # The large-object writers (`lo_export`, `lowrite`, `lo_from_bytea`, ...)
+ # are caught here too, and the shipped denylist happens to name them as
+ # well -- but that is config an operator can replace, while this is not.
+ #
+ # `is_mutating` is the same question SQL Lab, `get_virtual_table_metadata`
+ # and the chart executor ask before letting SQL run, so a transform is held
+ # to the bar the rest of Superset already sets rather than to one invented
+ # here. Unconditional rather than gated on `Database.allow_dml`: a transform
+ # is a scalar function of `:value` by definition, so there is no legitimate
+ # mutating one, and the probe runs on a cache schedule nobody chose -- a
+ # write would repeat every time the entry expired.
+ #
+ # It bears saying what this does not reach. A user-defined function whose
+ # body writes is a plain call no parser can tell from `lower(:value)`, and
+ # `is_mutating`'s function-name walk is PostgreSQL-only by design, since the
+ # same names are read-only elsewhere. Neither residual is specific to this
+ # feature -- a dataset editor can already have the engine evaluate an
+ # arbitrary expression through a calculated column or a virtual dataset's
+ # SQL -- and closing them means authorizing the preview against the
+ # database, not parsing harder.
+ if statement.is_mutating():
+ return str(
+ _(
+ "A partition value transform cannot change data. It is "
+ "evaluated against the database to check that it mirrors, so "
+ "it has to be a read."
+ )
+ )
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the probe
+ uninspected -- string elements are escaped by the dialect's own literal
+ processor. `probe_sql_is_evaluable` then re-reads the finished query, which
+ is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def _placeholder_is_bindable(transform: str) -> bool:
+ """
+ Whether SQLAlchemy's ``text()`` can see ``:value`` as a bound parameter.
+
+ `VALUE_PLACEHOLDER_RE` is ``:value\b``, which matches the placeholder in a
+ Postgres cast such as ``:value::bigint``. SQLAlchemy's own bind scan is
+ ``(?<![:\\w$]):([\\w$]+)(?![:\\w$])`` -- note the trailing exclusion -- so a
+ following colon stops it: ``text(":value::bigint")`` reports a parameter
+ named ``valu``, and ``.bindparams(bindparam("value"))`` then raises
+ ``ArgumentError``.
+
+ `_probe` swallows that, so the only symptom was a perfectly valid transform
+ whose mapping silently never pruned, and a preview reporting an engine
+ failure for SQL that was never sent. Every write-side gate passes the
+ transform: it parses, it is a bare expression, and the placeholder *is* in
+ an executable position.
+
+ Answered by attempting the bind itself rather than by pattern-matching
+ ``::`` or reading ``text()``'s private parameter map, so this cannot
+ disagree with what `build_probe_sql` is about to do -- on any dialect, or on
+ a SQLAlchemy whose scan changes.
+ """
+ try:
+ sa.text(transform).bindparams(sa.bindparam("value", value=None))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return False
+ return True
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ bindable = _placeholder_is_bindable(transform)
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ elif bindable:
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ rendered = _compile_literal(clause, dialect)
+ else:
+ # `text()` cannot see the placeholder (see
+ # `_placeholder_is_bindable`), so the value is rendered by the
+ # dialect's own literal processor first and substituted as SQL
+ # text. The same two steps in the other order: binding exists to
+ # get the value through that processor, and `_compile_literal`
+ # inlines the result either way, so this is the same string by a
+ # different route -- not a loosening of the "never interpolate a
+ # raw value" rule. `parse_skeleton` substitutes literally, so a
+ # rendered literal containing a backslash is safe here.
+ rendered = parse_skeleton(
+ transform, _compile_literal(sa.literal(value), dialect)
+ )
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Four things have to hold, and all four are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ # Before the parse, because this gate's whole contract is that what the
+ # parse describes is what the engine will run, and an executable comment is
+ # precisely the text where that stops being true. The transform is already
+ # refused for carrying one; this covers the compiled statement, so no later
+ # change to how values are rendered can reintroduce it behind the gates
+ # below.
+ if contains_executable_comment(sql):
+ return False
+
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if not isinstance(statement, SQLStatement):
+ # A dialect whose statements this gate cannot take apart -- KQL -- gets
+ # no probe rather than an unchecked one. It never had one: the clause
+ # inspection below is implemented for SQL statements only, and the
+ # alternative to declining here is an `AttributeError` that `_probe`
+ # swallows into the same outcome, less legibly.
+ return False
+ if statement.has_subquery():
+ return False
+ if statement.get_clause_names() - {"from"}:
+ return False
+ if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+ """
+ The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+ Parsed rather than string-compared so that the comparison in
+ `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+ not parse answers ``None``, which no statement carrying a FROM can match --
+ the probe then declines, which is the right way for an unreadable engine
+ constant to fail.
+ """
+ if not from_suffix.strip():
+ return None
+ try:
+ return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+ except SupersetParseError:
+ return None
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=values is not None and not any(value is None for value in values),
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ from_suffix = database.db_engine_spec.select_without_from_suffix
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ from_suffix,
+ )
+ if not probe_sql_is_evaluable(
+ sql, database.backend, len(distinct), from_suffix
+ ):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _execution_identity(database: Database) -> str | None:
+ """
+ Who the warehouse will run the probe as, when that can vary by caller.
+
+ `_probe_cache_key` keys on the `Database` record, which is the *connection*
+ -- not the identity it is opened under. Two hooks make that identity a
+ function of the Superset user instead:
+
+ * ``impersonate_user`` on the database, which hands the effective username
+ to `db_engine_spec.impersonate_user`;
+ * ``DB_CONNECTION_MUTATOR``, which receives the effective username and may
+ return an entirely different account's URL.
+
+ Under either one, a cached probe result computed under user A's grants was
+ served to user B, and the preview echoed it back in ``emitted_predicate``.
+ A transform wrapping a read-capable function the denylist does not name --
+ Oracle's ``DBMS_XMLGEN.GETXML`` is the worked example -- then leaks across
+ users who were never allowed the same rows.
+
+ Returns ``None`` when neither hook is configured, which is the common case
+ and deliberately leaves the key as it was: the cache exists to keep a
+ synchronous warehouse round trip off the chart-query path, and keying every
+ deployment on the username would cost every deployment the hit rate to fix
+ the two that need it.
+
+ The *Superset* username rather than the resolved warehouse account, because
+ it is the input both hooks branch on, and reading it needs no URL parse and
+ puts no credential in the key.
+ """
+ if not (database.impersonate_user or app.config["DB_CONNECTION_MUTATOR"]):
+ return None
+ return get_username()
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _mirror_verdict_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str:
+ """
+ `_probe_cache_key` without the values.
+
+ Whether a transform can be evaluated at all is a property of the transform
+ and the connection, not of the filter that happened to be probing it, so
+ one chart's answer settles the question for the next one.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ # Whether a transform *can* be evaluated is a property of the
+ # transform and the connection -- but under impersonation the
+ # connection is per-user, and a function one account may call can
+ # be refused to another. See `_execution_identity`.
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_verdict:{digest}"
+
+
+def record_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ *,
+ mirrors: bool,
+) -> None:
+ """
+ Remember whether this transform produced a mirror, for the UI to read.
+
+ Advisory only. Nothing in the query path consults it: a probe that failed
+ once is retried on the next chart exactly as it is today, because declining
+ to prune for a whole cache timeout over one transient engine blip is the
+ trade `evaluate_transform` deliberately refuses -- see the comment where it
+ declines to cache a failure.
+
+ What this is for is the *claim*. `is_transform_active` parses the transform
+ and no more, so a transform the database rejects -- a misspelled function
+ is the common case -- is "active", and the editor's banner and Explore's
+ pruning glyph promise a speed-up that never happens. A promise is exactly
+ the thing that may be withheld on one bad answer and restored on a good
+ one, which is why this is a separate entry from the probe's own results
+ rather than a relaxation of that rule.
+
+ Written by `_run_probe`, so the preview endpoint -- which shares the
+ evaluator -- settles the question before the owner has even saved.
+ """
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(
+ _mirror_verdict_cache_key(database, catalog, schema, transform),
+ mirrors,
+ timeout=timeout,
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform verdict", exc_info=True)
+
+
+def known_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> bool | None:
+ """
+ The last verdict `record_mirror_verdict` stored, or `None` if there is none.
+
+ `None` is the honest answer on a cold cache and is deliberately not `False`:
+ reporting a working mapping as broken until something probes it would
+ trade one wrong claim for another. The alternative -- probing from the
+ read side -- would put a warehouse round trip on every Explore and
+ dashboard load, and a failing transform is not cached at all, so it would
+ be a round trip every single time.
+ """
+ try:
+ verdict = cache_manager.cache.get(
+ _mirror_verdict_cache_key(database, catalog, schema, transform)
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return verdict if isinstance(verdict, bool) else None
+
+
+def _compile_literal(element: Any, dialect: Dialect | None) -> str:
+ """
+ Compile with inline literals, undoing the paramstyle's percent doubling.
+
+ Both ``TextClause`` and literal compilation run the dialect's
+ ``post_process_text``, which doubles every ``%`` whenever the identifier
+ preparer asks it to -- true for MySQL and Postgres and for every spec
+ inheriting their paramstyle. That doubling exists so a later DBAPI
+ parameter-interpolation pass can undo it, and the probe has no such pass:
+ it executes with no bound parameters at all. So a transform of
+ ``date_format(:value, '%Y%m%d')`` reaches the warehouse asking for the
+ literal string ``%%Y%%m%%d``, the probe returns that instead of a date, and
+ the mirrored predicate drops every row the filter keeps.
+
+ The same normalization ``Database.compile_sqla_query`` applies for the same
+ reason. ``_double_percents`` is private and not guaranteed on a third-party
+ dialect, hence the ``getattr`` default.
+ """
+ compiled = str(
+ element.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
+ )
+ if dialect is not None and getattr(
+ dialect.identifier_preparer, "_double_percents", False
+ ):
+ compiled = compiled.replace("%%", "%")
+ return compiled
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be *asked* to stand in for itself, and the transform
+ cannot carry Jinja or call a non-deterministic function. Tier 2
+ (``blocking=False``) is everything that merely leaves the mapping inactive
+ -- including a self-mapping nobody asked for, where the partition column
+ merely happens to be the default datetime column.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column == partition_column:
+ # Asked for explicitly, so report it as the mistake it is.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+ elif not partition_mapped_column and main_dttm_col == partition_column:
+ # Resolved onto itself only because the default datetime column happens
+ # to be the partition column -- a state metadata sync could produce
+ # without anyone asking for it. The mapping is inert either way, since
+ # `resolve_partition_mapping` bails out on it, so this reports and lets
+ # the write through: blocking here means a dataset already in the state
+ # can never be saved again, not even to change its description, and
+ # there is no field whose edit would clear the error first.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "%(name)s is both the partition column and the default "
+ "datetime column, so the mapping points at itself and "
+ "stays inactive. Set a mapped column override, or change "
+ "the default datetime column.",
+ name=partition_column,
+ ),
+ blocking=False,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def drop_unmapped_value_transforms(
+ columns: list[dict[str, Any]] | None,
+ *,
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ names_by_id: dict[int, str] | None = None,
+) -> list[str]:
+ """
+ Null the value transform on every *incoming* column the mapping cannot mirror.
+
+ The write-side twin of `DatasetDAO.clear_unmapped_partition_transforms`,
+ which answers for the model. A mapping has exactly one mirrored column, so
+ at most one column may carry a transform. One parked on any other column is
+ invisible -- no row but the mapped one renders a transform -- and yet it is
+ stored, and it goes live the moment the mapped column resolves back to it.
+ Clearing an override is enough to do that: a null
+ ``partition_mapped_column`` means "follow ``main_dttm_col``".
+
+ Ungated on the feature flag, unlike its model-level twin, and the difference
+ is what each one discards. That one drops stored configuration, so with the
+ flag off it would be pure loss. This one drops only a value the request in
+ hand is asking to write where the invariant says none may live -- and the
+ flag-off window is precisely when such a value gets parked for later, since
+ the editor hides these fields and the model-level pass declines to run.
+
+ Three writers reach the columns with no effective model-level pass between
+ them, which is why this exists at all: the deprecated
+ ``POST /datasource/save/``, which writes straight through
+ `update_from_object` and so never had one; and a
+ ``PUT /api/v1/dataset/<pk>`` or a dataset import made while the flag is
+ off, where the pass runs on both sides of the write and declines on both.
+
+ Mutates the payload in place, because every caller hands its own request
+ dict straight on to the code that writes it. Returns the names it cleared,
+ so the caller can say so in a log: this is a silent correction to a payload
+ whose author may have meant it.
+
+ A column whose payload mentions neither field is left alone. "Incoming" is
+ the whole scope -- a transform already in storage on a column this request
+ says nothing about is the model-level pass's business, under its own flag.
+
+ The mapped column resolves the way every other reader resolves it,
+ ``partition_mapped_column or main_dttm_col``, and resolves to nothing
+ without a partition column -- in which case no column may hold a transform
+ either.
+
+ :param names_by_id: how to read the name off a payload entry that gives
+ only an ``id``. `DatasetDAO._upsert_columns` identifies an existing
+ column by its primary key and lets ``column_name`` be omitted -- the
+ column keeps the name it has -- so without this an ordinary PUT looked
+ like a payload of nameless columns, none of which matched the mapped
+ one, and every transform in it was dropped. Callers whose writer keys
+ on the name instead (`update_from_object`, the importer) pass nothing.
+ An entry this cannot name is left alone rather than guessed at.
+ """
+ mapped_column = (
+ (partition_mapped_column or main_dttm_col) if partition_column else None
+ )
+ cleared: list[str] = []
+ for column in columns or []:
+ name = column.get("column_name")
+ if name is None and names_by_id is not None:
+ column_id = column.get("id")
+ if column_id is not None:
+ name = names_by_id.get(column_id)
+ if name is None or name == mapped_column:
+ continue
+ if column.get("partition_value_transform") or column.get(
+ "partition_transform_is_monotonic"
+ ):
+ column["partition_value_transform"] = None
+ column["partition_transform_is_monotonic"] = False
+ cleared.append(name)
+ return cleared
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if contains_executable_comment(transform):
+ # Blocking, and checked on raw text next to the Jinja gate because no
+ # parse reports it: sqlglot reads `/*!50000 ... */` as comment data
+ # while MySQL and MariaDB execute it, so every shape gate downstream
+ # inspects a statement the engine will not run. See
+ # `EXECUTABLE_COMMENT_RE`.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform cannot contain a MySQL executable "
+ "comment (/*! ... */ or /*M! ... */). Those are comments "
+ "to every validator and statement text to the database, "
+ "so what would run is not what was checked."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_bare_expression(transform, engine):
+ # Blocking, and deliberately placed in `validate_transform` rather than
+ # only at the probe: one issue here closes the PUT, the importer, the
+ # query-time gate through `is_transform_active`, the Explore indicator's
+ # active verdict and the preview endpoint, all of which already consult
+ # this function.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform must be a single SQL expression. It "
+ "cannot carry a FROM, WHERE, GROUP BY or any other clause, "
+ "and it cannot contain a sub-query."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not contains_value_placeholder(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform must contain the :value placeholder, "
+ "which stands for the filter value being mirrored."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not placeholder_is_executable(transform, engine):
+ # Blocking, and for the same reason the shape gate above is: this is
+ # the function the PUT, the importer, `is_transform_active`, the
+ # Explore indicator and the preview all consult, so one issue here
+ # closes every door at once. A placeholder inside a string literal is
+ # a sub-query the engine will run once a filter value closes the quote;
+ # one inside a comment silently eats the probe's own alias.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The :value placeholder must appear where the engine will "
+ "evaluate it. It cannot sit inside a string literal or a "
+ "comment."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if functions := find_non_deterministic_functions(transform, engine):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform calls %(functions)s, whose result "
+ "depends on when and where it runs. The transform is "
+ "evaluated in a separate session and the result is cached, "
+ "so the emitted predicate would freeze a snapshot of that "
+ "moment.",
+ functions=", ".join(sorted(functions)),
+ ),
+ blocking=True,
+ )
+ ]
+
+ return []
+
+
+@lru_cache(maxsize=LRU_CACHE_MAX_SIZE)
+def is_transform_active(transform: str | None, engine: str) -> bool:
+ """
+ Whether Superset will mirror filters through this transform.
+
+ `validate_transform` with the messages discarded, so the Explore indicator
+ cannot advertise a mapping the save path recorded as inactive. Anything
+ cheaper here would be a second, weaker statement of the same rule, free to
+ drift from the one the save path applies.
+
+ Blocking issues count too. Jinja and non-deterministic transforms are
+ rejected on PUT, but `CreateDatasetCommand` and import do not validate the
+ mapping, so one can still reach the database -- and it would never mirror a
+ filter either.
+
+ Memoized because `partition_filter_mapping_summary` is serialized on every
+ Explore and dashboard load and this parses the transform. The key is
+ everything the answer depends on: `validate_transform` reads no session, no
+ locale and no config beyond `SQL_MAX_PARSE_LENGTH`, which bounds the parser
+ rather than changing a verdict within that bound.
+ """
+ return not validate_transform(transform, engine)
+
+
+def preview_partition_mapping( # pylint: disable=too-many-return-statements
+ datasource: SqlaTable,
+ *,
+ mapped_column: str,
+ value_transform: str | None,
+ sample_values: list[str],
+ operator: FilterOperator = FilterOperator.EQUALS,
+ is_monotonic: bool = False,
+ partition_column: str | None = None,
+) -> dict[str, Any]:
+ """
+ Evaluate a candidate mapping and describe the predicate it would emit.
+
+ Shares the evaluator -- and therefore the probe cache -- with the query
+ path, so preview and runtime cannot drift and a previewed transform warms
+ the chart path for free. The predicate itself comes from
+ `build_mirrored_predicates`, the same builder the query path uses, so
+ operator shapes cannot drift either: what the panel shows is what a chart
+ would emit.
+
+ Validation runs first and the engine second: a half-typed transform is by
+ definition unparseable, so most of what a text input produces costs zero
+ queries.
+
+ Every part of the mapping is taken from the request rather than the stored
+ dataset. The editor previews while the owner is still editing -- a mapping
+ that has to be saved before it can be checked is not a preview.
+ """
+ partition_column = partition_column or datasource.partition_column
+ if not partition_column:
+ return {
+ "valid": False,
+ "reason": "unconfigured",
+ "error": _("No partition column is set."),
+ }
+
+ columns_by_name = {str(column.column_name): column for column in datasource.columns}
+ if mapped_column not in columns_by_name:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _("%(name)s is not a column on this dataset.", name=mapped_column),
+ }
+
+ # The bail-out `resolve_partition_mapping` makes at query time, and that
+ # `partition_filter_mapping_summary` repeats for the Explore indicator.
+ # Without it here, preview reports a valid emitted predicate for a mapping
+ # no chart will ever mirror -- the one answer a preview panel must not give.
+ if has_active_advanced_data_type(columns_by_name[mapped_column]):
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _(
+ "%(name)s has an advanced data type, so its filters are "
+ "translated into their own predicate shape and cannot be "
+ "mirrored onto the partition column.",
+ name=mapped_column,
+ ),
+ }
+
+ engine = datasource.database.backend
+ for issue in validate_partition_mapping(
+ column_names=set(columns_by_name),
+ partition_column=str(partition_column),
+ partition_mapped_column=mapped_column,
+ main_dttm_col=datasource.main_dttm_col,
+ transform=value_transform,
+ engine=engine,
+ ):
+ return {
+ "valid": False,
+ # The parse failure is the one an owner sees constantly, and it is
+ # the only one the mockup gives its own headline to.
+ "reason": (
+ "parse"
+ if issue.field == "partition_value_transform"
+ and not is_parseable(value_transform, engine)
+ else "validation"
+ ),
+ "error": str(issue.message),
+ }
+
+ # The policy every other stored expression goes through. The save path
+ # applies it in `UpdateDatasetCommand._validate_partition_mapping`, but
+ # preview evaluates a candidate transform that has not been saved, so
+ # without this the gate had a door around it. See
+ # `stored_expression_error` for what is being kept out and why.
+ if reason := stored_expression_error(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ cast(str, value_transform),
+ ):
+ return {"valid": False, "reason": "validation", "error": reason}
+
+ mapping = PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=mapped_column,
+ value_transform=cast(str, value_transform),
+ is_monotonic=is_monotonic,
+ equality_is_safe=equality_mirrors_safely(
+ columns_by_name[mapped_column], datasource.database.db_engine_spec
+ ),
+ )
+ sample_input = _render_sample_input(
+ datasource, mapped_column, operator, sample_values
+ )
+
+ if operator not in PREVIEWABLE_OPERATORS:
+ # Checked before `mirrors`, which lets `TEMPORAL_RANGE` through when the
+ # transform is declared monotonic -- and the single sample value would
+ # then reach `handle_comparison_filter`, which has no case for a range
+ # and raises. The request schema rejects it too; this keeps the function
+ # honest for any other caller.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is mirrored as a pair of bounds, which "
+ "a preview of a single value cannot describe.",
+ operator=operator.value,
+ ),
+ }
+
+ if not mapping.mirrors(operator):
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is only mirrored when the transform "
Review Comment:
Addressed on Hugh's behalf in a533814e7b: when `=`/`IN` is withdrawn by `equality_mirrors_safely`, preview now returns its own message saying the database may treat strings that differ in case or trailing spaces as equal, and the generic "preserves ordering" message is no longer shown for that case. Test added. The catalogs are regenerated in d808efd1f0.
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2730 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+#: Returned by `ExploreMixin.mirror_probe_request` for a filter no mirror can
+#: stand in for: one the engine compares more coarsely than the value carries, a
+#: value it cannot render as a literal, or an ``IN`` list with a member of
+#: either kind. A sentinel rather than `None`, because `None` is a filter value
+#: in its own right.
+#:
+#: Lives here rather than beside that method so the preview can read it too:
+#: `superset.models.helpers` imports this module, so the sentinel can only cross
+#: the boundary in this direction. Both callers have to recognise the same
+#: object -- a preview that answered "valid" for a request the chart path
+#: declines is the drift this is here to prevent.
+UNMIRRORABLE = object()
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error( # noqa: C901
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ And it must be a *read*. Shape is a separate question from effect: a bare
+ scalar expression can still write, so `SQLStatement.is_mutating` is asked
+ too -- the same question SQL Lab and the chart executor ask before letting
+ SQL run. See the gate itself for what that reaches and what it does not.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ # Also ahead of the parse, and for a stronger reason than cost: every gate
+ # below reasons about the parse tree, and this is the one construct that
+ # makes the parse tree describe a different statement from the one the
+ # engine runs. Checked here as well as in `validate_transform` because this
+ # is the door a row written by an earlier release still comes through.
+ if contains_executable_comment(transform):
+ return str(
+ _(
+ "A partition value transform cannot contain a MySQL "
+ "executable comment, which the database executes and every "
+ "validator reads as a comment."
+ )
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The read-only gate, which nothing above implies. The shape gates ask what
+ # the transform *selects*; this asks what evaluating it *does*, and a bare
+ # scalar expression can still write. `nextval(:value)` on PostgreSQL
+ # advances a sequence: one function call, no clause, no sub-query, and not
+ # in the default `DISALLOWED_SQL_FUNCTIONS` either -- so every gate above
+ # passes it and the probe then runs it. `setval` is the same shape, and
+ # `exp.Execute` and the opaque-`exp.Command` forms arrive the same way.
+ #
+ # The large-object writers (`lo_export`, `lowrite`, `lo_from_bytea`, ...)
+ # are caught here too, and the shipped denylist happens to name them as
+ # well -- but that is config an operator can replace, while this is not.
+ #
+ # `is_mutating` is the same question SQL Lab, `get_virtual_table_metadata`
+ # and the chart executor ask before letting SQL run, so a transform is held
+ # to the bar the rest of Superset already sets rather than to one invented
+ # here. Unconditional rather than gated on `Database.allow_dml`: a transform
+ # is a scalar function of `:value` by definition, so there is no legitimate
+ # mutating one, and the probe runs on a cache schedule nobody chose -- a
+ # write would repeat every time the entry expired.
+ #
+ # It bears saying what this does not reach. A user-defined function whose
+ # body writes is a plain call no parser can tell from `lower(:value)`, and
+ # `is_mutating`'s function-name walk is PostgreSQL-only by design, since the
+ # same names are read-only elsewhere. Neither residual is specific to this
+ # feature -- a dataset editor can already have the engine evaluate an
+ # arbitrary expression through a calculated column or a virtual dataset's
+ # SQL -- and closing them means authorizing the preview against the
+ # database, not parsing harder.
+ if statement.is_mutating():
+ return str(
+ _(
+ "A partition value transform cannot change data. It is "
+ "evaluated against the database to check that it mirrors, so "
+ "it has to be a read."
+ )
+ )
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the probe
+ uninspected -- string elements are escaped by the dialect's own literal
+ processor. `probe_sql_is_evaluable` then re-reads the finished query, which
+ is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def _placeholder_is_bindable(transform: str) -> bool:
+ """
+ Whether SQLAlchemy's ``text()`` can see ``:value`` as a bound parameter.
+
+ `VALUE_PLACEHOLDER_RE` is ``:value\b``, which matches the placeholder in a
+ Postgres cast such as ``:value::bigint``. SQLAlchemy's own bind scan is
+ ``(?<![:\\w$]):([\\w$]+)(?![:\\w$])`` -- note the trailing exclusion -- so a
+ following colon stops it: ``text(":value::bigint")`` reports a parameter
+ named ``valu``, and ``.bindparams(bindparam("value"))`` then raises
+ ``ArgumentError``.
+
+ `_probe` swallows that, so the only symptom was a perfectly valid transform
+ whose mapping silently never pruned, and a preview reporting an engine
+ failure for SQL that was never sent. Every write-side gate passes the
+ transform: it parses, it is a bare expression, and the placeholder *is* in
+ an executable position.
+
+ Answered by attempting the bind itself rather than by pattern-matching
+ ``::`` or reading ``text()``'s private parameter map, so this cannot
+ disagree with what `build_probe_sql` is about to do -- on any dialect, or on
+ a SQLAlchemy whose scan changes.
+ """
+ try:
+ sa.text(transform).bindparams(sa.bindparam("value", value=None))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return False
+ return True
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ bindable = _placeholder_is_bindable(transform)
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ elif bindable:
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ rendered = _compile_literal(clause, dialect)
+ else:
+ # `text()` cannot see the placeholder (see
+ # `_placeholder_is_bindable`), so the value is rendered by the
+ # dialect's own literal processor first and substituted as SQL
+ # text. The same two steps in the other order: binding exists to
+ # get the value through that processor, and `_compile_literal`
+ # inlines the result either way, so this is the same string by a
+ # different route -- not a loosening of the "never interpolate a
+ # raw value" rule. `parse_skeleton` substitutes literally, so a
+ # rendered literal containing a backslash is safe here.
+ rendered = parse_skeleton(
+ transform, _compile_literal(sa.literal(value), dialect)
+ )
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Four things have to hold, and all four are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ # Before the parse, because this gate's whole contract is that what the
+ # parse describes is what the engine will run, and an executable comment is
+ # precisely the text where that stops being true. The transform is already
+ # refused for carrying one; this covers the compiled statement, so no later
+ # change to how values are rendered can reintroduce it behind the gates
+ # below.
+ if contains_executable_comment(sql):
+ return False
+
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if not isinstance(statement, SQLStatement):
+ # A dialect whose statements this gate cannot take apart -- KQL -- gets
+ # no probe rather than an unchecked one. It never had one: the clause
+ # inspection below is implemented for SQL statements only, and the
+ # alternative to declining here is an `AttributeError` that `_probe`
+ # swallows into the same outcome, less legibly.
+ return False
+ if statement.has_subquery():
+ return False
+ if statement.get_clause_names() - {"from"}:
+ return False
+ if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+ """
+ The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+ Parsed rather than string-compared so that the comparison in
+ `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+ not parse answers ``None``, which no statement carrying a FROM can match --
+ the probe then declines, which is the right way for an unreadable engine
+ constant to fail.
+ """
+ if not from_suffix.strip():
+ return None
+ try:
+ return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+ except SupersetParseError:
+ return None
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=values is not None and not any(value is None for value in values),
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ from_suffix = database.db_engine_spec.select_without_from_suffix
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ from_suffix,
+ )
+ if not probe_sql_is_evaluable(
+ sql, database.backend, len(distinct), from_suffix
+ ):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _execution_identity(database: Database) -> str | None:
+ """
+ Who the warehouse will run the probe as, when that can vary by caller.
+
+ `_probe_cache_key` keys on the `Database` record, which is the *connection*
+ -- not the identity it is opened under. Two hooks make that identity a
+ function of the Superset user instead:
+
+ * ``impersonate_user`` on the database, which hands the effective username
+ to `db_engine_spec.impersonate_user`;
+ * ``DB_CONNECTION_MUTATOR``, which receives the effective username and may
+ return an entirely different account's URL.
+
+ Under either one, a cached probe result computed under user A's grants was
+ served to user B, and the preview echoed it back in ``emitted_predicate``.
+ A transform wrapping a read-capable function the denylist does not name --
+ Oracle's ``DBMS_XMLGEN.GETXML`` is the worked example -- then leaks across
+ users who were never allowed the same rows.
+
+ Returns ``None`` when neither hook is configured, which is the common case
+ and deliberately leaves the key as it was: the cache exists to keep a
+ synchronous warehouse round trip off the chart-query path, and keying every
+ deployment on the username would cost every deployment the hit rate to fix
+ the two that need it.
+
+ The *Superset* username rather than the resolved warehouse account, because
+ it is the input both hooks branch on, and reading it needs no URL parse and
+ puts no credential in the key.
+ """
+ if not (database.impersonate_user or app.config["DB_CONNECTION_MUTATOR"]):
+ return None
+ return get_username()
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _mirror_verdict_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str:
+ """
+ `_probe_cache_key` without the values.
+
+ Whether a transform can be evaluated at all is a property of the transform
+ and the connection, not of the filter that happened to be probing it, so
+ one chart's answer settles the question for the next one.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ # Whether a transform *can* be evaluated is a property of the
+ # transform and the connection -- but under impersonation the
+ # connection is per-user, and a function one account may call can
+ # be refused to another. See `_execution_identity`.
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_verdict:{digest}"
+
+
+def record_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ *,
+ mirrors: bool,
+) -> None:
+ """
+ Remember whether this transform produced a mirror, for the UI to read.
+
+ Advisory only. Nothing in the query path consults it: a probe that failed
+ once is retried on the next chart exactly as it is today, because declining
+ to prune for a whole cache timeout over one transient engine blip is the
+ trade `evaluate_transform` deliberately refuses -- see the comment where it
+ declines to cache a failure.
+
+ What this is for is the *claim*. `is_transform_active` parses the transform
+ and no more, so a transform the database rejects -- a misspelled function
+ is the common case -- is "active", and the editor's banner and Explore's
+ pruning glyph promise a speed-up that never happens. A promise is exactly
+ the thing that may be withheld on one bad answer and restored on a good
+ one, which is why this is a separate entry from the probe's own results
+ rather than a relaxation of that rule.
+
+ Written by `_run_probe`, so the preview endpoint -- which shares the
+ evaluator -- settles the question before the owner has even saved.
+ """
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(
+ _mirror_verdict_cache_key(database, catalog, schema, transform),
+ mirrors,
+ timeout=timeout,
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform verdict", exc_info=True)
+
+
+def known_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> bool | None:
+ """
+ The last verdict `record_mirror_verdict` stored, or `None` if there is none.
+
+ `None` is the honest answer on a cold cache and is deliberately not `False`:
+ reporting a working mapping as broken until something probes it would
+ trade one wrong claim for another. The alternative -- probing from the
+ read side -- would put a warehouse round trip on every Explore and
+ dashboard load, and a failing transform is not cached at all, so it would
+ be a round trip every single time.
+ """
+ try:
+ verdict = cache_manager.cache.get(
+ _mirror_verdict_cache_key(database, catalog, schema, transform)
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return verdict if isinstance(verdict, bool) else None
+
+
+def _compile_literal(element: Any, dialect: Dialect | None) -> str:
+ """
+ Compile with inline literals, undoing the paramstyle's percent doubling.
+
+ Both ``TextClause`` and literal compilation run the dialect's
+ ``post_process_text``, which doubles every ``%`` whenever the identifier
+ preparer asks it to -- true for MySQL and Postgres and for every spec
+ inheriting their paramstyle. That doubling exists so a later DBAPI
+ parameter-interpolation pass can undo it, and the probe has no such pass:
+ it executes with no bound parameters at all. So a transform of
+ ``date_format(:value, '%Y%m%d')`` reaches the warehouse asking for the
+ literal string ``%%Y%%m%%d``, the probe returns that instead of a date, and
+ the mirrored predicate drops every row the filter keeps.
+
+ The same normalization ``Database.compile_sqla_query`` applies for the same
+ reason. ``_double_percents`` is private and not guaranteed on a third-party
+ dialect, hence the ``getattr`` default.
+ """
+ compiled = str(
+ element.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
+ )
+ if dialect is not None and getattr(
+ dialect.identifier_preparer, "_double_percents", False
+ ):
+ compiled = compiled.replace("%%", "%")
+ return compiled
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be *asked* to stand in for itself, and the transform
+ cannot carry Jinja or call a non-deterministic function. Tier 2
+ (``blocking=False``) is everything that merely leaves the mapping inactive
+ -- including a self-mapping nobody asked for, where the partition column
+ merely happens to be the default datetime column.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column == partition_column:
+ # Asked for explicitly, so report it as the mistake it is.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+ elif not partition_mapped_column and main_dttm_col == partition_column:
+ # Resolved onto itself only because the default datetime column happens
+ # to be the partition column -- a state metadata sync could produce
+ # without anyone asking for it. The mapping is inert either way, since
+ # `resolve_partition_mapping` bails out on it, so this reports and lets
+ # the write through: blocking here means a dataset already in the state
+ # can never be saved again, not even to change its description, and
+ # there is no field whose edit would clear the error first.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "%(name)s is both the partition column and the default "
+ "datetime column, so the mapping points at itself and "
+ "stays inactive. Set a mapped column override, or change "
+ "the default datetime column.",
+ name=partition_column,
+ ),
+ blocking=False,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def drop_unmapped_value_transforms(
+ columns: list[dict[str, Any]] | None,
+ *,
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ names_by_id: dict[int, str] | None = None,
+) -> list[str]:
+ """
+ Null the value transform on every *incoming* column the mapping cannot mirror.
+
+ The write-side twin of `DatasetDAO.clear_unmapped_partition_transforms`,
+ which answers for the model. A mapping has exactly one mirrored column, so
+ at most one column may carry a transform. One parked on any other column is
+ invisible -- no row but the mapped one renders a transform -- and yet it is
+ stored, and it goes live the moment the mapped column resolves back to it.
+ Clearing an override is enough to do that: a null
+ ``partition_mapped_column`` means "follow ``main_dttm_col``".
+
+ Ungated on the feature flag, unlike its model-level twin, and the difference
+ is what each one discards. That one drops stored configuration, so with the
+ flag off it would be pure loss. This one drops only a value the request in
+ hand is asking to write where the invariant says none may live -- and the
+ flag-off window is precisely when such a value gets parked for later, since
+ the editor hides these fields and the model-level pass declines to run.
+
+ Three writers reach the columns with no effective model-level pass between
+ them, which is why this exists at all: the deprecated
+ ``POST /datasource/save/``, which writes straight through
+ `update_from_object` and so never had one; and a
+ ``PUT /api/v1/dataset/<pk>`` or a dataset import made while the flag is
+ off, where the pass runs on both sides of the write and declines on both.
+
+ Mutates the payload in place, because every caller hands its own request
+ dict straight on to the code that writes it. Returns the names it cleared,
+ so the caller can say so in a log: this is a silent correction to a payload
+ whose author may have meant it.
+
+ A column whose payload mentions neither field is left alone. "Incoming" is
+ the whole scope -- a transform already in storage on a column this request
+ says nothing about is the model-level pass's business, under its own flag.
+
+ The mapped column resolves the way every other reader resolves it,
+ ``partition_mapped_column or main_dttm_col``, and resolves to nothing
+ without a partition column -- in which case no column may hold a transform
+ either.
+
+ :param names_by_id: how to read the name off a payload entry that gives
+ only an ``id``. `DatasetDAO._upsert_columns` identifies an existing
+ column by its primary key and lets ``column_name`` be omitted -- the
+ column keeps the name it has -- so without this an ordinary PUT looked
+ like a payload of nameless columns, none of which matched the mapped
+ one, and every transform in it was dropped. Callers whose writer keys
+ on the name instead (`update_from_object`, the importer) pass nothing.
+ An entry this cannot name is left alone rather than guessed at.
+ """
+ mapped_column = (
+ (partition_mapped_column or main_dttm_col) if partition_column else None
+ )
+ cleared: list[str] = []
+ for column in columns or []:
+ name = column.get("column_name")
+ if name is None and names_by_id is not None:
+ column_id = column.get("id")
+ if column_id is not None:
+ name = names_by_id.get(column_id)
+ if name is None or name == mapped_column:
+ continue
+ if column.get("partition_value_transform") or column.get(
+ "partition_transform_is_monotonic"
+ ):
+ column["partition_value_transform"] = None
+ column["partition_transform_is_monotonic"] = False
+ cleared.append(name)
+ return cleared
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if contains_executable_comment(transform):
+ # Blocking, and checked on raw text next to the Jinja gate because no
+ # parse reports it: sqlglot reads `/*!50000 ... */` as comment data
+ # while MySQL and MariaDB execute it, so every shape gate downstream
+ # inspects a statement the engine will not run. See
+ # `EXECUTABLE_COMMENT_RE`.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform cannot contain a MySQL executable "
+ "comment (/*! ... */ or /*M! ... */). Those are comments "
+ "to every validator and statement text to the database, "
+ "so what would run is not what was checked."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_bare_expression(transform, engine):
+ # Blocking, and deliberately placed in `validate_transform` rather than
+ # only at the probe: one issue here closes the PUT, the importer, the
+ # query-time gate through `is_transform_active`, the Explore indicator's
+ # active verdict and the preview endpoint, all of which already consult
+ # this function.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform must be a single SQL expression. It "
+ "cannot carry a FROM, WHERE, GROUP BY or any other clause, "
+ "and it cannot contain a sub-query."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not contains_value_placeholder(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform must contain the :value placeholder, "
+ "which stands for the filter value being mirrored."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not placeholder_is_executable(transform, engine):
+ # Blocking, and for the same reason the shape gate above is: this is
+ # the function the PUT, the importer, `is_transform_active`, the
+ # Explore indicator and the preview all consult, so one issue here
+ # closes every door at once. A placeholder inside a string literal is
+ # a sub-query the engine will run once a filter value closes the quote;
+ # one inside a comment silently eats the probe's own alias.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The :value placeholder must appear where the engine will "
+ "evaluate it. It cannot sit inside a string literal or a "
+ "comment."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if functions := find_non_deterministic_functions(transform, engine):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform calls %(functions)s, whose result "
+ "depends on when and where it runs. The transform is "
+ "evaluated in a separate session and the result is cached, "
+ "so the emitted predicate would freeze a snapshot of that "
+ "moment.",
+ functions=", ".join(sorted(functions)),
+ ),
+ blocking=True,
+ )
+ ]
+
+ return []
+
+
+@lru_cache(maxsize=LRU_CACHE_MAX_SIZE)
+def is_transform_active(transform: str | None, engine: str) -> bool:
+ """
+ Whether Superset will mirror filters through this transform.
+
+ `validate_transform` with the messages discarded, so the Explore indicator
+ cannot advertise a mapping the save path recorded as inactive. Anything
+ cheaper here would be a second, weaker statement of the same rule, free to
+ drift from the one the save path applies.
+
+ Blocking issues count too. Jinja and non-deterministic transforms are
+ rejected on PUT, but `CreateDatasetCommand` and import do not validate the
+ mapping, so one can still reach the database -- and it would never mirror a
+ filter either.
+
+ Memoized because `partition_filter_mapping_summary` is serialized on every
+ Explore and dashboard load and this parses the transform. The key is
+ everything the answer depends on: `validate_transform` reads no session, no
+ locale and no config beyond `SQL_MAX_PARSE_LENGTH`, which bounds the parser
+ rather than changing a verdict within that bound.
+ """
+ return not validate_transform(transform, engine)
+
+
+def preview_partition_mapping( # pylint: disable=too-many-return-statements
+ datasource: SqlaTable,
+ *,
+ mapped_column: str,
+ value_transform: str | None,
+ sample_values: list[str],
+ operator: FilterOperator = FilterOperator.EQUALS,
+ is_monotonic: bool = False,
+ partition_column: str | None = None,
+) -> dict[str, Any]:
+ """
+ Evaluate a candidate mapping and describe the predicate it would emit.
+
+ Shares the evaluator -- and therefore the probe cache -- with the query
+ path, so preview and runtime cannot drift and a previewed transform warms
+ the chart path for free. The predicate itself comes from
+ `build_mirrored_predicates`, the same builder the query path uses, so
+ operator shapes cannot drift either: what the panel shows is what a chart
+ would emit.
+
+ Validation runs first and the engine second: a half-typed transform is by
+ definition unparseable, so most of what a text input produces costs zero
+ queries.
+
+ Every part of the mapping is taken from the request rather than the stored
+ dataset. The editor previews while the owner is still editing -- a mapping
+ that has to be saved before it can be checked is not a preview.
+ """
+ partition_column = partition_column or datasource.partition_column
+ if not partition_column:
+ return {
+ "valid": False,
+ "reason": "unconfigured",
+ "error": _("No partition column is set."),
+ }
+
+ columns_by_name = {str(column.column_name): column for column in datasource.columns}
+ if mapped_column not in columns_by_name:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _("%(name)s is not a column on this dataset.", name=mapped_column),
+ }
+
+ # The bail-out `resolve_partition_mapping` makes at query time, and that
+ # `partition_filter_mapping_summary` repeats for the Explore indicator.
+ # Without it here, preview reports a valid emitted predicate for a mapping
+ # no chart will ever mirror -- the one answer a preview panel must not give.
+ if has_active_advanced_data_type(columns_by_name[mapped_column]):
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _(
+ "%(name)s has an advanced data type, so its filters are "
+ "translated into their own predicate shape and cannot be "
+ "mirrored onto the partition column.",
+ name=mapped_column,
+ ),
+ }
+
+ engine = datasource.database.backend
+ for issue in validate_partition_mapping(
+ column_names=set(columns_by_name),
+ partition_column=str(partition_column),
+ partition_mapped_column=mapped_column,
+ main_dttm_col=datasource.main_dttm_col,
+ transform=value_transform,
+ engine=engine,
+ ):
+ return {
+ "valid": False,
+ # The parse failure is the one an owner sees constantly, and it is
+ # the only one the mockup gives its own headline to.
+ "reason": (
+ "parse"
+ if issue.field == "partition_value_transform"
+ and not is_parseable(value_transform, engine)
+ else "validation"
+ ),
+ "error": str(issue.message),
+ }
+
+ # The policy every other stored expression goes through. The save path
+ # applies it in `UpdateDatasetCommand._validate_partition_mapping`, but
+ # preview evaluates a candidate transform that has not been saved, so
+ # without this the gate had a door around it. See
+ # `stored_expression_error` for what is being kept out and why.
+ if reason := stored_expression_error(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ cast(str, value_transform),
+ ):
+ return {"valid": False, "reason": "validation", "error": reason}
+
+ mapping = PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=mapped_column,
+ value_transform=cast(str, value_transform),
+ is_monotonic=is_monotonic,
+ equality_is_safe=equality_mirrors_safely(
+ columns_by_name[mapped_column], datasource.database.db_engine_spec
+ ),
+ )
+ sample_input = _render_sample_input(
+ datasource, mapped_column, operator, sample_values
+ )
+
+ if operator not in PREVIEWABLE_OPERATORS:
+ # Checked before `mirrors`, which lets `TEMPORAL_RANGE` through when the
+ # transform is declared monotonic -- and the single sample value would
+ # then reach `handle_comparison_filter`, which has no case for a range
+ # and raises. The request schema rejects it too; this keeps the function
+ # honest for any other caller.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is mirrored as a pair of bounds, which "
+ "a preview of a single value cannot describe.",
+ operator=operator.value,
+ ),
+ }
+
+ if not mapping.mirrors(operator):
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is only mirrored when the transform "
+ "preserves ordering, which this one is not declared to do.",
+ operator=operator.value,
+ ),
+ }
+
+ return _preview_probe(
+ datasource,
+ mapping,
+ columns_by_name[mapped_column],
+ operator,
+ sample_values,
+ sample_input,
+ )
+
+
+def _preview_probe(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ mapped_col: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+ sample_input: str,
+) -> dict[str, Any]:
+ """
+ The half of a preview that needs the warehouse.
+
+ Split out from `preview_partition_mapping` so that the gates which answer
+ from the stored mapping alone stay readable as the single run of guard
+ clauses they are. Everything here has either run a query or decided not to.
+ """
+ value = datasource.mirror_probe_request(
+ operator,
+ _probe_input(datasource, mapped_col, operator, sample_values),
+ mapped_col,
+ )
+ if value is UNMIRRORABLE:
+ # The same step the chart path applies, so the preview cannot promise a
+ # mirror the query declines. Its own reason: the transform is fine and
+ # the engine evaluates it, the filter just carries more of the value
+ # than the engine compares on this column -- which is the column's type
+ # talking, not a broken expression.
+ return {
+ "valid": False,
+ "reason": "resolution",
+ "sample_input": sample_input,
+ "error": _(
+ "This engine compares less of a %(operator)s value on "
+ "%(column)s than the filter carries, so there is no mirror a "
+ "predicate on the partition column could stand in for. Map a "
+ "column the engine compares in full to mirror this operator.",
+ operator=operator.value,
+ column=mapped_col.column_name,
+ ),
+ }
+ errors: list[str] = []
+ type_errors: list[str] = []
+ predicates = build_mirrored_predicates(
+ datasource,
+ mapping,
+ [(operator, value)],
+ errors=errors,
+ type_errors=type_errors,
+ )
+ if type_errors:
+ # Its own reason, because "the database would not evaluate this" and
+ # "it evaluated and answered with the wrong kind of thing" are
+ # different problems with different fixes, and the owner is the only
+ # one who can tell which transform they meant to write.
+ return {
+ "valid": False,
+ "reason": "type",
+ "sample_input": sample_input,
+ "error": type_errors[0],
+ }
+ if not predicates:
+ return {
+ "valid": False,
+ "reason": "engine",
+ "sample_input": sample_input,
+ "error": (
+ _(
+ "The transform could not be evaluated against the "
+ "database: %(reason)s",
+ reason=errors[0],
+ )
+ if errors
+ else _("The transform could not be evaluated against the database.")
+ ),
+ }
+
+ return {
+ "valid": True,
+ "sample_input": sample_input,
+ "emitted_predicate": _render_predicate(datasource, predicates[0]),
+ }
+
+
+def _probe_input(
+ datasource: SqlaTable,
+ column: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+) -> Any:
+ """
+ The sample values as the query path would bind them.
+
+ The request carries samples as strings, and the probe is keyed on exactly
+ what it is handed, so passing them through raw asks the engine a different
+ question from the one a chart asks. A sample of ``2025`` on a numeric
+ column has to arrive as the integer the chart compares: under a transform
+ of ``typeof(:value)`` the raw string previewed ``'text'`` where the chart
+ emitted ``'integer'``. And because `_probe_cache_key` keys on each value's
+ ``repr``, the two also missed each other's cache entirely -- so the "a
+ previewed transform warms the chart path for free" claim in
+ `preview_partition_mapping`'s docstring did not actually hold.
+
+ Coerced by `filter_values_handler`, the same function the query path uses,
+ rather than by a second implementation of the same rules. Everything the
+ query path then does to the coerced value -- rendering an expression as a
+ literal, widening a bound, declining a comparison the engine resolves too
+ coarsely -- is `ExploreMixin.mirror_probe_request`'s, and the caller hands
+ this result straight to it.
+
+ Ranges are not previewable (see `PREVIEWABLE_OPERATORS`), so the bound
+ conversion `_collect_partition_mirror_range` applies -- a ``datetime`` into
+ the column's stored representation -- has no counterpart here.
+
+ Always answers with a value: nothing here declines. `UNMIRRORABLE` is
+ `mirror_probe_request`'s to return, and the caller hands this straight to it.
+ """
+ is_list = operator == FilterOperator.IN
+ column_spec = datasource.db_engine_spec.get_column_spec(native_type=column.type)
+ handled = datasource.filter_values_handler(
+ # `list[str]` is not a `list[FilterValue]` to mypy, invariantly, even
+ # though every `str` is a `FilterValue`.
+ values=cast(FilterValues, sample_values if is_list else sample_values[0]),
+ operator=operator,
+ target_generic_type=(
+ column_spec.generic_type if column_spec else utils.GenericDataType.STRING
+ ),
+ target_native_type=column.type,
+ is_list_target=is_list,
+ db_engine_spec=datasource.db_engine_spec,
+ db_extra=datasource.db_extra,
+ )
+ # No `ColumnElement` conversion here: an epoch-milliseconds sample comes back
+ # as engine SQL rather than a value, and `mirror_probe_request` renders it --
+ # the same step, on the same values, as for a chart filter.
+ return handled
Review Comment:
Addressed on Hugh's behalf in 1fa334d289: `_probe_input` now sends `=`/`IN` samples on a MULTI_VALUE column through `_array_mirror_probe_value`, the same as the chart path, so the preview probes `array(1, 2)` rather than the text. Range operators keep the handled value on both paths. Added a ClickHouse preview test that checks the probed literal.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #43870:
URL: https://github.com/apache/superset/pull/43870#issuecomment-6001666265
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers an incremental AI Review.
- `/review full` - Manually triggers a full AI Review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #43870:
URL: https://github.com/apache/superset/pull/43870#issuecomment-6004740136
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers an incremental AI Review.
- `/review full` - Manually triggers a full AI Review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4263831906
##########
superset/mcp_service/dataset/schemas.py:
##########
@@ -207,6 +207,16 @@ class DatasetInfo(BaseModel):
url: str | None = Field(None, description="Explore view URL for this dataset")
sql: str | None = Field(None, description="SQL for virtual datasets")
main_dttm_col: str | None = Field(None, description="Main datetime column")
+ partition_column: str | None = Field(
Review Comment:
These two fields grow the dataset tools' output schemas by 337 B, so `test_native_inventory_report_matches_registered_tools` fails `unit-tests (current)`. Rerun it with `SUPERSET_MCP_UPDATE_TOOL_INVENTORY=1` and commit `native_tool_inventory.json` (no suggestion: that file is outside the diff).
##########
superset/views/datasource/views.py:
##########
@@ -293,6 +425,72 @@ def save(self) -> FlaskResponse:
),
status=409,
)
+ # The mapping's one-transform invariant, against the columns this
+ # request is about to write. `update_from_object` sets every field in
+ # `update_from_object_fields` straight onto the column, so nothing
+ # between here and storage would notice a transform parked on a column
+ # the mapping does not mirror -- invisible in the editor, since no row
+ # but the mapped one renders a transform, and live the moment the mapped
+ # column resolves back to it. `DatasetDAO.update` runs a model-level
+ # pass for this; this endpoint bypasses that along with the rest of
+ # `UpdateDatasetCommand`.
+ #
+ # Corrected rather than refused, unlike the gates below. Those are about
+ # a value that may not be stored anywhere; this is about a value in the
+ # wrong place, and the payload a GET-then-POST client sends back carries
+ # whatever a previous writer left there -- so a 422 would punish the
+ # client that is merely echoing the state it was given.
+ #
+ # Which is also why it runs *first*. A parked transform that is not a
+ # storable expression would otherwise fail the gate below and 422 every
+ # save, leaving the dataset uneditable over a value nobody asked to
+ # keep; dropped here, there is nothing left for that gate to refuse.
+ # What it still guards is the transform this request actually stores,
+ # the one on the mapped column.
+ #
+ # Read from the payload alone, with no fallback to the model: every
+ # field here rides in on `update_from_object`, which writes
+ # `obj.get(attr)` for each one, so what this request says *is* what the
+ # mapping will be.
+ if cleared := drop_unmapped_value_transforms(
+ datasource_dict.get("columns"),
+ partition_column=datasource_dict.get("partition_column"),
+ partition_mapped_column=datasource_dict.get("partition_mapped_column"),
+ main_dttm_col=datasource_dict.get("main_dttm_col"),
+ # So an unchanged echo of stored configuration survives: this
+ # endpoint's own client does GET-then-POST, which is exactly the
+ # shape that looked like a value being parked.
+ stored_by_name={
+ column.column_name: (
+ column.partition_value_transform,
+ bool(column.partition_transform_is_monotonic),
+ )
+ for column in getattr(orm_datasource, "columns", None) or []
+ },
Review Comment:
With the flag on, this endpoint has no model-level pass, so the echo exemption keeps the transform on the old mapped column; REST PUT's post-pass clears it. Clearing the override later through this endpoint then re-arms it.
```suggestion
stored_by_name=None
if is_feature_enabled("PARTITION_FILTER_MAPPING")
else {
column.column_name: (
column.partition_value_transform,
bool(column.partition_transform_is_monotonic),
)
for column in getattr(orm_datasource, "columns", None) or []
},
```
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,3128 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: The opening and closing delimiters of each kind of Jinja block. The probe
+#: would render these in a different context at a different time from the chart
+#: query, so a transform holding one is rejected at save time.
+JINJA_BLOCK_DELIMITERS = (("{{", "}}"), ("{%", "%}"), ("{#", "#}"))
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: A PostgreSQL Unicode-escaped identifier, ``U&"..."``.
+#:
+#: The second construct that breaks the premise above, and in the same way:
+#: ``U&"\\0071uery_to_xml"(...)`` parses as an anonymous function whose name is
+#: the *literal* ``\\0071uery_to_xml``, so the function denylist is matching a
+#: name the engine never sees -- PostgreSQL decodes the escape and runs
+#: ``query_to_xml``, handing a dataset owner rows from outside their RLS scope
+#: through the preview's ``emitted_predicate``.
+#:
+#: Normalizing the escapes and re-checking would be the other repair, and is
+#: worse: it means reimplementing one engine's identifier decoding well enough
+#: to be a security boundary. Refusing the construct is exact, and costs
+#: nothing real -- a transform is a scalar function of ``:value``, and there is
+#: no reason to name a function or column through an escape sequence.
+#:
+#: Refused on every engine, like the executable comment, so a transform stored
+#: on SQLite cannot detonate when the dataset is re-pointed at PostgreSQL. The
+#: ``&`` may be separated from the ``U`` by nothing at all, but whitespace or a
+#: comment between the prefix and the string is not accepted by PostgreSQL
+#: either, so the strict form is the whole surface.
+#:
+#: Matched in raw text, so the prefix is refused inside a string literal too.
+#: That is the same trade the executable comment makes and has the same
+#: justification: a gate whose contract is to fire *before* the parse cannot
+#: ask the parse whether the text was quoted. ``concat(:value, 'u&"x"')`` is
+#: refused, which costs an owner nothing anyone writes.
+UNICODE_ESCAPED_IDENTIFIER_RE = re.compile(r'\bU&"', re.IGNORECASE)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate: a transform such as
+#: ``datediff(day, :value, LOCALTIMESTAMP)`` for a relative partition key is
+#: evaluated once and then keeps emitting yesterday's answer, so the chart
+#: silently drops rows after midnight.
+#:
+#: Matched by SQL function name, so every engine's spelling of "now" has to be
+#: named -- the ANSI four were not enough. Listed rather than delegated to the
+#: engine specs because the risk is the same everywhere and a spec that had not
+#: got round to declaring its own would fail open; a name no engine has is
+#: inert, so over-listing costs nothing.
+NON_DETERMINISTIC_FUNCTIONS = {
+ # ANSI, and the engines that spell it this way.
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "LOCALTIME",
+ "LOCALTIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+ # PostgreSQL. `now()` is statement-stable; these two are not even that.
+ "CLOCK_TIMESTAMP",
+ "STATEMENT_TIMESTAMP",
+ "TIMEOFDAY",
+ # MySQL and MariaDB.
+ "CURDATE",
+ "CURTIME",
+ "SYSDATE",
+ "UTC_DATE",
+ "UTC_TIME",
+ "UTC_TIMESTAMP",
+ "UUID_SHORT",
+ # Oracle.
+ "SYSTIMESTAMP",
+ "SYS_GUID",
+ # SQL Server.
+ "GETDATE",
+ "GETUTCDATE",
+ "SYSDATETIME",
+ "SYSUTCDATETIME",
+ "SYSDATETIMEOFFSET",
+ "NEWID",
+ # BigQuery.
+ "CURRENT_DATETIME",
+ "GENERATE_UUID",
+ # Snowflake.
+ "RANDSTR",
+ "UUID_STRING",
+ # ClickHouse.
+ "NOW64",
+ "RANDCANONICAL",
+ "GENERATEUUIDV4",
+ # H2 and Derby, which the test fixtures use.
+ "RANDOM_UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+class Unmirrorable:
+ """
+ A filter no mirror can stand in for, and why.
+
+ Returned by `ExploreMixin.mirror_probe_request` for a value the engine
+ compares more coarsely than the filter carries, one it cannot render as a
+ literal, one in a time frame the transform would discard, or an ``IN`` list
+ with a member of any of those kinds. An object rather than `None`, because
+ `None` is a filter value in its own right.
+
+ The reason rides along because the preview has to explain the decline to
+ the owner, and the two declines want different advice: "the engine compares
+ less of this value than you typed, so map a column it compares in full" is
+ sound guidance for a `DATE` column and actively misleading for an
+ offset-bearing bound on a `TIMESTAMP` one, which already is such a column.
+ Carried rather than re-derived so the preview's explanation cannot come
+ apart from the chart path's decision.
+
+ Lives here rather than beside that method so the preview can read it too:
+ `superset.models.helpers` imports this module, so these can only cross the
+ boundary in this direction. Both callers recognise the same instances -- a
+ preview that answered "valid" for a request the chart path declines is the
+ drift this is here to prevent.
+ """
+
+ __slots__ = ("reason",)
+
+ def __init__(self, reason: str) -> None:
+ self.reason = reason
+
+ def __repr__(self) -> str:
+ return f"<Unmirrorable {self.reason}>"
+
+
+#: The ordinary decline: whatever the mirror cannot be built from, with the
+#: engine's own comparison resolution as the reason an owner can act on.
+UNMIRRORABLE = Unmirrorable("resolution")
+
+#: A value carrying a UTC offset, declined whatever the column's resolution.
+#: A transform such as ``CAST(:value AS TIMESTAMP)`` drops the offset, so even
+#: an engine that compares the whole instant would be probed in the wrong
+#: frame -- which is not something mapping a different column fixes.
+UNMIRRORABLE_OFFSET = Unmirrorable("offset")
+
+
+def is_unmirrorable(value: Any) -> bool:
+ """Whether `mirror_probe_request` declined this request."""
+ return isinstance(value, Unmirrorable)
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+#: Declared types whose comparison ignores trailing blanks.
+#:
+#: The fixed-width character types, which the SQL standard has compare as
+#: though both sides were padded to the same length -- so ``'US'`` and
+#: ``'US '`` are equal in a ``CHARACTER(3)``, while ``lower()`` of the two is
+#: not. Spelled out rather than matched by prefix because the variable-width
+#: names start with the same letters: ``VARCHAR`` and ``CHARACTER VARYING``
+#: compare the blanks and must not land here.
+PADDED_CHARACTER_TYPES = frozenset(
+ {
+ "CHAR",
+ "NCHAR",
+ # PostgreSQL's own name for ``CHARACTER``, which is what reflection
+ # reports for a ``CHAR(n)`` column there.
+ "BPCHAR",
+ "CHARACTER",
+ "NATIONAL CHAR",
+ "NATIONAL CHARACTER",
+ }
+)
+
+
+def _is_padded_character_type(column: TableColumn) -> bool:
+ """
+ Whether ``column``'s declared type compares without its trailing blanks.
+
+ Read off the declared type rather than the engine spec's resolved one: the
+ specs map ``CHAR`` and ``VARCHAR`` onto the same `sqlalchemy.String`, so
+ the distinction this needs is gone by then. The length suffix is dropped
+ and the name matched against `PADDED_CHARACTER_TYPES`, so an unfamiliar
+ spelling answers ``False`` and the engine-level flag decides as before --
+ this gate adds a decline rather than lifting one. A column with no
+ declared type has nothing to read, and answers the same way.
+ """
+ if not isinstance(column.type, str):
+ return False
+ native = re.sub(r"\s+", " ", column.type.strip().upper())
+ return native.split("(")[0].strip() in PADDED_CHARACTER_TYPES
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ Padding is asked about per column, because it is a property of the *type*
+ rather than of the engine. ``binary_string_comparison`` speaks for an
+ engine's default text comparison, and on PostgreSQL -- which declares it
+ -- a ``CHAR(2)`` still matches a filter for ``'US '`` against a stored
+ ``'US'``, because the standard says a padded character type compares
+ without its trailing blanks. The mirror ``region_key = lower('US ')`` then
+ excludes the row. So a fixed-width character type declines whatever the
+ engine says, and an engine that ignores trailing blanks on its *variable*
+ types says so by not declaring the flag at all (see `RedshiftEngineSpec`).
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ # Ahead of the generic-type question, which a padded type can lose: the
+ # specs map ``CHARACTER`` onto no generic type at all on some engines, and
+ # a fixed-width character type is a string whether or not Superset can say
+ # so from the name.
+ if _is_padded_character_type(column):
+ return False
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_unicode_escaped_identifier(transform: str | None) -> bool:
+ """Whether the transform names something through a ``U&"..."`` escape.
+
+ See `UNICODE_ESCAPED_IDENTIFIER_RE`. Answered on raw text for the same
+ reason as the comment above: the parse reports a name the engine does not
+ use, which is exactly what makes the denylist blind to it.
+ """
+ return (
+ bool(transform)
+ and UNICODE_ESCAPED_IDENTIFIER_RE.search(transform or "") is not None
+ )
+
+
+#: Sequence pseudo-columns, which advance a sequence when they are *read*.
+#:
+#: ``orders_seq.NEXTVAL`` parses as a qualified column reference, not a
+#: function call, so neither `SQLStatement.is_mutating` -- which walks function
+#: names -- nor the function denylist can see it. The probe would then run
+#: ``SELECT orders_seq.NEXTVAL + 1 FROM DUAL`` and advance the sequence, again
+#: on every cache expiry, for a dataset editor holding neither SQL Lab nor a
+#: DML grant. Reading one is a write however the parser classifies it.
+#:
+#: The function spelling (``nextval('s')`` on PostgreSQL) is a different shape
+#: and is caught as a function; this is only about the suffix form.
+SEQUENCE_PSEUDO_COLUMNS = frozenset({"nextval", "currval"})
+
+#: The same thing written as a call.
+#:
+#: Only the suffix form parses as a column; `nextval('s')` on PostgreSQL and
+#: DuckDB, `NEXTVAL(s)`/`SETVAL(s, 1)` on MySQL and MariaDB, and SQL Server's
+#: `NEXT VALUE FOR s` all parse as functions. `SQLStatement.is_mutating` walks
+#: function names on PostgreSQL alone -- deliberately, since the same names are
+#: read-only elsewhere -- so every other engine let these through.
+#:
+#: Matched on the name whatever the engine, because advancing a sequence is a
+#: write wherever it happens and a transform has no reason to call one.
+SEQUENCE_FUNCTIONS = frozenset(
+ {"nextval", "setval", "next_value_for", "nextvalfor", "prevval", "lastval"}
+)
+
+
+def references_sequence(statement: SQLStatement) -> bool:
+ """Whether the statement reads or advances a sequence.
+
+ Both spellings: the pseudo-column suffix, which parses as a column (see
+ `SEQUENCE_PSEUDO_COLUMNS`), and the call, which parses as a function (see
+ `SEQUENCE_FUNCTIONS`).
+
+ Answered on the parse rather than on raw text, because position is what
+ makes it the construct: a column or alias merely *called* ``nextval`` is
+ an ordinary column, and a string literal holding the word is text.
+ """
+ return bool(
+ statement.get_column_names() & SEQUENCE_PSEUDO_COLUMNS
+ or statement.get_disallowed_functions(set(SEQUENCE_FUNCTIONS))
+ )
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """
+ Whether the transform contains a balanced Jinja block.
+
+ A block is an opening delimiter followed, anywhere later, by its closing
+ one -- the same thing ``{{.*?}}`` and its two siblings match under
+ ``re.DOTALL``. Scanned with `str.find` rather than that pattern, because a
+ lazy match retried from every opening delimiter is quadratic in a run of
+ them, and this runs on stored transforms with no length bound of its own:
+ `is_transform_active` reads whatever the column holds. The earliest opening
+ delimiter is the only one worth trying, since any closing delimiter after a
+ later one is also after it.
+ """
+ if not transform:
+ return False
+ for opening, closing in JINJA_BLOCK_DELIMITERS:
+ start = transform.find(opening)
+ if start != -1 and transform.find(closing, start + len(opening)) != -1:
+ return True
+ return False
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
Review Comment:
MySQL also accepts `UTC_DATE`, `UTC_TIME` and `UTC_TIMESTAMP` without parentheses, which parse as columns, so `datediff(UTC_DATE, :value)` passes this gate.
```suggestion
found = {
name
for name in NON_DETERMINISTIC_FUNCTIONS
if statement.check_functions_present({name})
}
# MySQL also accepts these without parentheses, which parses as a column.
bare = {"utc_date", "utc_time", "utc_timestamp"} & statement.get_column_names()
found |= {name.upper() for name in bare}
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "hughhhh (via GitHub)" <gi...@apache.org>.
hughhhh commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4319666839
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,1613 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import re
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: Every entry point enforces it -- the typed column field, the import schema
+#: and the preview request -- because `is_transform_active` parses the stored
+#: value on each Explore load, and an unbounded string would make that parse
+#: the expensive part of rendering a chart.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+ """
+ return VALUE_PLACEHOLDER_RE.sub(_PARSE_STANDIN, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(transform: str, engine: str) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error(
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ selections = []
+ for index, value in enumerate(values):
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ selections.append(f"{_compile_literal(clause, dialect)} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ database.db_engine_spec.select_without_from_suffix,
+ )
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _compile_literal(element: Any, dialect: Dialect | None) -> str:
+ """
+ Compile with inline literals, undoing the paramstyle's percent doubling.
+
+ Both ``TextClause`` and literal compilation run the dialect's
+ ``post_process_text``, which doubles every ``%`` whenever the identifier
+ preparer asks it to -- true for MySQL and Postgres and for every spec
+ inheriting their paramstyle. That doubling exists so a later DBAPI
+ parameter-interpolation pass can undo it, and the probe has no such pass:
+ it executes with no bound parameters at all. So a transform of
+ ``date_format(:value, '%Y%m%d')`` reaches the warehouse asking for the
+ literal string ``%%Y%%m%%d``, the probe returns that instead of a date, and
+ the mirrored predicate drops every row the filter keeps.
+
+ The same normalization ``Database.compile_sqla_query`` applies for the same
+ reason. ``_double_percents`` is private and not guaranteed on a third-party
+ dialect, hence the ``getattr`` default.
+ """
+ compiled = str(
+ element.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
+ )
+ if dialect is not None and getattr(
+ dialect.identifier_preparer, "_double_percents", False
+ ):
+ compiled = compiled.replace("%%", "%")
+ return compiled
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be *asked* to stand in for itself, and the transform
+ cannot carry Jinja or call a non-deterministic function. Tier 2
+ (``blocking=False``) is everything that merely leaves the mapping inactive
+ -- including a self-mapping nobody asked for, where the partition column
+ merely happens to be the default datetime column.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column == partition_column:
+ # Asked for explicitly, so report it as the mistake it is.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+ elif not partition_mapped_column and main_dttm_col == partition_column:
+ # Resolved onto itself only because the default datetime column happens
+ # to be the partition column -- a state metadata sync could produce
+ # without anyone asking for it. The mapping is inert either way, since
+ # `resolve_partition_mapping` bails out on it, so this reports and lets
+ # the write through: blocking here means a dataset already in the state
+ # can never be saved again, not even to change its description, and
+ # there is no field whose edit would clear the error first.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "%(name)s is both the partition column and the default "
+ "datetime column, so the mapping points at itself and "
+ "stays inactive. Set a mapped column override, or change "
+ "the default datetime column.",
+ name=partition_column,
+ ),
+ blocking=False,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_bare_expression(transform, engine):
+ # Blocking, and deliberately placed in `validate_transform` rather than
+ # only at the probe: one issue here closes the PUT, the importer, the
+ # query-time gate through `is_transform_active`, the Explore indicator's
+ # active verdict and the preview endpoint, all of which already consult
+ # this function.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform must be a single SQL expression. It "
+ "cannot carry a FROM, WHERE, GROUP BY or any other clause, "
+ "and it cannot contain a sub-query."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not contains_value_placeholder(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform must contain the :value placeholder, "
+ "which stands for the filter value being mirrored."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if functions := find_non_deterministic_functions(transform, engine):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform calls %(functions)s, whose result "
+ "depends on when and where it runs. The transform is "
+ "evaluated in a separate session and the result is cached, "
+ "so the emitted predicate would freeze a snapshot of that "
+ "moment.",
+ functions=", ".join(sorted(functions)),
+ ),
+ blocking=True,
+ )
+ ]
+
+ return []
+
+
+@lru_cache(maxsize=LRU_CACHE_MAX_SIZE)
+def is_transform_active(transform: str | None, engine: str) -> bool:
+ """
+ Whether Superset will mirror filters through this transform.
+
+ `validate_transform` with the messages discarded, so the Explore indicator
+ cannot advertise a mapping the save path recorded as inactive. Anything
+ cheaper here would be a second, weaker statement of the same rule, free to
+ drift from the one the save path applies.
+
+ Blocking issues count too. Jinja and non-deterministic transforms are
+ rejected on PUT, but `CreateDatasetCommand` and import do not validate the
+ mapping, so one can still reach the database -- and it would never mirror a
+ filter either.
+
+ Memoized because `partition_filter_mapping_summary` is serialized on every
+ Explore and dashboard load and this parses the transform. The key is
+ everything the answer depends on: `validate_transform` reads no session, no
+ locale and no config beyond `SQL_MAX_PARSE_LENGTH`, which bounds the parser
+ rather than changing a verdict within that bound.
+ """
+ return not validate_transform(transform, engine)
+
+
+def preview_partition_mapping( # pylint: disable=too-many-return-statements
+ datasource: SqlaTable,
+ *,
+ mapped_column: str,
+ value_transform: str | None,
+ sample_values: list[str],
+ operator: FilterOperator = FilterOperator.EQUALS,
+ is_monotonic: bool = False,
+ partition_column: str | None = None,
+) -> dict[str, Any]:
+ """
+ Evaluate a candidate mapping and describe the predicate it would emit.
+
+ Shares the evaluator -- and therefore the probe cache -- with the query
+ path, so preview and runtime cannot drift and a previewed transform warms
+ the chart path for free. The predicate itself comes from
+ `build_mirrored_predicates`, the same builder the query path uses, so
+ operator shapes cannot drift either: what the panel shows is what a chart
+ would emit.
+
+ Validation runs first and the engine second: a half-typed transform is by
+ definition unparseable, so most of what a text input produces costs zero
+ queries.
+
+ Every part of the mapping is taken from the request rather than the stored
+ dataset. The editor previews while the owner is still editing -- a mapping
+ that has to be saved before it can be checked is not a preview.
+ """
+ partition_column = partition_column or datasource.partition_column
+ if not partition_column:
+ return {
+ "valid": False,
+ "reason": "unconfigured",
+ "error": _("No partition column is set."),
+ }
+
+ columns_by_name = {str(column.column_name): column for column in datasource.columns}
+ if mapped_column not in columns_by_name:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _("%(name)s is not a column on this dataset.", name=mapped_column),
+ }
+
+ # The bail-out `resolve_partition_mapping` makes at query time, and that
+ # `partition_filter_mapping_summary` repeats for the Explore indicator.
+ # Without it here, preview reports a valid emitted predicate for a mapping
+ # no chart will ever mirror -- the one answer a preview panel must not give.
+ if has_active_advanced_data_type(columns_by_name[mapped_column]):
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _(
+ "%(name)s has an advanced data type, so its filters are "
+ "translated into their own predicate shape and cannot be "
+ "mirrored onto the partition column.",
+ name=mapped_column,
+ ),
+ }
+
+ engine = datasource.database.backend
+ for issue in validate_partition_mapping(
+ column_names=set(columns_by_name),
+ partition_column=str(partition_column),
+ partition_mapped_column=mapped_column,
+ main_dttm_col=datasource.main_dttm_col,
+ transform=value_transform,
+ engine=engine,
+ ):
+ return {
+ "valid": False,
+ # The parse failure is the one an owner sees constantly, and it is
+ # the only one the mockup gives its own headline to.
+ "reason": (
+ "parse"
+ if issue.field == "partition_value_transform"
+ and not is_parseable(value_transform, engine)
+ else "validation"
+ ),
+ "error": str(issue.message),
+ }
+
+ # The policy every other stored expression goes through. The save path
+ # applies it in `UpdateDatasetCommand._validate_partition_mapping`, but
+ # preview evaluates a candidate transform that has not been saved, so
+ # without this the gate had a door around it. See
+ # `stored_expression_error` for what is being kept out and why.
+ if reason := stored_expression_error(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ cast(str, value_transform),
+ ):
+ return {"valid": False, "reason": "validation", "error": reason}
+
+ mapping = PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=mapped_column,
+ value_transform=cast(str, value_transform),
+ is_monotonic=is_monotonic,
+ equality_is_safe=equality_mirrors_safely(
+ columns_by_name[mapped_column], datasource.database.db_engine_spec
+ ),
+ )
+ sample_input = _render_sample_input(
+ datasource, mapped_column, operator, sample_values
+ )
+
+ if operator not in PREVIEWABLE_OPERATORS:
+ # Checked before `mirrors`, which lets `TEMPORAL_RANGE` through when the
+ # transform is declared monotonic -- and the single sample value would
+ # then reach `handle_comparison_filter`, which has no case for a range
+ # and raises. The request schema rejects it too; this keeps the function
+ # honest for any other caller.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is mirrored as a pair of bounds, which "
+ "a preview of a single value cannot describe.",
+ operator=operator.value,
+ ),
+ }
+
+ if not mapping.mirrors(operator):
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is only mirrored when the transform "
+ "preserves ordering, which this one is not declared to do.",
+ operator=operator.value,
+ ),
+ }
+
+ value: Any = sample_values if operator == FilterOperator.IN else sample_values[0]
+ errors: list[str] = []
+ predicates = build_mirrored_predicates(
+ datasource, mapping, [(operator, value)], errors=errors
+ )
+ if not predicates:
+ return {
+ "valid": False,
+ "reason": "engine",
+ "sample_input": sample_input,
+ "error": (
+ _(
+ "The transform could not be evaluated against the "
+ "database: %(reason)s",
+ reason=errors[0],
+ )
+ if errors
+ else _("The transform could not be evaluated against the database.")
+ ),
+ }
+
+ return {
+ "valid": True,
+ "sample_input": sample_input,
+ "emitted_predicate": _render_predicate(datasource, predicates[0]),
+ }
+
+
+def _render_sample_input(
+ datasource: SqlaTable,
+ mapped_column: str,
+ operator: FilterOperator,
+ values: list[str],
+) -> str:
+ """
+ The filter being previewed, written the way an owner would read it.
+
+ Display-only -- it is never executed -- but it is still read as SQL, so the
+ column is quoted and the values are rendered by the dialect rather than
+ concatenated raw. A column named ``order date`` would otherwise come out as
+ two bare words.
+ """
+ quoted = datasource.quote_identifier(mapped_column)
+ if operator == FilterOperator.IN:
+ rendered = ", ".join(
+ _render_literal(datasource.database, value) for value in values
+ )
+ return f"{quoted} IN ({rendered})"
+ return (
+ f"{quoted} {operator.value} {_render_literal(datasource.database, values[0])}"
+ )
+
+
+def _render_predicate(datasource: SqlaTable, predicate: ColumnElement[Any]) -> str:
+ """
+ Compile a mirrored predicate to the text a reader would see in View query.
+
+ Every value in it is a probed constant by this point, so ``literal_binds``
+ renders the same literals the chart query carries.
+ """
+ return _compile_literal(predicate, _dialect_for(datasource.database)).replace(
+ "\n", " "
+ )
+
+
+def _render_literal(database: Database, value: Any) -> str:
+ """
+ Render a value the way it appears in the generated SQL.
+
+ Compiled by the dialect rather than formatted by hand. `str()` would render
+ a NULL as the Python repr `None` and leave a date unquoted, neither of which
+ is SQL, and hand-rolled quote-doubling would only ever have been right for
+ strings.
+ """
+ return _compile_literal(sa.literal(value), _dialect_for(database))
+
+
+def build_mirrored_predicates(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ requests: list[tuple[FilterOperator, Any]],
+ *,
+ errors: list[str] | None = None,
+) -> list[ColumnElement[Any]]:
+ """
+ Turn collected ``(operator, value)`` mirror requests into predicates.
+
+ ``requests`` is expected to be deduplicated by the caller. Every value is
+ resolved in a single probe round trip -- one per chart query at most -- then
+ emitted as a literal constant, so "View query" shows the reader an ordinary
+ ``WHERE`` clause rather than an inline expression.
+
+ :param errors: optional sink; see `evaluate_transform`.
+ """
+ if not requests:
+ return []
+
+ partition_column = next(
+ (
+ column
+ for column in datasource.columns
+ if column.column_name == mapping.partition_column
+ ),
+ None,
+ )
+ if partition_column is None:
+ return []
+
+ # Flatten every value that needs probing into one list, remembering how many
+ # each request consumed so the results can be handed back out.
+ flat: list[Any] = []
+ spans: list[tuple[FilterOperator, int, int]] = []
+ for operator, value in requests:
+ values = list(value) if operator == FilterOperator.IN else [value]
+ spans.append((operator, len(flat), len(values)))
+ flat.extend(values)
+
+ evaluated = evaluate_transform(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ mapping.value_transform,
+ flat,
+ errors=errors,
+ )
+ if evaluated is None:
+ return []
+
+ if not _bounds_are_ordered(evaluated, spans):
+ return []
+
+ sqla_col = datasource.convert_tbl_column_to_sqla_col(partition_column)
+ db_engine_spec = datasource.db_engine_spec
+
+ predicates: list[ColumnElement[Any]] = []
+ for operator, start, length in spans:
+ chunk = evaluated[start : start + length]
+ if any(value is None for value in chunk):
+ continue
+ if operator == FilterOperator.IN:
+ predicates.append(sqla_col.in_(chunk))
Review Comment:
Fixed. `normalize_mixed_numbers` widens every number to float when any value in the list is one, so `[33, 29.02]` no longer binds as integer and emits `IN (33, 29)`.
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,1314 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` always -- ``T`` is a function
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import re
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLStatement
+from superset.utils import json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: Every entry point enforces it -- the typed column field, the import schema
+#: and the preview request -- because `is_transform_active` parses the stored
+#: value on each Explore load, and an unbounded string would make that parse
+#: the expensive part of rendering a chart.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
Review Comment:
Decision from Hugh: this stays as a documented owner assumption, and we're not adding a gate for it.
The engine-level half is enforced: `equality_mirrors_safely` withdraws `=`/`IN` on a string column unless the spec declares `binary_string_comparison`, declines fixed-width character types whatever the engine says, and declines a type the spec cannot classify (so `citext` is refused rather than waved through).
What's left is the case you named — a column carrying its own `COLLATE NOCASE` on one of the six specs that do declare the flag. We can't detect it: `BaseEngineSpec.column_datatype_to_string` sets `sqla_column_type.collation = None` before the type is stored, so `TableColumn.type` has never carried a collation, and nothing else in the sync path captures one.
The two ways to close it are both worse trades than the gap:
- a per-mapping "this column compares byte-exactly" opt-in would have to fail closed, which costs equality pruning on every existing string mapping until an owner goes and ticks it;
- reflecting collation means a path around that normalization plus per-engine coverage, for a case the gate would then decline anyway.
So it sits with `p = T(mapped_col)` itself — the owner asserts the transform is a function of the mapped column *under the comparison the engine performs*. That's written up in `equality_mirrors_safely`'s docstring and in the module header.
Leaving this one unresolved for you rather than closing it ourselves, since it was your finding and it's a judgement call rather than a fix.
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2264 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate. Named so it cannot
+#: plausibly collide with a real column; a collision only makes the count
+#: disagree, which fails closed.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+ """
+ if not transform:
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error(
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the probe
+ uninspected -- string elements are escaped by the dialect's own literal
+ processor. `probe_sql_is_evaluable` then re-reads the finished query, which
+ is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ else:
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ rendered = _compile_literal(clause, dialect)
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(sql: str, engine: str, expected: int) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Three things have to hold, and all three are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+
+ A ``FROM`` clause is allowed: ``select_without_from_suffix`` adds one on the
+ engines that cannot select without a table.
+ """
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if statement.has_subquery():
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=values is not None and not any(value is None for value in values),
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ database.db_engine_spec.select_without_from_suffix,
+ )
+ if not probe_sql_is_evaluable(sql, database.backend, len(distinct)):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _mirror_verdict_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str:
+ """
+ `_probe_cache_key` without the values.
+
+ Whether a transform can be evaluated at all is a property of the transform
+ and the connection, not of the filter that happened to be probing it, so
+ one chart's answer settles the question for the next one.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_verdict:{digest}"
+
+
+def record_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ *,
+ mirrors: bool,
+) -> None:
+ """
+ Remember whether this transform produced a mirror, for the UI to read.
+
+ Advisory only. Nothing in the query path consults it: a probe that failed
+ once is retried on the next chart exactly as it is today, because declining
+ to prune for a whole cache timeout over one transient engine blip is the
+ trade `evaluate_transform` deliberately refuses -- see the comment where it
+ declines to cache a failure.
+
+ What this is for is the *claim*. `is_transform_active` parses the transform
+ and no more, so a transform the database rejects -- a misspelled function
+ is the common case -- is "active", and the editor's banner and Explore's
+ pruning glyph promise a speed-up that never happens. A promise is exactly
+ the thing that may be withheld on one bad answer and restored on a good
+ one, which is why this is a separate entry from the probe's own results
+ rather than a relaxation of that rule.
+
+ Written by `_run_probe`, so the preview endpoint -- which shares the
+ evaluator -- settles the question before the owner has even saved.
+ """
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(
+ _mirror_verdict_cache_key(database, catalog, schema, transform),
+ mirrors,
+ timeout=timeout,
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform verdict", exc_info=True)
+
+
+def known_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> bool | None:
+ """
+ The last verdict `record_mirror_verdict` stored, or `None` if there is none.
+
+ `None` is the honest answer on a cold cache and is deliberately not `False`:
+ reporting a working mapping as broken until something probes it would
+ trade one wrong claim for another. The alternative -- probing from the
+ read side -- would put a warehouse round trip on every Explore and
+ dashboard load, and a failing transform is not cached at all, so it would
+ be a round trip every single time.
+ """
+ try:
+ verdict = cache_manager.cache.get(
+ _mirror_verdict_cache_key(database, catalog, schema, transform)
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return verdict if isinstance(verdict, bool) else None
+
+
+def _compile_literal(element: Any, dialect: Dialect | None) -> str:
+ """
+ Compile with inline literals, undoing the paramstyle's percent doubling.
+
+ Both ``TextClause`` and literal compilation run the dialect's
+ ``post_process_text``, which doubles every ``%`` whenever the identifier
+ preparer asks it to -- true for MySQL and Postgres and for every spec
+ inheriting their paramstyle. That doubling exists so a later DBAPI
+ parameter-interpolation pass can undo it, and the probe has no such pass:
+ it executes with no bound parameters at all. So a transform of
+ ``date_format(:value, '%Y%m%d')`` reaches the warehouse asking for the
+ literal string ``%%Y%%m%%d``, the probe returns that instead of a date, and
+ the mirrored predicate drops every row the filter keeps.
+
+ The same normalization ``Database.compile_sqla_query`` applies for the same
+ reason. ``_double_percents`` is private and not guaranteed on a third-party
+ dialect, hence the ``getattr`` default.
+ """
+ compiled = str(
+ element.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
+ )
+ if dialect is not None and getattr(
+ dialect.identifier_preparer, "_double_percents", False
+ ):
+ compiled = compiled.replace("%%", "%")
+ return compiled
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be *asked* to stand in for itself, and the transform
+ cannot carry Jinja or call a non-deterministic function. Tier 2
+ (``blocking=False``) is everything that merely leaves the mapping inactive
+ -- including a self-mapping nobody asked for, where the partition column
+ merely happens to be the default datetime column.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column == partition_column:
+ # Asked for explicitly, so report it as the mistake it is.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+ elif not partition_mapped_column and main_dttm_col == partition_column:
+ # Resolved onto itself only because the default datetime column happens
+ # to be the partition column -- a state metadata sync could produce
+ # without anyone asking for it. The mapping is inert either way, since
+ # `resolve_partition_mapping` bails out on it, so this reports and lets
+ # the write through: blocking here means a dataset already in the state
+ # can never be saved again, not even to change its description, and
+ # there is no field whose edit would clear the error first.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "%(name)s is both the partition column and the default "
+ "datetime column, so the mapping points at itself and "
+ "stays inactive. Set a mapped column override, or change "
+ "the default datetime column.",
+ name=partition_column,
+ ),
+ blocking=False,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_bare_expression(transform, engine):
+ # Blocking, and deliberately placed in `validate_transform` rather than
+ # only at the probe: one issue here closes the PUT, the importer, the
+ # query-time gate through `is_transform_active`, the Explore indicator's
+ # active verdict and the preview endpoint, all of which already consult
+ # this function.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform must be a single SQL expression. It "
+ "cannot carry a FROM, WHERE, GROUP BY or any other clause, "
+ "and it cannot contain a sub-query."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not contains_value_placeholder(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform must contain the :value placeholder, "
+ "which stands for the filter value being mirrored."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not placeholder_is_executable(transform, engine):
+ # Blocking, and for the same reason the shape gate above is: this is
+ # the function the PUT, the importer, `is_transform_active`, the
+ # Explore indicator and the preview all consult, so one issue here
+ # closes every door at once. A placeholder inside a string literal is
+ # a sub-query the engine will run once a filter value closes the quote;
+ # one inside a comment silently eats the probe's own alias.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The :value placeholder must appear where the engine will "
+ "evaluate it. It cannot sit inside a string literal or a "
+ "comment."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if functions := find_non_deterministic_functions(transform, engine):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform calls %(functions)s, whose result "
+ "depends on when and where it runs. The transform is "
+ "evaluated in a separate session and the result is cached, "
+ "so the emitted predicate would freeze a snapshot of that "
+ "moment.",
+ functions=", ".join(sorted(functions)),
+ ),
+ blocking=True,
+ )
+ ]
+
+ return []
+
+
+@lru_cache(maxsize=LRU_CACHE_MAX_SIZE)
+def is_transform_active(transform: str | None, engine: str) -> bool:
+ """
+ Whether Superset will mirror filters through this transform.
+
+ `validate_transform` with the messages discarded, so the Explore indicator
+ cannot advertise a mapping the save path recorded as inactive. Anything
+ cheaper here would be a second, weaker statement of the same rule, free to
+ drift from the one the save path applies.
+
+ Blocking issues count too. Jinja and non-deterministic transforms are
+ rejected on PUT, but `CreateDatasetCommand` and import do not validate the
+ mapping, so one can still reach the database -- and it would never mirror a
+ filter either.
+
+ Memoized because `partition_filter_mapping_summary` is serialized on every
+ Explore and dashboard load and this parses the transform. The key is
+ everything the answer depends on: `validate_transform` reads no session, no
+ locale and no config beyond `SQL_MAX_PARSE_LENGTH`, which bounds the parser
+ rather than changing a verdict within that bound.
+ """
+ return not validate_transform(transform, engine)
+
+
+def preview_partition_mapping( # pylint: disable=too-many-return-statements
+ datasource: SqlaTable,
+ *,
+ mapped_column: str,
+ value_transform: str | None,
+ sample_values: list[str],
+ operator: FilterOperator = FilterOperator.EQUALS,
+ is_monotonic: bool = False,
+ partition_column: str | None = None,
+) -> dict[str, Any]:
+ """
+ Evaluate a candidate mapping and describe the predicate it would emit.
+
+ Shares the evaluator -- and therefore the probe cache -- with the query
+ path, so preview and runtime cannot drift and a previewed transform warms
+ the chart path for free. The predicate itself comes from
+ `build_mirrored_predicates`, the same builder the query path uses, so
+ operator shapes cannot drift either: what the panel shows is what a chart
+ would emit.
+
+ Validation runs first and the engine second: a half-typed transform is by
+ definition unparseable, so most of what a text input produces costs zero
+ queries.
+
+ Every part of the mapping is taken from the request rather than the stored
+ dataset. The editor previews while the owner is still editing -- a mapping
+ that has to be saved before it can be checked is not a preview.
+ """
+ partition_column = partition_column or datasource.partition_column
+ if not partition_column:
+ return {
+ "valid": False,
+ "reason": "unconfigured",
+ "error": _("No partition column is set."),
+ }
+
+ columns_by_name = {str(column.column_name): column for column in datasource.columns}
+ if mapped_column not in columns_by_name:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _("%(name)s is not a column on this dataset.", name=mapped_column),
+ }
+
+ # The bail-out `resolve_partition_mapping` makes at query time, and that
+ # `partition_filter_mapping_summary` repeats for the Explore indicator.
+ # Without it here, preview reports a valid emitted predicate for a mapping
+ # no chart will ever mirror -- the one answer a preview panel must not give.
+ if has_active_advanced_data_type(columns_by_name[mapped_column]):
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _(
+ "%(name)s has an advanced data type, so its filters are "
+ "translated into their own predicate shape and cannot be "
+ "mirrored onto the partition column.",
+ name=mapped_column,
+ ),
+ }
+
+ engine = datasource.database.backend
+ for issue in validate_partition_mapping(
+ column_names=set(columns_by_name),
+ partition_column=str(partition_column),
+ partition_mapped_column=mapped_column,
+ main_dttm_col=datasource.main_dttm_col,
+ transform=value_transform,
+ engine=engine,
+ ):
+ return {
+ "valid": False,
+ # The parse failure is the one an owner sees constantly, and it is
+ # the only one the mockup gives its own headline to.
+ "reason": (
+ "parse"
+ if issue.field == "partition_value_transform"
+ and not is_parseable(value_transform, engine)
+ else "validation"
+ ),
+ "error": str(issue.message),
+ }
+
+ # The policy every other stored expression goes through. The save path
+ # applies it in `UpdateDatasetCommand._validate_partition_mapping`, but
+ # preview evaluates a candidate transform that has not been saved, so
+ # without this the gate had a door around it. See
+ # `stored_expression_error` for what is being kept out and why.
+ if reason := stored_expression_error(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ cast(str, value_transform),
+ ):
+ return {"valid": False, "reason": "validation", "error": reason}
+
+ mapping = PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=mapped_column,
+ value_transform=cast(str, value_transform),
+ is_monotonic=is_monotonic,
+ equality_is_safe=equality_mirrors_safely(
+ columns_by_name[mapped_column], datasource.database.db_engine_spec
+ ),
+ )
+ sample_input = _render_sample_input(
+ datasource, mapped_column, operator, sample_values
+ )
+
+ if operator not in PREVIEWABLE_OPERATORS:
+ # Checked before `mirrors`, which lets `TEMPORAL_RANGE` through when the
+ # transform is declared monotonic -- and the single sample value would
+ # then reach `handle_comparison_filter`, which has no case for a range
+ # and raises. The request schema rejects it too; this keeps the function
+ # honest for any other caller.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is mirrored as a pair of bounds, which "
+ "a preview of a single value cannot describe.",
+ operator=operator.value,
+ ),
+ }
+
+ if not mapping.mirrors(operator):
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is only mirrored when the transform "
+ "preserves ordering, which this one is not declared to do.",
+ operator=operator.value,
+ ),
+ }
+
+ value = _probe_input(
Review Comment:
Fixed. `_probe_input`'s result is handed straight to `ExploreMixin.mirror_probe_request`, which is where the chart path's widening and declining live, so preview and the query path now make the same call.
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2264 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate. Named so it cannot
+#: plausibly collide with a real column; a collision only makes the count
+#: disagree, which fails closed.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+ """
+ if not transform:
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error(
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the probe
+ uninspected -- string elements are escaped by the dialect's own literal
+ processor. `probe_sql_is_evaluable` then re-reads the finished query, which
+ is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ else:
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ rendered = _compile_literal(clause, dialect)
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(sql: str, engine: str, expected: int) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Three things have to hold, and all three are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+
+ A ``FROM`` clause is allowed: ``select_without_from_suffix`` adds one on the
+ engines that cannot select without a table.
+ """
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if statement.has_subquery():
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=values is not None and not any(value is None for value in values),
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ database.db_engine_spec.select_without_from_suffix,
+ )
+ if not probe_sql_is_evaluable(sql, database.backend, len(distinct)):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _mirror_verdict_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str:
+ """
+ `_probe_cache_key` without the values.
+
+ Whether a transform can be evaluated at all is a property of the transform
+ and the connection, not of the filter that happened to be probing it, so
+ one chart's answer settles the question for the next one.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_verdict:{digest}"
+
+
+def record_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ *,
+ mirrors: bool,
+) -> None:
+ """
+ Remember whether this transform produced a mirror, for the UI to read.
+
+ Advisory only. Nothing in the query path consults it: a probe that failed
+ once is retried on the next chart exactly as it is today, because declining
+ to prune for a whole cache timeout over one transient engine blip is the
+ trade `evaluate_transform` deliberately refuses -- see the comment where it
+ declines to cache a failure.
+
+ What this is for is the *claim*. `is_transform_active` parses the transform
+ and no more, so a transform the database rejects -- a misspelled function
+ is the common case -- is "active", and the editor's banner and Explore's
+ pruning glyph promise a speed-up that never happens. A promise is exactly
+ the thing that may be withheld on one bad answer and restored on a good
+ one, which is why this is a separate entry from the probe's own results
+ rather than a relaxation of that rule.
+
+ Written by `_run_probe`, so the preview endpoint -- which shares the
+ evaluator -- settles the question before the owner has even saved.
+ """
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(
+ _mirror_verdict_cache_key(database, catalog, schema, transform),
+ mirrors,
+ timeout=timeout,
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform verdict", exc_info=True)
+
+
+def known_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> bool | None:
+ """
+ The last verdict `record_mirror_verdict` stored, or `None` if there is none.
+
+ `None` is the honest answer on a cold cache and is deliberately not `False`:
+ reporting a working mapping as broken until something probes it would
+ trade one wrong claim for another. The alternative -- probing from the
+ read side -- would put a warehouse round trip on every Explore and
+ dashboard load, and a failing transform is not cached at all, so it would
+ be a round trip every single time.
+ """
+ try:
+ verdict = cache_manager.cache.get(
+ _mirror_verdict_cache_key(database, catalog, schema, transform)
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return verdict if isinstance(verdict, bool) else None
+
+
+def _compile_literal(element: Any, dialect: Dialect | None) -> str:
+ """
+ Compile with inline literals, undoing the paramstyle's percent doubling.
+
+ Both ``TextClause`` and literal compilation run the dialect's
+ ``post_process_text``, which doubles every ``%`` whenever the identifier
+ preparer asks it to -- true for MySQL and Postgres and for every spec
+ inheriting their paramstyle. That doubling exists so a later DBAPI
+ parameter-interpolation pass can undo it, and the probe has no such pass:
+ it executes with no bound parameters at all. So a transform of
+ ``date_format(:value, '%Y%m%d')`` reaches the warehouse asking for the
+ literal string ``%%Y%%m%%d``, the probe returns that instead of a date, and
+ the mirrored predicate drops every row the filter keeps.
+
+ The same normalization ``Database.compile_sqla_query`` applies for the same
+ reason. ``_double_percents`` is private and not guaranteed on a third-party
+ dialect, hence the ``getattr`` default.
+ """
+ compiled = str(
+ element.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
+ )
+ if dialect is not None and getattr(
+ dialect.identifier_preparer, "_double_percents", False
+ ):
+ compiled = compiled.replace("%%", "%")
+ return compiled
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be *asked* to stand in for itself, and the transform
+ cannot carry Jinja or call a non-deterministic function. Tier 2
+ (``blocking=False``) is everything that merely leaves the mapping inactive
+ -- including a self-mapping nobody asked for, where the partition column
+ merely happens to be the default datetime column.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column == partition_column:
+ # Asked for explicitly, so report it as the mistake it is.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+ elif not partition_mapped_column and main_dttm_col == partition_column:
+ # Resolved onto itself only because the default datetime column happens
+ # to be the partition column -- a state metadata sync could produce
+ # without anyone asking for it. The mapping is inert either way, since
+ # `resolve_partition_mapping` bails out on it, so this reports and lets
+ # the write through: blocking here means a dataset already in the state
+ # can never be saved again, not even to change its description, and
+ # there is no field whose edit would clear the error first.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "%(name)s is both the partition column and the default "
+ "datetime column, so the mapping points at itself and "
+ "stays inactive. Set a mapped column override, or change "
+ "the default datetime column.",
+ name=partition_column,
+ ),
+ blocking=False,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_bare_expression(transform, engine):
+ # Blocking, and deliberately placed in `validate_transform` rather than
+ # only at the probe: one issue here closes the PUT, the importer, the
+ # query-time gate through `is_transform_active`, the Explore indicator's
+ # active verdict and the preview endpoint, all of which already consult
+ # this function.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform must be a single SQL expression. It "
+ "cannot carry a FROM, WHERE, GROUP BY or any other clause, "
+ "and it cannot contain a sub-query."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not contains_value_placeholder(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform must contain the :value placeholder, "
+ "which stands for the filter value being mirrored."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not placeholder_is_executable(transform, engine):
+ # Blocking, and for the same reason the shape gate above is: this is
+ # the function the PUT, the importer, `is_transform_active`, the
+ # Explore indicator and the preview all consult, so one issue here
+ # closes every door at once. A placeholder inside a string literal is
+ # a sub-query the engine will run once a filter value closes the quote;
+ # one inside a comment silently eats the probe's own alias.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The :value placeholder must appear where the engine will "
+ "evaluate it. It cannot sit inside a string literal or a "
+ "comment."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if functions := find_non_deterministic_functions(transform, engine):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform calls %(functions)s, whose result "
+ "depends on when and where it runs. The transform is "
+ "evaluated in a separate session and the result is cached, "
+ "so the emitted predicate would freeze a snapshot of that "
+ "moment.",
+ functions=", ".join(sorted(functions)),
+ ),
+ blocking=True,
+ )
+ ]
+
+ return []
+
+
+@lru_cache(maxsize=LRU_CACHE_MAX_SIZE)
+def is_transform_active(transform: str | None, engine: str) -> bool:
+ """
+ Whether Superset will mirror filters through this transform.
+
+ `validate_transform` with the messages discarded, so the Explore indicator
+ cannot advertise a mapping the save path recorded as inactive. Anything
+ cheaper here would be a second, weaker statement of the same rule, free to
+ drift from the one the save path applies.
+
+ Blocking issues count too. Jinja and non-deterministic transforms are
+ rejected on PUT, but `CreateDatasetCommand` and import do not validate the
+ mapping, so one can still reach the database -- and it would never mirror a
+ filter either.
+
+ Memoized because `partition_filter_mapping_summary` is serialized on every
+ Explore and dashboard load and this parses the transform. The key is
+ everything the answer depends on: `validate_transform` reads no session, no
+ locale and no config beyond `SQL_MAX_PARSE_LENGTH`, which bounds the parser
+ rather than changing a verdict within that bound.
+ """
+ return not validate_transform(transform, engine)
+
+
+def preview_partition_mapping( # pylint: disable=too-many-return-statements
+ datasource: SqlaTable,
+ *,
+ mapped_column: str,
+ value_transform: str | None,
+ sample_values: list[str],
+ operator: FilterOperator = FilterOperator.EQUALS,
+ is_monotonic: bool = False,
+ partition_column: str | None = None,
+) -> dict[str, Any]:
+ """
+ Evaluate a candidate mapping and describe the predicate it would emit.
+
+ Shares the evaluator -- and therefore the probe cache -- with the query
+ path, so preview and runtime cannot drift and a previewed transform warms
+ the chart path for free. The predicate itself comes from
+ `build_mirrored_predicates`, the same builder the query path uses, so
+ operator shapes cannot drift either: what the panel shows is what a chart
+ would emit.
+
+ Validation runs first and the engine second: a half-typed transform is by
+ definition unparseable, so most of what a text input produces costs zero
+ queries.
+
+ Every part of the mapping is taken from the request rather than the stored
+ dataset. The editor previews while the owner is still editing -- a mapping
+ that has to be saved before it can be checked is not a preview.
+ """
+ partition_column = partition_column or datasource.partition_column
+ if not partition_column:
+ return {
+ "valid": False,
+ "reason": "unconfigured",
+ "error": _("No partition column is set."),
+ }
+
+ columns_by_name = {str(column.column_name): column for column in datasource.columns}
+ if mapped_column not in columns_by_name:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _("%(name)s is not a column on this dataset.", name=mapped_column),
+ }
+
+ # The bail-out `resolve_partition_mapping` makes at query time, and that
+ # `partition_filter_mapping_summary` repeats for the Explore indicator.
+ # Without it here, preview reports a valid emitted predicate for a mapping
+ # no chart will ever mirror -- the one answer a preview panel must not give.
+ if has_active_advanced_data_type(columns_by_name[mapped_column]):
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _(
+ "%(name)s has an advanced data type, so its filters are "
+ "translated into their own predicate shape and cannot be "
+ "mirrored onto the partition column.",
+ name=mapped_column,
+ ),
+ }
+
+ engine = datasource.database.backend
+ for issue in validate_partition_mapping(
+ column_names=set(columns_by_name),
+ partition_column=str(partition_column),
+ partition_mapped_column=mapped_column,
+ main_dttm_col=datasource.main_dttm_col,
+ transform=value_transform,
+ engine=engine,
+ ):
+ return {
+ "valid": False,
+ # The parse failure is the one an owner sees constantly, and it is
+ # the only one the mockup gives its own headline to.
+ "reason": (
+ "parse"
+ if issue.field == "partition_value_transform"
+ and not is_parseable(value_transform, engine)
+ else "validation"
+ ),
+ "error": str(issue.message),
+ }
+
+ # The policy every other stored expression goes through. The save path
+ # applies it in `UpdateDatasetCommand._validate_partition_mapping`, but
+ # preview evaluates a candidate transform that has not been saved, so
+ # without this the gate had a door around it. See
+ # `stored_expression_error` for what is being kept out and why.
+ if reason := stored_expression_error(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ cast(str, value_transform),
+ ):
+ return {"valid": False, "reason": "validation", "error": reason}
+
+ mapping = PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=mapped_column,
+ value_transform=cast(str, value_transform),
+ is_monotonic=is_monotonic,
+ equality_is_safe=equality_mirrors_safely(
+ columns_by_name[mapped_column], datasource.database.db_engine_spec
+ ),
+ )
+ sample_input = _render_sample_input(
+ datasource, mapped_column, operator, sample_values
+ )
+
+ if operator not in PREVIEWABLE_OPERATORS:
+ # Checked before `mirrors`, which lets `TEMPORAL_RANGE` through when the
+ # transform is declared monotonic -- and the single sample value would
+ # then reach `handle_comparison_filter`, which has no case for a range
+ # and raises. The request schema rejects it too; this keeps the function
+ # honest for any other caller.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is mirrored as a pair of bounds, which "
+ "a preview of a single value cannot describe.",
+ operator=operator.value,
+ ),
+ }
+
+ if not mapping.mirrors(operator):
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is only mirrored when the transform "
+ "preserves ordering, which this one is not declared to do.",
+ operator=operator.value,
+ ),
+ }
+
+ value = _probe_input(
+ datasource, columns_by_name[mapped_column], operator, sample_values
+ )
+ errors: list[str] = []
+ type_errors: list[str] = []
+ predicates = build_mirrored_predicates(
+ datasource,
+ mapping,
+ [(operator, value)],
+ errors=errors,
+ type_errors=type_errors,
+ )
+ if type_errors:
+ # Its own reason, because "the database would not evaluate this" and
+ # "it evaluated and answered with the wrong kind of thing" are
+ # different problems with different fixes, and the owner is the only
+ # one who can tell which transform they meant to write.
+ return {
+ "valid": False,
+ "reason": "type",
+ "sample_input": sample_input,
+ "error": type_errors[0],
+ }
+ if not predicates:
+ return {
+ "valid": False,
+ "reason": "engine",
+ "sample_input": sample_input,
+ "error": (
+ _(
+ "The transform could not be evaluated against the "
+ "database: %(reason)s",
+ reason=errors[0],
+ )
+ if errors
+ else _("The transform could not be evaluated against the database.")
+ ),
+ }
+
+ return {
+ "valid": True,
+ "sample_input": sample_input,
+ "emitted_predicate": _render_predicate(datasource, predicates[0]),
+ }
+
+
+def _probe_input(
+ datasource: SqlaTable,
+ column: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+) -> Any:
+ """
+ The sample values as the query path would bind them.
+
+ The request carries samples as strings, and the probe is keyed on exactly
+ what it is handed, so passing them through raw asks the engine a different
+ question from the one a chart asks. A sample of ``2025`` on a numeric
+ column has to arrive as the integer the chart compares: under a transform
+ of ``typeof(:value)`` the raw string previewed ``'text'`` where the chart
+ emitted ``'integer'``. And because `_probe_cache_key` keys on each value's
+ ``repr``, the two also missed each other's cache entirely -- so the "a
+ previewed transform warms the chart path for free" claim in
+ `preview_partition_mapping`'s docstring did not actually hold.
+
+ Coerced by `filter_values_handler`, the same function the query path uses,
+ rather than by a second implementation of the same rules.
+
+ Ranges are not previewable (see `PREVIEWABLE_OPERATORS`), so the bound
+ conversion `_collect_partition_mirror_range` applies -- a ``datetime`` into
+ the column's stored representation -- has no counterpart here.
+ """
+ is_list = operator == FilterOperator.IN
+ column_spec = datasource.db_engine_spec.get_column_spec(native_type=column.type)
+ handled = datasource.filter_values_handler(
+ # `list[str]` is not a `list[FilterValue]` to mypy, invariantly, even
+ # though every `str` is a `FilterValue`.
+ values=cast(FilterValues, sample_values if is_list else sample_values[0]),
+ operator=operator,
+ target_generic_type=(
+ column_spec.generic_type if column_spec else utils.GenericDataType.STRING
+ ),
+ target_native_type=column.type,
+ is_list_target=is_list,
+ db_engine_spec=datasource.db_engine_spec,
+ db_extra=datasource.db_extra,
+ )
+
+ def bindable(value: Any) -> Any:
+ # An epoch-milliseconds sample on a temporal column comes back as
+ # engine SQL rather than a value, and SQL cannot be the value of a bind
+ # parameter -- carried as text so the probe substitutes it, the same way
+ # an array literal is.
+ if isinstance(value, ColumnElement):
+ return raw_probe_value(datasource.database, value)
+ return value
+
+ if is_list and isinstance(handled, (list, tuple)):
+ return [bindable(entry) for entry in handled]
+ return bindable(handled)
+
+
+def _render_sample_input(
+ datasource: SqlaTable,
+ mapped_column: str,
+ operator: FilterOperator,
+ values: list[str],
+) -> str:
+ """
+ The filter being previewed, written the way an owner would read it.
+
+ Display-only -- it is never executed -- but it is still read as SQL, so the
+ column is quoted and the values are rendered by the dialect rather than
+ concatenated raw. A column named ``order date`` would otherwise come out as
+ two bare words.
+ """
+ quoted = datasource.quote_identifier(mapped_column)
+ if operator == FilterOperator.IN:
+ rendered = ", ".join(
+ _render_literal(datasource.database, value) for value in values
+ )
+ return f"{quoted} IN ({rendered})"
+ return (
+ f"{quoted} {operator.value} {_render_literal(datasource.database, values[0])}"
+ )
+
+
+def _render_predicate(datasource: SqlaTable, predicate: ColumnElement[Any]) -> str:
+ """
+ Compile a mirrored predicate to the text a reader would see in View query.
+
+ Every value in it is a probed constant by this point, so ``literal_binds``
+ renders the same literals the chart query carries.
+ """
+ return _compile_literal(predicate, _dialect_for(datasource.database)).replace(
+ "\n", " "
+ )
+
+
+def _render_literal(database: Database, value: Any) -> str:
+ """
+ Render a value the way it appears in the generated SQL.
+
+ Compiled by the dialect rather than formatted by hand. `str()` would render
+ a NULL as the Python repr `None` and leave a date unquoted, neither of which
+ is SQL, and hand-rolled quote-doubling would only ever have been right for
+ strings.
+ """
+ return _compile_literal(sa.literal(value), _dialect_for(database))
+
+
+def build_mirrored_predicates(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ requests: list[tuple[FilterOperator, Any]],
+ *,
+ errors: list[str] | None = None,
+ type_errors: list[str] | None = None,
+) -> list[ColumnElement[Any]]:
+ """
+ Turn collected ``(operator, value)`` mirror requests into predicates.
+
+ ``requests`` is expected to be deduplicated by the caller. Every value is
+ resolved in a single probe round trip -- one per chart query at most -- then
+ emitted as a literal constant, so "View query" shows the reader an ordinary
+ ``WHERE`` clause rather than an inline expression.
+
+ A strict bound is emitted non-strictly; see `mirror_operator`. That happens
+ here, at the one point where a ``FilterOperator`` becomes SQL, rather than
+ at the collection sites in `ExploreMixin`: the preview endpoint calls this
+ directly, so this is what keeps the predicate the editor shows an owner and
+ the predicate the chart carries from disagreeing.
+
+ :param errors: optional sink; see `evaluate_transform`.
+ :param type_errors: optional sink for a probe result the partition column
+ cannot hold -- see `probed_value_type_error`. Separate from ``errors``
+ because the two say different things to an owner: that one is "the
+ database would not evaluate this", and this one is "it evaluated, and
+ answered with the wrong kind of thing".
+ """
+ if not requests:
+ return []
+
+ partition_column = next(
+ (
+ column
+ for column in datasource.columns
+ if column.column_name == mapping.partition_column
+ ),
+ None,
+ )
+ if partition_column is None:
+ return []
+
+ # Flatten every value that needs probing into one list, remembering how many
+ # each request consumed so the results can be handed back out.
+ flat: list[Any] = []
+ spans: list[tuple[FilterOperator, int, int]] = []
+ for operator, value in requests:
+ values = list(value) if operator == FilterOperator.IN else [value]
+ spans.append((operator, len(flat), len(values)))
+ flat.extend(values)
+
+ evaluated = evaluate_transform(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ mapping.value_transform,
+ flat,
+ errors=errors,
+ )
+ if evaluated is None:
+ return []
+
+ if not _bounds_are_ordered(evaluated, spans):
+ return []
+
+ # Declining here is the last chance to decline at all: once these
+ # predicates are in the statement, a value the partition column cannot
+ # hold fails the whole chart rather than its pruning.
+ if reason := probed_value_type_error(partition_column, evaluated):
+ logger.warning(
+ "Partition transform returned a value the partition column cannot "
+ "hold; queries will not prune: %s",
+ reason,
+ )
+ if type_errors is not None:
+ type_errors.append(reason)
+ record_mirror_verdict(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ mapping.value_transform,
+ mirrors=False,
+ )
+ return []
+
+ sqla_col = datasource.convert_tbl_column_to_sqla_col(partition_column)
+ predicates = _predicates_from_probe(
+ sqla_col, datasource.db_engine_spec, evaluated, spans
+ )
+ if not predicates:
+ return []
+
+ # A comparison against a NULL partition value is NULL, so a row parked in a
+ # NULL partition is dropped by the mirror even when the real filter matches
+ # it -- Hive and Impala's default partition, or a transform that returns
+ # NULL for an input it cannot convert. The mirror only has to be no
+ # narrower than the filter it stands in for, so admitting NULL partitions
+ # keeps those rows. Engines still prune; they read one extra partition.
+ return [sa.or_(sa.and_(*predicates), sqla_col.is_(None))]
+
+
+def _predicates_from_probe(
+ sqla_col: ColumnElement[Any],
+ db_engine_spec: type[BaseEngineSpec],
+ evaluated: list[Any],
+ spans: list[tuple[FilterOperator, int, int]],
+) -> list[ColumnElement[Any]]:
+ """
+ One predicate on the partition column per surviving mirror request.
+
+ A request whose probe answered `None` for any of its values is skipped
+ rather than emitted: `col = NULL` is `NULL`, so it would drop every row the
+ filter keeps. A strict bound is emitted non-strictly; see `mirror_operator`.
+ """
+ predicates: list[ColumnElement[Any]] = []
+ for operator, start, length in spans:
+ chunk = evaluated[start : start + length]
+ if any(value is None for value in chunk):
+ continue
+ if operator == FilterOperator.IN:
+ # The probe answers per value, so a transform over a mixed-number
+ # filter can answer with a mixed-number partition key -- and
+ # `in_` infers the bind type from the first element it is handed.
+ # Without this, probe results of `[33, 29.02]` emit
+ # `IN (33, 29)` and prune away the partition holding `29.02`.
+ predicates.append(sqla_col.in_(normalize_mixed_numbers(chunk)))
+ else:
+ predicates.append(
+ db_engine_spec.handle_comparison_filter(
+ sqla_col, mirror_operator(operator), chunk[0]
+ )
+ )
+ return predicates
+
+
+#: Operators whose value is the lower end of a range, and whose upper-end twins.
+#:
+#: Shared with `ExploreMixin._mirror_probe_input`, which rounds a bound *outward*
+#: where the engine resolves it more coarsely than the filter carries -- backward
+#: for a lower bound, forward for an upper one. Which end an operator names is
+#: the only thing separating the two directions in either caller, so the two have
+#: to agree on it rather than each classify for itself.
+LOWER_BOUND_OPERATORS = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+}
+UPPER_BOUND_OPERATORS = {
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+#: What Python type a probe result may have, per generic type of the partition
+#: column it is about to be compared against.
+#:
+#: Only the types a mismatch can actually break a query with are listed. A
+#: ``STRING`` partition column is deliberately absent: every engine accepts a
+#: number in a text comparison, and refusing one would break a working mapping
+#: for the sake of tidiness. An unresolvable column type is absent for the
+#: stronger reason that there is nothing to check against.
+#: ``numbers.Number`` rather than ``(int, float)``: Postgres answers
+#: ``extract(epoch from ...)`` with a `Decimal`, which is the single commonest
+#: transform this feature has, and an engine is free to answer with any number
+#: type its driver prefers. What the check is for is a *string* where a number
+#: belongs, and every numeric type is equally not that.
+_PROBE_RESULT_TYPES: dict[utils.GenericDataType, tuple[type, ...]] = {
Review Comment:
Fixed. `_PROBE_RESULT_TYPES` maps `GenericDataType.STRING` to `(str,)` — a number rendered against a text partition key is declined rather than exempted, with Postgres, Trino, BigQuery and SQLite's differing failure modes written up at the table. An owner whose key really is text writes the cast into the transform.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "hughhhh (via GitHub)" <gi...@apache.org>.
hughhhh commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4319677594
##########
tests/unit_tests/commands/dataset/update_test.py:
##########
@@ -1366,3 +1375,254 @@ def test_update_dataset_rejects_malicious_fetch_values_predicate(
and "fetch_values_predicate" in (exc.field_name or "")
for exc in excinfo.value._exceptions
)
+
+
+def _mapping_command(
+ mocker: MockerFixture,
+ transform: str | None,
+ *,
+ partition_mapped_column: str | None = None,
+) -> UpdateDatasetCommand:
+ """A command whose stored dataset maps `event_time` onto `dt_epoch`."""
+ mapped_column = mocker.MagicMock()
+ mapped_column.column_name = "event_time"
+ mapped_column.partition_value_transform = transform
+ partition_column = mocker.MagicMock()
+ partition_column.column_name = "dt_epoch"
+ # The partition column is the target of a mapping, never the source of one.
+ partition_column.partition_value_transform = None
+
+ mock_dataset = mocker.MagicMock(is_managed_externally=False)
+ mock_dataset.database.backend = "sqlite"
+ mock_dataset.catalog = None
+ mock_dataset.schema = "main"
+ mock_dataset.columns = [mapped_column, partition_column]
+ mock_dataset.main_dttm_col = "event_time"
+ mock_dataset.partition_column = "dt_epoch"
+ mock_dataset.partition_mapped_column = partition_mapped_column
+
+ command = UpdateDatasetCommand(1, {})
+ command._model = mock_dataset
+ return command
+
+
+@with_feature_flags(PARTITION_FILTER_MAPPING=True)
+def test_an_unparseable_transform_does_not_block_the_save(
+ mocker: MockerFixture,
+) -> None:
+ """
+ An unparseable transform is a Tier-2 issue: the mapping saves and stays
+ inactive. `validate_stored_expression` rejects anything it cannot parse, so
+ running it here would turn that into a blocking error and cost the owner the
+ rest of their edits.
+ """
+ gate = mocker.patch("superset.commands.dataset.update.validate_stored_expression")
+ command = _mapping_command(mocker, "unix_timestamp(:value")
+
+ exceptions: list[ValidationError] = []
+ command._validate_partition_mapping(exceptions)
+
+ assert exceptions == []
+ gate.assert_not_called()
+
+
+@with_feature_flags(PARTITION_FILTER_MAPPING=True)
+def test_a_parseable_transform_still_goes_through_the_stored_expression_gate(
+ mocker: MockerFixture,
+) -> None:
+ """The parser gate that governs every other stored expression still runs."""
+ gate = mocker.patch("superset.commands.dataset.update.validate_stored_expression")
+ command = _mapping_command(mocker, "unix_timestamp(:value)")
+
+ exceptions: list[ValidationError] = []
+ command._validate_partition_mapping(exceptions)
+
+ assert exceptions == []
+ gate.assert_called_once()
+ assert ":value" not in gate.call_args.args[-1]
+
+
+@with_feature_flags(PARTITION_FILTER_MAPPING=True)
+@pytest.mark.parametrize(
+ "transform",
+ [
+ "unix_timestamp(:value) UNION ALL SELECT password FROM ab_user",
+ "unix_timestamp(:value); DROP TABLE ab_user",
+ "password || :value FROM ab_user",
+ ],
+ ids=["set-operation", "multi-statement", "bare-from"],
+)
+def test_a_transform_that_is_the_wrong_sql_still_reaches_the_gate(
+ mocker: MockerFixture, transform: str
+) -> None:
+ """
+ The companion to the test above, and the reason the skip condition is "not
+ SQL yet" rather than "does not parse". All three of these fail to parse as
+ a single statement, exactly as a half-typed transform does -- so a skip
+ keyed on parseability would have waved them through. None of them is on the
+ way to a valid transform.
+ """
+ gate = mocker.patch("superset.commands.dataset.update.validate_stored_expression")
+ command = _mapping_command(mocker, transform)
+
+ exceptions: list[ValidationError] = []
+ command._validate_partition_mapping(exceptions)
+
+ # Either the shape issue reports it or the gate does; what matters is that
+ # it is not silently accepted the way an unfinished transform is.
+ assert exceptions or gate.called
+
+
+@with_feature_flags(PARTITION_FILTER_MAPPING=True)
+def test_a_jinja_transform_is_still_rejected(mocker: MockerFixture) -> None:
+ """
+ Skipping the gate for unparseable transforms is not a hole for templating:
+ Jinja is a blocking issue of its own, reported before the gate is reached.
+ """
+ mocker.patch("superset.commands.dataset.update.validate_stored_expression")
+ command = _mapping_command(mocker, "unix_timestamp({{ current_user_id() }})")
+
+ exceptions: list[ValidationError] = []
+ command._validate_partition_mapping(exceptions)
+
+ assert [exc.field_name for exc in exceptions] == ["partition_value_transform"]
+
+
+@with_feature_flags(PARTITION_FILTER_MAPPING=True)
+def test_a_description_only_put_survives_an_implicit_self_mapping(
+ mocker: MockerFixture,
+) -> None:
+ """
+ `fetch_metadata` could choose the partition column as the default datetime
+ column without anyone asking, and a blocking self-mapping error then made
+ the dataset unsaveable forever -- including by the very write that would
+ have set the override that fixes it, and including a write that changes
+ nothing but the description.
+
+ The mapping is inert in that state either way, since
+ `resolve_partition_mapping` bails out on it, so the issue is reported
+ rather than blocking.
+ """
+ mocker.patch("superset.commands.dataset.update.validate_stored_expression")
+ command = _mapping_command(mocker, "unix_timestamp(:value)")
+ command._model.main_dttm_col = "dt_epoch"
Review Comment:
Fixed — `pre-commit run mypy` passes on this file at the current head.
##########
tests/unit_tests/connectors/sqla/partition_mapping_test.py:
##########
@@ -0,0 +1,2512 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Unit tests for ``superset.connectors.sqla.partition_mapping``."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from decimal import Decimal
+from importlib import import_module
+from typing import Any, cast
+from unittest.mock import MagicMock, patch, PropertyMock
+
+import pandas as pd
+import pytest
+from dateutil.relativedelta import relativedelta
+from flask import Flask
+from sqlalchemy.dialects import mysql, postgresql
+
+from superset.config import DISALLOWED_SQL_FUNCTIONS
+from superset.connectors.sqla.models import SqlaTable, TableColumn
+from superset.connectors.sqla.partition_mapping import (
+ _mirror_verdict_cache_key,
+ _placeholder_is_bindable,
+ _probe_cache_key,
+ _reads_as_temporal,
+ _render_literal,
+ build_mirrored_predicates,
+ build_probe_sql,
+ contains_executable_comment,
+ contains_jinja,
+ contains_value_placeholder,
+ drop_unmapped_value_transforms,
+ equality_mirrors_safely,
+ evaluate_transform,
+ find_non_deterministic_functions,
+ grain_bucket_width,
+ GRAIN_BUCKET_WIDTHS,
+ is_bare_expression,
+ is_parseable,
+ is_transform_active,
+ is_unfinished,
+ known_mirror_verdict,
+ MappingValidationIssue,
+ mirror_operator,
+ MIRRORABLE_ALWAYS,
+ MIRRORABLE_IF_MONOTONIC,
+ mirrorable_operators,
+ parse_error_detail,
+ placeholder_is_executable,
+ probe_sql_is_evaluable,
+ probed_value_type_error,
+ RawProbeValue,
+ resolve_partition_mapping,
+ stored_expression_error,
+ validate_partition_mapping,
+ validate_transform,
+)
+from superset.constants import TimeGrain
+from superset.db_engine_specs.base import BaseEngineSpec
+from superset.db_engine_specs.oracle import OracleEngineSpec
+from superset.models.core import Database
+from superset.sql.parse import SQLStatement
+from superset.utils.core import FilterOperator, override_user
+
+
+@pytest.fixture(autouse=True)
+def real_probe_cache(app: Flask) -> Any:
+ """
+ The test app runs a null cache, which would make every cache assertion here
+ vacuously pass. Swap in a real in-memory one for the duration.
+ """
+ from flask_caching import Cache
+
+ from superset.extensions import cache_manager
+
+ cache = Cache(config={"CACHE_TYPE": "SimpleCache", "CACHE_DEFAULT_TIMEOUT": 300})
+ cache.init_app(app)
+ original = cache_manager._cache # noqa: SLF001
+ cache_manager._cache = cache # noqa: SLF001
+ yield
+ cache_manager._cache = original # noqa: SLF001
+
+
+@pytest.fixture(autouse=True)
+def enable_partition_filter_mapping(app: Flask) -> Any:
+ """The feature ships off; every test here exercises it on."""
+ original = app.config["DEFAULT_FEATURE_FLAGS"].get("PARTITION_FILTER_MAPPING")
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = True
+ yield
+ if original is None:
+ del app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"]
+ else:
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = original
+
+
+def _table(**kwargs: Any) -> SqlaTable:
+ database = Database(database_name="test_db", sqlalchemy_uri="sqlite://")
+ defaults: dict[str, Any] = {
+ "table_name": "web_events",
+ "database": database,
+ "main_dttm_col": "event_time",
+ "columns": [
+ TableColumn(column_name="event_time", is_dttm=True, type="TIMESTAMP"),
+ TableColumn(
+ column_name="dt_epoch",
+ type="BIGINT",
+ partition_value_transform=None,
+ ),
+ TableColumn(column_name="country", type="VARCHAR"),
+ TableColumn(column_name="region_key", type="VARCHAR"),
+ ],
+ }
+ defaults.update(kwargs)
+ return SqlaTable(**defaults)
+
+
+def _mapped_table(
+ *,
+ partition_column: str = "dt_epoch",
+ mapped_column: str = "event_time",
+ transform: str | None = "unix_timestamp(:value)",
+ monotonic: bool = True,
+ partition_mapped_column: str | None = None,
+ main_dttm_col: str | None = "event_time",
+) -> SqlaTable:
+ table = _table(main_dttm_col=main_dttm_col)
+ table.partition_column = partition_column
+ table.partition_mapped_column = partition_mapped_column
+ for column in table.columns:
+ if column.column_name == mapped_column:
+ column.partition_value_transform = transform
+ column.partition_transform_is_monotonic = monotonic
+ return table
+
+
+# ---------------------------------------------------------------------------
+# §2 — operator safety matrix
+# ---------------------------------------------------------------------------
+
+
+def test_equality_and_in_are_always_mirrorable() -> None:
+ """``=`` and ``IN`` are safe for any function ``T``."""
+ assert MIRRORABLE_ALWAYS == {FilterOperator.EQUALS, FilterOperator.IN}
+
+
+def test_range_operators_require_a_monotonic_transform() -> None:
+ assert MIRRORABLE_IF_MONOTONIC == {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+ }
+
+
+def test_mirrorable_operators_excludes_ranges_when_not_monotonic() -> None:
+ assert mirrorable_operators(is_monotonic=False) == MIRRORABLE_ALWAYS
+
+
+def test_mirrorable_operators_includes_ranges_when_monotonic() -> None:
+ assert mirrorable_operators(is_monotonic=True) == (
+ MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+ )
+
+
+@pytest.mark.parametrize(
+ "operator",
+ [
+ FilterOperator.NOT_EQUALS,
+ FilterOperator.NOT_IN,
+ FilterOperator.LIKE,
+ FilterOperator.ILIKE,
+ FilterOperator.NOT_LIKE,
+ FilterOperator.NOT_ILIKE,
+ FilterOperator.IS_NULL,
+ FilterOperator.IS_NOT_NULL,
+ FilterOperator.IS_TRUE,
+ FilterOperator.IS_FALSE,
+ ],
+)
+def test_negations_and_pattern_matches_are_never_mirrorable(
+ operator: FilterOperator,
+) -> None:
+ """
+ ``T`` is not injective, so ``col != v`` does **not** imply ``T(col) != T(v)``:
+ mirroring it would drop rows the original filter keeps.
+ """
+ assert operator not in mirrorable_operators(is_monotonic=True)
+
+
+def test_equality_is_dropped_when_the_engine_does_not_compare_byte_exactly() -> None:
+ """
+ "Safe for any function ``T``" reasons about value equality: ``T`` is a
+ function, so ``col = v`` gives ``T(col) = T(v)``. The engine reasons about
+ *SQL* equality, and the two part company under a case-insensitive
+ collation -- a stored ``'us'`` satisfies a filter for ``'US'`` while the
+ mirror ``hex('US')`` excludes the row, and the chart loses it silently.
+ """
+ assert mirrorable_operators(is_monotonic=False, equality_is_safe=False) == set()
+
+
+def test_ranges_survive_an_unsafe_equality() -> None:
+ """
+ Range mirroring already rests on the owner declaring ``T``
+ order-preserving with respect to the column's own order -- an assertion
+ about the very comparison semantics this gate checks for. Equality has no
+ such declaration behind it, which is why only equality is withdrawn.
+ """
+ assert (
+ mirrorable_operators(is_monotonic=True, equality_is_safe=False)
+ == MIRRORABLE_IF_MONOTONIC
+ )
+
+
+@pytest.mark.parametrize(
+ "operator,expected",
+ [
+ (FilterOperator.GREATER_THAN, FilterOperator.GREATER_THAN_OR_EQUALS),
+ (FilterOperator.LESS_THAN, FilterOperator.LESS_THAN_OR_EQUALS),
+ (
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ ),
+ (FilterOperator.LESS_THAN_OR_EQUALS, FilterOperator.LESS_THAN_OR_EQUALS),
+ (FilterOperator.EQUALS, FilterOperator.EQUALS),
+ (FilterOperator.IN, FilterOperator.IN),
+ ],
+)
+def test_a_strict_bound_mirrors_non_strictly(
+ operator: FilterOperator, expected: FilterOperator
+) -> None:
+ """
+ Order-preserving means non-decreasing, not injective, so ``col < v``
+ implies only ``T(col) <= T(v)``. A day-key transform maps a whole day onto
+ one value and a strict mirror drops the boundary bucket. The non-strict
+ cases are already safe and pass through, which is what makes applying this
+ twice harmless.
+ """
+ assert mirror_operator(operator) == expected
+
+
+def test_relaxing_a_bound_stays_inside_the_mirrorable_set() -> None:
+ """
+ The substitution is about strictness, not about which filters mirror. The
+ Explore indicator reads `mirrorable_operators`, so leaving that set alone is
+ what keeps the glyph from promising pruning the SQL does not do -- and it is
+ also what guarantees `handle_comparison_filter` is never handed an operator
+ it has no case for.
+ """
+ assert {
+ mirror_operator(operator) for operator in MIRRORABLE_IF_MONOTONIC
+ } <= MIRRORABLE_IF_MONOTONIC
+
+
+def _column(type_: str) -> TableColumn:
+ database = Database(database_name="t", sqlalchemy_uri="sqlite://")
+ table = SqlaTable(table_name="t", database=database)
+ return TableColumn(column_name="c", type=type_, table=table)
+
+
+@pytest.mark.parametrize(
+ "type_, binary, expected",
+ [
+ ("VARCHAR", True, True),
+ ("VARCHAR", False, False),
+ # Numeric and temporal comparison is exact everywhere.
+ ("BIGINT", False, True),
+ ("TIMESTAMP", False, True),
+ ("DOUBLE", False, True),
+ ],
+)
+def test_equality_mirrors_safely_only_guards_string_columns(
+ app: Flask, type_: str, binary: bool, expected: bool
+) -> None:
+ class _Spec(BaseEngineSpec):
+ binary_string_comparison = binary
+
+ with app.app_context():
+ assert equality_mirrors_safely(_column(type_), _Spec) is expected
+
+
+def test_equality_mirrors_safely_fails_closed_on_an_unresolvable_type(
+ app: Flask,
+) -> None:
+ """
+ The gate exists to stop a silent wrong answer, so a column whose type it
+ cannot read is treated as the risky case rather than waved through.
+ """
+ column = MagicMock()
+ type(column).type_generic = PropertyMock(side_effect=ValueError("no type"))
+
+ with app.app_context():
+ assert equality_mirrors_safely(column, BaseEngineSpec) is False
+
+
+def test_no_mapped_column_leaves_the_matrix_alone(app: Flask) -> None:
+ """Nothing to reason about, and the resolver bails out on it anyway."""
+ with app.app_context():
+ assert equality_mirrors_safely(None, BaseEngineSpec) is True
+
+
+@pytest.mark.parametrize(
+ "module, spec_name",
+ [
+ ("presto", "PrestoEngineSpec"),
+ ("hive", "HiveEngineSpec"),
+ ("trino", "TrinoEngineSpec"),
+ ("impala", "ImpalaEngineSpec"),
+ ("postgres", "PostgresEngineSpec"),
+ ("bigquery", "BigQueryEngineSpec"),
+ ("sqlite", "SqliteEngineSpec"),
+ ],
+)
+def test_the_byte_exact_engines_opt_in(module: str, spec_name: str) -> None:
+ """
+ The engines this feature targets compare text byte-exactly, so the gate
+ must not cost them the second canonical mapping (`lower(:value)` onto a
+ lowercased key).
+ """
+ spec = getattr(import_module(f"superset.db_engine_specs.{module}"), spec_name)
+ assert spec.binary_string_comparison is True
+
+
+@pytest.mark.parametrize("module, spec_name", [("mysql", "MySQLEngineSpec")])
+def test_a_case_insensitive_engine_does_not_opt_in(module: str, spec_name: str) -> None:
+ """
+ MySQL's default collation is `utf8mb4_0900_ai_ci`, which is exactly the
+ case the reviewer raised.
+ """
+ spec = getattr(import_module(f"superset.db_engine_specs.{module}"), spec_name)
+ assert spec.binary_string_comparison is False
+
+
+def test_the_base_spec_does_not_opt_in() -> None:
+ """A spec that has not said so does not mirror string equality."""
+ assert BaseEngineSpec.binary_string_comparison is False
+
+
+# ---------------------------------------------------------------------------
+# Time grain bucket widths
+# ---------------------------------------------------------------------------
+
+
+@pytest.mark.parametrize("grain", list(TimeGrain))
+def test_every_builtin_grain_has_a_known_bucket_width(
+ app: Flask, grain: TimeGrain
+) -> None:
+ """
+ The widening is only sound for a grain whose bucket width we know, so a
+ grain added upstream without a width here would silently stop mirroring.
+ This is the test that notices.
+ """
+ with app.app_context():
+ assert grain_bucket_width(grain.value, "sqlite") is not None
+
+
+def test_a_calendar_grain_widens_by_a_calendar_month(app: Flask) -> None:
+ """A month is not thirty days, and the month it lands in decides its width."""
+ with app.app_context():
+ width = grain_bucket_width(TimeGrain.MONTH.value, "sqlite")
+
+ assert width is not None
+ assert datetime(2026, 1, 31) + width == datetime(2026, 2, 28)
+ assert datetime(2026, 2, 1) + width == datetime(2026, 3, 1)
+
+
+def test_a_fractional_grain_has_a_width(app: Flask) -> None:
+ """
+ ``PT0.5H`` and ``P0.25Y`` are why the widths are written out rather than
+ parsed -- and the anchored week grains are intervals ``parse_duration``
+ rejects outright.
+ """
+ with app.app_context():
+ assert grain_bucket_width(TimeGrain.HALF_HOUR.value, "sqlite") == relativedelta(
+ minutes=30
+ )
+ assert grain_bucket_width(
+ TimeGrain.WEEK_ENDING_SATURDAY.value, "sqlite"
+ ) == relativedelta(days=7)
+
+
+def test_an_unknown_grain_has_no_known_width(app: Flask) -> None:
+ with app.app_context():
+ assert grain_bucket_width("P13X", "sqlite") is None
+ assert grain_bucket_width(None, "sqlite") is None
+
+
+def test_an_addon_grain_has_no_known_width(app: Flask) -> None:
+ """An operator-declared grain carries whatever duration string they typed."""
+ with app.app_context():
+ app.config["TIME_GRAIN_ADDONS"] = {"PT2S": "2 second"}
+ try:
+ assert grain_bucket_width("PT2S", "sqlite") is None
+ finally:
+ app.config["TIME_GRAIN_ADDONS"] = {}
+
+
+def test_a_builtin_grain_an_operator_redefined_has_no_known_width(
+ app: Flask,
+) -> None:
+ """
+ ``TIME_GRAIN_ADDON_EXPRESSIONS`` replaces a built-in grain's SQL for one
+ engine, so its duration no longer bounds the displacement *there* -- but it
+ still does on every other engine.
+ """
+ with app.app_context():
+ app.config["TIME_GRAIN_ADDON_EXPRESSIONS"] = {
+ "sqlite": {"P1D": "DATETIME({col}, 'start of year')"}
+ }
+ try:
+ assert grain_bucket_width(TimeGrain.DAY.value, "sqlite") is None
+ assert grain_bucket_width(TimeGrain.DAY.value, "hive") is not None
+ finally:
+ app.config["TIME_GRAIN_ADDON_EXPRESSIONS"] = {}
+
+
+def test_the_width_table_is_keyed_on_grain_durations(app: Flask) -> None:
+ """Keys are the ISO duration a filter carries, not the enum member name."""
+ assert GRAIN_BUCKET_WIDTHS[TimeGrain.DAY] == relativedelta(days=1)
+ assert set(GRAIN_BUCKET_WIDTHS) == {grain.value for grain in TimeGrain}
+
+
+# ---------------------------------------------------------------------------
+# §4.1 — resolving the effective mapping, and the defensive bail-outs
+# ---------------------------------------------------------------------------
+
+
+def test_resolve_returns_the_mapping_when_everything_lines_up(app: Flask) -> None:
+ with app.app_context():
+ mapping = resolve_partition_mapping(_mapped_table())
+
+ assert mapping is not None
+ assert mapping.partition_column == "dt_epoch"
+ assert mapping.mapped_column == "event_time"
+ assert mapping.value_transform == "unix_timestamp(:value)"
+ assert mapping.is_monotonic is True
+
+
+def test_effective_mapped_column_follows_main_dttm_col(app: Flask) -> None:
+ """No explicit override: the mapping follows the default datetime column."""
+ with app.app_context():
+ mapping = resolve_partition_mapping(_mapped_table())
+
+ assert mapping is not None
+ assert mapping.mapped_column == "event_time"
+
+
+def test_explicit_override_wins_over_main_dttm_col(app: Flask) -> None:
+ table = _mapped_table(
+ mapped_column="country",
+ transform="lower(:value)",
+ monotonic=False,
+ partition_mapped_column="country",
+ )
+ table.partition_column = "region_key"
+
+ with app.app_context():
+ mapping = resolve_partition_mapping(table)
+
+ assert mapping is not None
+ assert mapping.mapped_column == "country"
+ assert mapping.partition_column == "region_key"
+ assert mapping.is_monotonic is False
+
+
+def test_resolve_returns_none_when_the_feature_flag_is_off(app: Flask) -> None:
+ table = _mapped_table()
+ with app.app_context():
+ with patch(
+ "superset.connectors.sqla.partition_mapping.feature_flag_manager."
+ "is_feature_enabled",
+ return_value=False,
+ ):
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_without_a_partition_column(app: Flask) -> None:
+ table = _mapped_table()
+ table.partition_column = None
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_partition_column_no_longer_exists(
+ app: Flask,
+) -> None:
+ """A column sync can drop the physical partition column out from under us."""
+ table = _mapped_table()
+ table.partition_column = "dt_epoch_gone"
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_the_mapped_column_no_longer_exists(
+ app: Flask,
+) -> None:
+ table = _mapped_table(main_dttm_col="vanished")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_on_self_mapping(app: Flask) -> None:
+ """
+ ``partition_column == effective mapped column`` mirrors a column onto itself.
+ Save-time validation rejects it, but rows predating that validation exist.
+ """
+ table = _mapped_table(
+ partition_column="event_time",
+ mapped_column="event_time",
+ )
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+@pytest.mark.parametrize("transform", [None, "", " "])
+def test_resolve_returns_none_without_a_transform(
+ app: Flask, transform: str | None
+) -> None:
+ table = _mapped_table(transform=transform)
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_the_transform_lacks_the_placeholder(
+ app: Flask,
+) -> None:
+ table = _mapped_table(transform="unix_timestamp(event_time)")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_for_a_non_deterministic_transform(app: Flask) -> None:
+ """
+ The query-time gate is `is_transform_active`, the same one the Explore
+ indicator reads. Anything narrower would let a transform that reached
+ storage without passing `UpdateDatasetCommand` -- through import, or a
+ hand-written bundle -- mirror a filter with a value frozen at probe time,
+ while the editor reported the mapping as inactive and nothing on screen
+ said otherwise.
+ """
+ table = _mapped_table(transform="unix_timestamp(:value) + rand()")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_for_a_multi_expression_transform(app: Flask) -> None:
+ """A select list is not an expression; the probe cannot align its columns."""
+ table = _mapped_table(transform="lower(:value), 'x'")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_for_an_unparseable_transform(app: Flask) -> None:
+ table = _mapped_table(transform="unix_timestamp(:value")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_the_mapped_column_has_an_advanced_data_type(
+ app: Flask,
+) -> None:
+ """
+ ``translate_filter`` builds its own predicate shape from *translated* values,
+ so the ``(operator, value)`` pair the operator matrix reasons about does not
+ exist. Mirroring anyway would silently apply the wrong values (§4.1).
+ """
+ table = _mapped_table()
+ for column in table.columns:
+ if column.column_name == "event_time":
+ column.advanced_data_type = "port"
+
+ with app.app_context():
+ with patch.dict(app.config["ADVANCED_DATA_TYPES"], {"port": MagicMock()}):
+ with patch(
+ "superset.connectors.sqla.partition_mapping.feature_flag_manager."
+ "is_feature_enabled",
+ side_effect=lambda flag: (
+ flag in {"PARTITION_FILTER_MAPPING", "ENABLE_ADVANCED_DATA_TYPES"}
+ ),
+ ):
+ assert resolve_partition_mapping(table) is None
+
+
+def test_advanced_data_type_does_not_block_when_the_flag_is_off(app: Flask) -> None:
+ """An inert ``advanced_data_type`` is not a reason to skip mirroring."""
+ table = _mapped_table()
+ for column in table.columns:
+ if column.column_name == "event_time":
+ column.advanced_data_type = "port"
+
+ with app.app_context():
+ with patch(
+ "superset.connectors.sqla.partition_mapping.feature_flag_manager."
+ "is_feature_enabled",
+ side_effect=lambda flag: flag == "PARTITION_FILTER_MAPPING",
+ ):
+ assert resolve_partition_mapping(table) is not None
+
+
+# ---------------------------------------------------------------------------
+# §5 — transform inspection helpers
+# ---------------------------------------------------------------------------
+
+
+@pytest.mark.parametrize(
+ "transform,expected",
+ [
+ ("unix_timestamp(:value)", True),
+ ("lower(:value)", True),
+ ("CAST(:value AS BIGINT)", True),
+ ("unix_timestamp(event_time)", False),
+ (":values", False),
+ ("", False),
+ (None, False),
+ ],
+)
+def test_contains_value_placeholder(transform: str | None, expected: bool) -> None:
+ assert contains_value_placeholder(transform) is expected
+
+
+@pytest.mark.parametrize(
+ "transform,expected",
+ [
+ ("unix_timestamp(:value)", False),
+ ("{{ current_username() }}", True),
+ ("lower({% if x %}:value{% endif %})", True),
+ ("lower(:value) -- {# comment #}", True),
+ ],
+)
+def test_contains_jinja(transform: str, expected: bool) -> None:
+ assert contains_jinja(transform) is expected
+
+
+@pytest.mark.parametrize(
+ ("transform", "expected"),
+ [
+ ("lower(:value)", False),
+ ("lower(:value) /* an ordinary comment */", False),
+ ("lower(:value) -- a line comment", False),
+ (":value /*!50000 + 1 */", True),
+ (":value /*M!50000 + 1 */", True),
+ (":value /*! + 1 */", True),
+ ("", False),
+ (None, False),
+ ],
+)
+def test_contains_executable_comment(transform: str | None, expected: bool) -> None:
+ assert contains_executable_comment(transform) is expected
+
+
+@pytest.mark.parametrize(
+ "transform",
+ [
+ "unix_timestamp(:value)",
+ "lower(:value)",
+ "CAST(:value AS BIGINT)",
+ "date_format(:value, 'yyyyMMdd')",
+ ],
+)
+def test_pure_transforms_report_no_non_deterministic_functions(
+ transform: str,
+) -> None:
+ assert find_non_deterministic_functions(transform, "hive") == set()
+
+
+@pytest.mark.parametrize(
+ "transform,expected_name",
+ [
+ ("date_diff(:value, now())", "NOW"),
+ ("CAST(:value AS BIGINT) + rand()", "RAND"),
+ ("CAST(:value AS DATE) - current_date", "CURRENT_DATE"),
+ ],
+)
+def test_non_deterministic_functions_are_reported(
+ transform: str, expected_name: str
+) -> None:
+ """
+ The probe runs at a different moment and in a different session from the
+ chart query, and its result is cached, so anything time- or
+ randomness-dependent freezes a snapshot of probe time into the predicate.
+ """
+ assert expected_name in find_non_deterministic_functions(transform, "hive")
+
+
+def test_niladic_unix_timestamp_is_rejected_but_the_unary_form_is_not() -> None:
+ """
+ On Hive/Impala ``unix_timestamp()`` means "now" while ``unix_timestamp(x)``
+ -- the canonical temporal transform -- is pure. The distinction is the whole
+ reason this check inspects arity rather than just the name.
+ """
+ assert find_non_deterministic_functions("unix_timestamp(:value)", "hive") == set()
+ assert find_non_deterministic_functions(
+ "unix_timestamp(:value) - unix_timestamp()", "hive"
+ )
+
+
+# ---------------------------------------------------------------------------
+# §4.2 — probe evaluation
+# ---------------------------------------------------------------------------
+
+
+def _user(username: str) -> Any:
+ """A stand-in for `override_user`, which only needs `.username` here."""
+ user = MagicMock()
+ user.username = username
+ user.is_anonymous = False
+ return user
+
+
+def _database_returning(values: list[Any]) -> Database:
+ """A real ``Database`` (so the dialect is real) with only ``get_df`` stubbed."""
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ return_value=pd.DataFrame(
+ [values], columns=[f"v{i}" for i in range(len(values))]
+ )
+ )
+ return database
+
+
+def _database_returning_frame(frame: pd.DataFrame) -> Database:
+ """
+ ``_database_returning`` for a probe result whose column dtypes matter.
+
+ The flat-list sibling builds its frame from one Python list, so pandas
+ infers a single dtype and the row-versus-cell distinction cannot be seen.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ return_value=frame
+ )
+ return database
+
+
+def _probe(database: Database) -> MagicMock:
+ """
+ The stubbed ``get_df``, typed for call assertions.
+
+ ``Database.get_df`` is a real method, so mypy reads its declared signature
+ rather than the mock that replaced it and rejects ``.call_args`` and
+ friends.
+ """
+ return cast(MagicMock, database.get_df)
+
+
+def test_evaluate_transform_returns_one_value_per_input(app: Flask) -> None:
+ database = _database_returning([1767225600, 1769904000])
+
+ with app.app_context():
+ result = evaluate_transform(
+ database,
+ None,
+ "default",
+ "unix_timestamp(:value)",
+ ["2026-01-01 00:00:00", "2026-02-01 00:00:00"],
+ )
+
+ assert result == [1767225600, 1769904000]
+ _probe(database).assert_called_once()
+
+
+def test_evaluate_transform_binds_values_rather_than_interpolating(
+ app: Flask,
+) -> None:
+ """
+ Filter values are attacker-controlled (a Gamma user picks them), so they must
+ be bound and escaped, never pasted into the probe SQL.
+ """
+ database = _database_returning(["o''brien"])
+
+ with app.app_context():
+ evaluate_transform(database, None, None, "lower(:value)", ["O'Brien"])
+
+ sql = _probe(database).call_args.kwargs["sql"]
+ assert "O'Brien" not in sql
+ assert "O''Brien" in sql
+
+
+@pytest.mark.parametrize(
+ ("transform", "expected"),
+ [
+ ("lower(:value)", True),
+ ("CAST(:value AS BIGINT)", True),
+ ("date_format(:value, '%Y%m%d')", True),
+ # The cast shorthand: a trailing colon stops SQLAlchemy's bind scan.
+ (":value::bigint", False),
+ ("(:value::date)::text", False),
+ ],
+)
+def test_a_postgres_cast_shorthand_is_not_bindable(
+ transform: str, expected: bool
+) -> None:
+ """
+ `VALUE_PLACEHOLDER_RE` is `:value\b`, which matches inside `:value::bigint`.
+ SQLAlchemy's own scan ends with `(?![:\\w$])`, so the following colon stops
+ it: `text(":value::bigint")` reports a parameter named `valu`, and asking it
+ to bind `value` raises.
+
+ Pinned because the two regexes disagreeing is the whole bug: every
+ write-side gate accepted the transform and the probe then died on an
+ `ArgumentError` that `_probe` swallows.
+ """
+ assert _placeholder_is_bindable(transform) is expected
+
+
+def test_a_cast_shorthand_transform_still_probes(app: Flask) -> None:
+ """
+ The transform is valid SQL, passes every gate, and used to prune nothing:
+ `build_probe_sql` raised, `_probe` swallowed it, and the only symptom was a
+ mapping that silently never mirrored -- with the preview reporting an engine
+ failure for SQL that was never sent.
+ """
+ database = _database_returning([20260115])
+
+ with app.app_context():
+ result = evaluate_transform(
+ database, None, None, ":value::bigint", ["20260115"]
+ )
+
+ assert result == [20260115]
+ assert _probe(database).call_count == 1
+ assert "::bigint" in _probe(database).call_args.kwargs["sql"]
+
+
+def test_a_cast_shorthand_value_is_still_escaped_by_the_dialect(
+ app: Flask,
+) -> None:
+ """
+ The fallback substitutes where the bind path binds, so it has to earn the
+ same guarantee its sibling above pins: the value is rendered by the
+ dialect's literal processor, not pasted in.
+
+ Binding was only ever the vehicle for reaching that processor --
+ `_compile_literal` inlines the result either way -- so this renders first
+ and substitutes second. Same string, different order.
+ """
+ database = _database_returning(["x"])
+
+ with app.app_context():
+ evaluate_transform(database, None, None, ":value::text", ["O'Brien"])
+
+ sql = _probe(database).call_args.kwargs["sql"]
+ assert "O'Brien" not in sql
+ assert "O''Brien" in sql
+
+
+def test_evaluate_transform_dedupes_repeated_values(app: Flask) -> None:
+ """Three inputs, two distinct: the probe evaluates the transform twice."""
+ database = _database_returning(["us", "us"])
+
+ with app.app_context():
+ result = evaluate_transform(
+ database, None, None, "lower(:value)", ["US", "US", "us"]
+ )
+
+ assert result == ["us", "us", "us"]
+ sql = _probe(database).call_args.kwargs["sql"]
+ assert sql.count("lower") == 2
+
+
+def test_evaluate_transform_fails_open_on_a_short_result_row(app: Flask) -> None:
+ """A row narrower than the probe asked for means the results cannot be
+ aligned back to their inputs; pruning is skipped rather than guessed at."""
+ database = _database_returning(["us"])
+
+ with app.app_context():
+ assert (
+ evaluate_transform(database, None, None, "lower(:value)", ["US", "CA"])
+ is None
+ )
+
+
+def test_evaluate_transform_fails_open_on_a_wide_result_row(app: Flask) -> None:
+ """
+ Too many columns is the dangerous direction. A transform whose select list
+ holds two expressions returns 2N columns for N inputs, and reading the first
+ N interleaves the expressions instead of taking one per value -- a predicate
+ built from the wrong values rather than one that is merely short. A frame of
+ `('us', 'x', 'ca', 'x')` read as the first two columns would have yielded
+ `('us', 'x')` and dropped every CA row.
+
+ The transform is a perfectly ordinary `lower(:value)` and the width comes
+ from the stubbed frame, which is the only way to reach the guard: a
+ transform that really does carry two expressions -- `lower(:value), 'x'` --
+ is refused by `stored_expression_error` for not being a single expression,
+ so `get_df` is never called and `None` comes back for an unrelated reason.
+ Asserting the probe *ran* is what separates the two, and it is what makes
+ relaxing the guard from `!=` to `<` fail here rather than pass: four columns
+ for two inputs is not fewer than two.
+ """
+ database = _database_returning(["us", "x", "ca", "x"])
+
+ with app.app_context():
+ assert (
+ evaluate_transform(database, None, None, "lower(:value)", ["US", "CA"])
+ is None
+ )
+
+ assert _probe(database).call_count == 1
+
+
+def test_the_probe_select_carries_the_engine_s_from_clause(app: Flask) -> None:
+ """
+ A `SELECT` with no `FROM` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from. Without this every probe on those engines
+ raises, which `evaluate_transform` swallows -- so the only symptom is a
+ correctly configured mapping that silently never prunes.
+ """
+ assert build_probe_sql("lower(:value)", ["US"]) == "SELECT lower('US') AS v0"
+ assert build_probe_sql("lower(:value)", ["US"], None, " FROM DUAL").endswith(
+ " FROM DUAL"
+ )
+ assert OracleEngineSpec.select_without_from_suffix == " FROM DUAL"
+ assert BaseEngineSpec.select_without_from_suffix == ""
+
+
+@pytest.mark.parametrize("dialect", [mysql.dialect(), postgresql.dialect()])
+def test_the_probe_select_does_not_double_percent_signs(dialect: Any) -> None:
+ """
+ `TextClause` compilation runs the dialect's `post_process_text`, which
+ doubles every `%` on any paramstyle whose DBAPI later interpolates
+ parameters -- MySQL and Postgres, and every spec inheriting from them. The
+ probe has no such interpolation pass: it executes with no bound parameters
+ at all. Left doubled, `date_format(:value, '%Y%m%d')` asks the warehouse
+ for the literal string `%%Y%%m%%d`, so the probe returns that instead of a
+ date and the mirrored predicate drops every row the filter keeps.
+ """
+ sql = build_probe_sql("date_format(:value, '%Y%m%d')", ["2026-01-15"], dialect)
+
+ assert "'%Y%m%d'" in sql
+ assert "%%" not in sql
+
+
+def test_the_probe_select_is_unchanged_on_a_dialect_that_does_not_double() -> None:
+ """
+ Pins the no-dialect path, which is also the blind spot: the default dialect
+ does not double percent signs, so no assertion made through it can see the
+ bug the two cases above cover.
+ """
+ assert (
+ build_probe_sql("date_format(:value, '%Y%m%d')", ["2026-01-15"])
+ == "SELECT date_format('2026-01-15', '%Y%m%d') AS v0"
+ )
+
+
+def test_a_raw_probe_value_is_substituted_literally() -> None:
+ r"""
+ `RawProbeValue.sql` is rendered from a filter value, so it reaches
+ `parse_skeleton` as the *replacement* for `:value`. Read as a replacement
+ template, a backslash in it is an escape: `array('a\nb')` -- which is how a
+ dialect renders the two characters `\` and `n` -- would become a real
+ newline, so the engine is asked about a different array than the predicate
+ compares and the mirror can exclude rows the filter keeps.
+ """
+ sql = build_probe_sql("toYYYYMM(:value)", [RawProbeValue(r"array('a\nb')")])
+
+ assert sql == r"SELECT toYYYYMM(array('a\nb')) AS v0"
+
+
+def test_a_raw_probe_value_does_not_re_inject_the_placeholder() -> None:
+ r"""
+ `\g<0>` in a replacement template expands to the whole match, which would
+ put `:value` back into the probe -- an unbound parameter the engine refuses.
+ """
+ sql = build_probe_sql("toYYYYMM(:value)", [RawProbeValue(r"'a\g<0>b'")])
+
+ assert sql == r"SELECT toYYYYMM('a\g<0>b') AS v0"
+ assert ":value" not in sql
+
+
+def test_a_raw_probe_value_with_a_group_reference_does_not_raise() -> None:
+ r"""
+ `\1` is an invalid group reference for this pattern, so as a replacement
+ template it raised `re.PatternError` rather than probing anything.
+ """
+ sql = build_probe_sql("toYYYYMM(:value)", [RawProbeValue(r"'a\1b'")])
+
+ assert sql == r"SELECT toYYYYMM('a\1b') AS v0"
+
+
+def test_a_probed_literal_keeps_its_percent_sign(app: Flask) -> None:
+ """
+ The preview panel renders probed values through the same dialect, so a
+ value that merely contains a `%` would be shown doubled.
+ """
+ database = Database(database_name="pct_db", sqlalchemy_uri="postgresql://h/d")
+
+ with app.app_context():
+ assert _render_literal(database, "100%") == "'100%'"
+
+
+def test_the_probe_reads_each_cell_without_row_wide_dtype_coercion(
+ app: Flask,
+) -> None:
+ """
+ A row is a Series, so it carries one dtype across every probe column: a row
+ mixing an exact int64 with a float unifies to float64 and an integer
+ partition key above 2^53 comes back rounded. The mirror then asks for a key
+ the warehouse does not hold, and the row the filter matched is dropped.
+ """
+ database = _database_returning_frame(
+ pd.DataFrame({"v0": [9007199254740993], "v1": [1.5]})
+ )
+
+ with app.app_context():
+ probed = evaluate_transform(
+ database, None, None, "CAST(:value AS NUMERIC)", ["9007199254740993", "1.5"]
+ )
+
+ assert probed == [9007199254740993, 1.5]
+
+
+def test_evaluate_transform_pins_catalog_and_schema(app: Flask) -> None:
+ """
+ The probe runs in a different session from the chart query; pinning the
+ catalog and schema keeps session settings as close as the pool allows.
+ """
+ database = _database_returning([1])
+
+ with app.app_context():
+ evaluate_transform(database, "prod", "analytics", "lower(:value)", ["x"])
+
+ kwargs = _probe(database).call_args.kwargs
+ assert kwargs["catalog"] == "prod"
+ assert kwargs["schema"] == "analytics"
+
+
+def test_evaluate_transform_fails_open_when_the_probe_raises(app: Flask) -> None:
+ """A wedged engine must not break the chart — it just stops pruning."""
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ side_effect=RuntimeError("connection reset")
+ )
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, "lower(:value)", ["x"]) is None
+
+
+def test_evaluate_transform_fails_open_on_an_empty_result(app: Flask) -> None:
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ return_value=pd.DataFrame()
+ )
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, "lower(:value)", ["x"]) is None
+
+
+def test_evaluate_transform_returns_none_for_no_values(app: Flask) -> None:
+ database = _database_returning([])
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, "lower(:value)", []) is None
+
+ _probe(database).assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "transform",
+ [
+ "(SELECT password FROM ab_user LIMIT 1) || :value",
+ "lower(:value) UNION ALL SELECT password FROM ab_user",
+ "lower(:value); DROP TABLE ab_user",
+ "password || :value FROM ab_user",
+ "lower(:value) FROM ab_user WHERE 1 = 1",
+ ],
+ ids=[
+ "subquery",
+ "set-operation",
+ "multi-statement",
+ "bare-from",
+ "from-and-where",
+ ],
+)
+def test_a_transform_that_is_not_a_storable_expression_never_runs(
+ app: Flask, transform: str
+) -> None:
+ """
+ The probe is where a transform stops being text and becomes SQL.
+
+ `build_probe_sql` binds `:value` and splices the rest in verbatim, so a
+ transform that was never a single harmless expression is arbitrary SQL
+ against the dataset's database -- read back out of the emitted predicate
+ by anyone who can open "View query". The write-side gates refuse these,
+ but they can only speak for rows written after they existed, so the last
+ word belongs here.
+ """
+ database = _database_returning(["irrelevant"])
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, transform, ["us"]) is None
+
+ _probe(database).assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "transform, unfinished",
+ [
+ ("unix_timestamp(:value", True),
+ ("unix_timestamp(:value))", True),
+ ("unix_timestamp(:value) +", True),
+ ("unix_timestamp(:value)", False),
+ ("unix_timestamp(:value); DROP TABLE ab_user", False),
+ ("unix_timestamp(:value) UNION ALL SELECT password FROM ab_user", False),
+ ("password || :value FROM ab_user", False),
+ ],
+)
+def test_is_unfinished_separates_not_sql_yet_from_the_wrong_sql(
+ transform: str, unfinished: bool
+) -> None:
+ """
+ The two deserve opposite treatment -- a half-typed transform is stored and
+ parked inactive, the wrong SQL is refused -- and neither `is_parseable` nor
+ parsing as a single statement tells them apart, because the multi-statement
+ form fails both exactly as unfinished text does. Parsing as a script does.
+ """
+ assert is_unfinished(transform, "hive") is unfinished
+
+
+def test_a_transform_smuggling_its_own_from_clause_is_refused(app: Flask) -> None:
+ """
+ The hole this gate was added for.
+
+ `is_parseable` counts only the projection, so `password || :value FROM
+ ab_user` reads as a single select expression and passed every write-side
+ gate -- including with `ALLOW_ADHOC_SUBQUERY` off, since a top-level FROM
+ is not a sub-query. `build_probe_sql` then emitted `SELECT password || 'us'
+ AS v0 FROM ab_user`, where its own alias is read as a table alias on the
+ FROM clause the transform brought with it: valid SQL, one row, and the
+ secret handed back through the predicate the preview panel renders.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ transform = "password || :value FROM ab_user"
+
+ assert is_parseable(transform, "sqlite") is True
+ assert is_bare_expression(transform, "sqlite") is False
+
+ with app.app_context():
+ reason = stored_expression_error(database, None, None, transform)
+ assert reason is not None
+
+ blocking = _blocking(validate_transform(transform, "sqlite"))
+ assert len(blocking) == 1
+ assert "single SQL expression" in str(blocking[0].message)
+ assert is_transform_active(transform, "sqlite") is False
+
+
+def test_a_subquery_transform_is_refused_even_with_adhoc_subquery_enabled(
+ app: Flask,
+) -> None:
+ """
+ `validate_adhoc_subquery` admits a sub-query under `ALLOW_ADHOC_SUBQUERY`
+ and returns RLS-rewritten SQL -- which this path has no way to propagate,
+ because `build_probe_sql` splices the original transform text. So the probe
+ ran a sub-query with no row-level-security predicates at all and reported
+ the hidden row in `emitted_predicate`. A transform is a scalar function of
+ `:value`, so refusing the sub-query outright is both correct and what makes
+ the missing RLS rewrite moot.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ transform = "(SELECT secret FROM vault LIMIT 1) || :value"
+
+ with app.app_context():
+ app.config["DEFAULT_FEATURE_FLAGS"]["ALLOW_ADHOC_SUBQUERY"] = True
+ try:
+ reason = stored_expression_error(database, None, None, transform)
+ finally:
+ del app.config["DEFAULT_FEATURE_FLAGS"]["ALLOW_ADHOC_SUBQUERY"]
+
+ assert reason is not None
+ assert "sub-query" in reason
+
+
+@pytest.mark.parametrize(
+ "comment",
+ ["/*!50000 + (SELECT secret FROM vault LIMIT 1) */", "/*M!50000 + 1 */"],
+)
+def test_an_executable_comment_is_refused_by_every_gate(
+ app: Flask, comment: str
+) -> None:
+ """
+ The one construct that made the shape gates describe a statement the engine
+ would not run.
+
+ sqlglot reads a MySQL executable comment as comment data: the pinned parse
+ below reports no sub-query and no clause, so `stored_expression_error` and
+ `probe_sql_is_evaluable` both passed it, while MySQL and MariaDB execute
+ what is inside. An owner with dataset write and no SQL Lab could put one in
+ a transform, call the preview and read a table back out of
+ `emitted_predicate`, with no RLS on the hidden query.
+
+ Refused on every engine, not only the two that honour it -- hence SQLite
+ here. There is no legitimate transform carrying one, and a per-engine gate
+ would store on Postgres what detonates after the dataset is re-pointed.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ transform = f"(:value {comment})"
+
+ # The premise: no parse-tree gate can see it.
+ statement = SQLStatement(f"SELECT (1 {comment}) AS v0", "mysql")
+ assert statement.has_subquery() is False
+ assert statement.get_clause_names() == set()
+
+ with app.app_context():
+ assert stored_expression_error(database, None, None, transform) is not None
+
+ blocking = [
+ issue for issue in validate_transform(transform, "mysql") if issue.blocking
+ ]
+ assert len(blocking) == 1
+ assert "executable comment" in str(blocking[0].message)
+
+
+def test_an_executable_comment_stops_the_probe_before_the_engine(app: Flask) -> None:
+ """
+ The gate above is the save path. This is the row an earlier release stored:
+ `_probe` consults `stored_expression_error` on every call, so a transform
+ already in the metadata database never reaches `get_df`.
+ """
+ database = _database_returning(["x"])
+ transform = "(:value /*!50000 + (SELECT secret FROM vault LIMIT 1) */)"
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, transform, ["US"]) is None
+
+ assert _probe(database).call_count == 0
+
+
+def test_a_plain_comment_is_still_allowed_through_the_shape_gates(
+ app: Flask,
+) -> None:
+ """
+ Only the executable form is refused. An ordinary comment is inert on every
+ engine, so rejecting it would cost an owner a transform that works -- and
+ the placeholder gate already covers the case that matters, a `:value` the
+ comment swallows.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+
+ with app.app_context():
+ assert (
+ stored_expression_error(database, None, None, "lower(:value) /* ok */")
+ is None
+ )
+
+
+def test_a_transform_calling_a_disallowed_function_is_refused(app: Flask) -> None:
+ """
+ The probe executes the transform, so the operator's function denylist has
+ to apply to it for the same reason it applies in SQL Lab.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ transform = "version() || :value"
+
+ with app.app_context():
+ original = app.config["DISALLOWED_SQL_FUNCTIONS"]
+ try:
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = {"sqlite": {"version"}}
+ reason = stored_expression_error(database, None, None, transform)
+ assert reason is not None
+ assert "version" in reason
+
+ # Named, rather than echoing the operator's whole denylist back.
+ assert "current_user" not in reason
+
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = {}
+ assert stored_expression_error(database, None, None, transform) is None
+ finally:
+ # Restored: `app.config` is shared, and leaving it emptied silently
+ # disabled this gate for every test that ran afterwards.
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = original
+
+
+@pytest.mark.parametrize(
+ "function",
+ [
+ "database_to_xml",
+ "database_to_xmlschema",
+ "database_to_xml_and_xmlschema",
+ "schema_to_xml",
+ "schema_to_xmlschema",
+ "schema_to_xml_and_xmlschema",
+ "table_to_xml",
+ "table_to_xmlschema",
+ "table_to_xml_and_xmlschema",
+ "query_to_xml",
+ "query_to_xmlschema",
+ "query_to_xml_and_xmlschema",
+ ],
+)
+def test_the_whole_postgres_xml_family_is_denied_by_default(function: str) -> None:
+ """
+ These read tables with no FROM clause and no sub-query, so every gate that
+ reasons about table references is blind to them -- the denylist is the only
+ thing that can refuse them, and it has to name each shape. `schema_to_xml`
+ and three siblings were missing, so a bare scalar call cleared
+ `stored_expression_error` entirely and returned connection-user-readable
+ schema contents through preview.
+
+ Asserted against the shipped default rather than through the gate, because
+ the gap was an incomplete enumeration rather than broken wiring -- and
+ because `app.config` is ambient here, which the behavioural test below
+ handles by setting the denylist itself.
+ """
+ assert function in DISALLOWED_SQL_FUNCTIONS["postgresql"]
+
+
+def test_a_denied_read_capable_function_is_refused_despite_having_no_from(
+ app: Flask,
+) -> None:
+ """
+ The wiring half: a bare scalar call passes the length, single-statement,
+ bare-expression, sub-query and placeholder gates, so the denylist is what
+ has to stop it.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="postgresql://u@h/d")
+ transform = "schema_to_xml('public', true, false, '') || :value"
+
+ with app.app_context():
+ original = app.config["DISALLOWED_SQL_FUNCTIONS"]
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = {"postgresql": {"schema_to_xml"}}
+ try:
+ reason = stored_expression_error(database, None, None, transform)
+ finally:
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = original
+
+ assert reason is not None
+ assert "schema_to_xml" in reason
+
+
+@pytest.mark.parametrize("function", ["ts_rewrite", "ts_stat"])
+def test_the_postgres_full_text_query_functions_are_denied_by_default(
+ function: str,
+) -> None:
+ """
+ `ts_stat('select ...')` and `ts_rewrite(q, 'select ...')` run their *text*
+ argument as a query. The query is a string, so these have the same blind
+ spot the XML family above does: no FROM clause and no sub-query for a
+ table-reference gate to reason about, which leaves the denylist as the only
+ thing that can refuse them.
+ """
+ assert function in DISALLOWED_SQL_FUNCTIONS["postgresql"]
+
+
+def test_a_denied_query_running_text_function_is_refused(app: Flask) -> None:
+ """
+ The wiring half, and the only thing that proves the *name* matching works
+ for these two: neither is a function sqlglot models, so each reaches
+ `get_disallowed_functions` through its ANONYMOUS branch rather than as a
+ typed node. A denylist entry that only matched modelled functions would
+ pass the enumeration test above and still let these through.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="postgresql://u@h/d")
+ transform = "ts_stat('select 1') || :value"
+
+ with app.app_context():
+ original = app.config["DISALLOWED_SQL_FUNCTIONS"]
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = {"postgresql": {"ts_stat"}}
+ try:
+ reason = stored_expression_error(database, None, None, transform)
+ finally:
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = original
+
+ assert reason is not None
+ assert "ts_stat" in reason
+
+
+def test_the_function_denylist_is_keyed_on_the_engine_spec_name(app: Flask) -> None:
+ """
+ Every other denylist gate in the codebase keys on the engine spec's own
+ name, which is also the name the config documentation tells an operator to
+ write, so this one does too -- a spec covering several SQLAlchemy backends
+ through `engine_aliases` reports the one canonical name under which its
+ entry exists.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
Review Comment:
Fixed. The test uses an aliased engine — backend `postgres`, spec `postgresql`, asserted explicitly — so it now distinguishes the two and fails if the gate keys on `database.backend`.
##########
tests/unit_tests/connectors/sqla/partition_mapping_test.py:
##########
@@ -0,0 +1,1973 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Unit tests for ``superset.connectors.sqla.partition_mapping``."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from decimal import Decimal
+from importlib import import_module
+from typing import Any, cast
+from unittest.mock import MagicMock, patch, PropertyMock
+
+import pandas as pd
+import pytest
+from dateutil.relativedelta import relativedelta
+from flask import Flask
+from sqlalchemy.dialects import mysql, postgresql
+
+from superset.config import DISALLOWED_SQL_FUNCTIONS
+from superset.connectors.sqla.models import SqlaTable, TableColumn
+from superset.connectors.sqla.partition_mapping import (
+ _probe_cache_key,
+ _render_literal,
+ build_probe_sql,
+ contains_jinja,
+ contains_value_placeholder,
+ equality_mirrors_safely,
+ evaluate_transform,
+ find_non_deterministic_functions,
+ grain_bucket_width,
+ GRAIN_BUCKET_WIDTHS,
+ is_bare_expression,
+ is_parseable,
+ is_transform_active,
+ is_unfinished,
+ known_mirror_verdict,
+ MappingValidationIssue,
+ mirror_operator,
+ MIRRORABLE_ALWAYS,
+ MIRRORABLE_IF_MONOTONIC,
+ mirrorable_operators,
+ parse_error_detail,
+ placeholder_is_executable,
+ probe_sql_is_evaluable,
+ probed_value_type_error,
+ RawProbeValue,
+ resolve_partition_mapping,
+ stored_expression_error,
+ validate_partition_mapping,
+ validate_transform,
+)
+from superset.constants import TimeGrain
+from superset.db_engine_specs.base import BaseEngineSpec
+from superset.db_engine_specs.oracle import OracleEngineSpec
+from superset.models.core import Database
+from superset.utils.core import FilterOperator
+
+
+@pytest.fixture(autouse=True)
+def real_probe_cache(app: Flask) -> Any:
+ """
+ The test app runs a null cache, which would make every cache assertion here
+ vacuously pass. Swap in a real in-memory one for the duration.
+ """
+ from flask_caching import Cache
+
+ from superset.extensions import cache_manager
+
+ cache = Cache(config={"CACHE_TYPE": "SimpleCache", "CACHE_DEFAULT_TIMEOUT": 300})
+ cache.init_app(app)
+ original = cache_manager._cache # noqa: SLF001
+ cache_manager._cache = cache # noqa: SLF001
+ yield
+ cache_manager._cache = original # noqa: SLF001
+
+
+@pytest.fixture(autouse=True)
+def enable_partition_filter_mapping(app: Flask) -> Any:
+ """The feature ships off; every test here exercises it on."""
+ original = app.config["DEFAULT_FEATURE_FLAGS"].get("PARTITION_FILTER_MAPPING")
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = True
+ yield
+ if original is None:
+ del app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"]
+ else:
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = original
+
+
+def _table(**kwargs: Any) -> SqlaTable:
+ database = Database(database_name="test_db", sqlalchemy_uri="sqlite://")
+ defaults: dict[str, Any] = {
+ "table_name": "web_events",
+ "database": database,
+ "main_dttm_col": "event_time",
+ "columns": [
+ TableColumn(column_name="event_time", is_dttm=True, type="TIMESTAMP"),
+ TableColumn(
+ column_name="dt_epoch",
+ type="BIGINT",
+ partition_value_transform=None,
+ ),
+ TableColumn(column_name="country", type="VARCHAR"),
+ TableColumn(column_name="region_key", type="VARCHAR"),
+ ],
+ }
+ defaults.update(kwargs)
+ return SqlaTable(**defaults)
+
+
+def _mapped_table(
+ *,
+ partition_column: str = "dt_epoch",
+ mapped_column: str = "event_time",
+ transform: str | None = "unix_timestamp(:value)",
+ monotonic: bool = True,
+ partition_mapped_column: str | None = None,
+ main_dttm_col: str | None = "event_time",
+) -> SqlaTable:
+ table = _table(main_dttm_col=main_dttm_col)
+ table.partition_column = partition_column
+ table.partition_mapped_column = partition_mapped_column
+ for column in table.columns:
+ if column.column_name == mapped_column:
+ column.partition_value_transform = transform
+ column.partition_transform_is_monotonic = monotonic
+ return table
+
+
+# ---------------------------------------------------------------------------
+# §2 — operator safety matrix
+# ---------------------------------------------------------------------------
+
+
+def test_equality_and_in_are_always_mirrorable() -> None:
+ """``=`` and ``IN`` are safe for any function ``T``."""
+ assert MIRRORABLE_ALWAYS == {FilterOperator.EQUALS, FilterOperator.IN}
+
+
+def test_range_operators_require_a_monotonic_transform() -> None:
+ assert MIRRORABLE_IF_MONOTONIC == {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+ }
+
+
+def test_mirrorable_operators_excludes_ranges_when_not_monotonic() -> None:
+ assert mirrorable_operators(is_monotonic=False) == MIRRORABLE_ALWAYS
+
+
+def test_mirrorable_operators_includes_ranges_when_monotonic() -> None:
+ assert mirrorable_operators(is_monotonic=True) == (
+ MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+ )
+
+
+@pytest.mark.parametrize(
+ "operator",
+ [
+ FilterOperator.NOT_EQUALS,
+ FilterOperator.NOT_IN,
+ FilterOperator.LIKE,
+ FilterOperator.ILIKE,
+ FilterOperator.NOT_LIKE,
+ FilterOperator.NOT_ILIKE,
+ FilterOperator.IS_NULL,
+ FilterOperator.IS_NOT_NULL,
+ FilterOperator.IS_TRUE,
+ FilterOperator.IS_FALSE,
+ ],
+)
+def test_negations_and_pattern_matches_are_never_mirrorable(
+ operator: FilterOperator,
+) -> None:
+ """
+ ``T`` is not injective, so ``col != v`` does **not** imply ``T(col) != T(v)``:
+ mirroring it would drop rows the original filter keeps.
+ """
+ assert operator not in mirrorable_operators(is_monotonic=True)
+
+
+def test_equality_is_dropped_when_the_engine_does_not_compare_byte_exactly() -> None:
+ """
+ "Safe for any function ``T``" reasons about value equality: ``T`` is a
+ function, so ``col = v`` gives ``T(col) = T(v)``. The engine reasons about
+ *SQL* equality, and the two part company under a case-insensitive
+ collation -- a stored ``'us'`` satisfies a filter for ``'US'`` while the
+ mirror ``hex('US')`` excludes the row, and the chart loses it silently.
+ """
+ assert mirrorable_operators(is_monotonic=False, equality_is_safe=False) == set()
+
+
+def test_ranges_survive_an_unsafe_equality() -> None:
+ """
+ Range mirroring already rests on the owner declaring ``T``
+ order-preserving with respect to the column's own order -- an assertion
+ about the very comparison semantics this gate checks for. Equality has no
+ such declaration behind it, which is why only equality is withdrawn.
+ """
+ assert (
+ mirrorable_operators(is_monotonic=True, equality_is_safe=False)
+ == MIRRORABLE_IF_MONOTONIC
+ )
+
+
+@pytest.mark.parametrize(
+ "operator,expected",
+ [
+ (FilterOperator.GREATER_THAN, FilterOperator.GREATER_THAN_OR_EQUALS),
+ (FilterOperator.LESS_THAN, FilterOperator.LESS_THAN_OR_EQUALS),
+ (
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ ),
+ (FilterOperator.LESS_THAN_OR_EQUALS, FilterOperator.LESS_THAN_OR_EQUALS),
+ (FilterOperator.EQUALS, FilterOperator.EQUALS),
+ (FilterOperator.IN, FilterOperator.IN),
+ ],
+)
+def test_a_strict_bound_mirrors_non_strictly(
+ operator: FilterOperator, expected: FilterOperator
+) -> None:
+ """
+ Order-preserving means non-decreasing, not injective, so ``col < v``
+ implies only ``T(col) <= T(v)``. A day-key transform maps a whole day onto
+ one value and a strict mirror drops the boundary bucket. The non-strict
+ cases are already safe and pass through, which is what makes applying this
+ twice harmless.
+ """
+ assert mirror_operator(operator) == expected
+
+
+def test_relaxing_a_bound_stays_inside_the_mirrorable_set() -> None:
+ """
+ The substitution is about strictness, not about which filters mirror. The
+ Explore indicator reads `mirrorable_operators`, so leaving that set alone is
+ what keeps the glyph from promising pruning the SQL does not do -- and it is
+ also what guarantees `handle_comparison_filter` is never handed an operator
+ it has no case for.
+ """
+ assert {
+ mirror_operator(operator) for operator in MIRRORABLE_IF_MONOTONIC
+ } <= MIRRORABLE_IF_MONOTONIC
+
+
+def _column(type_: str) -> TableColumn:
+ database = Database(database_name="t", sqlalchemy_uri="sqlite://")
+ table = SqlaTable(table_name="t", database=database)
+ return TableColumn(column_name="c", type=type_, table=table)
+
+
+@pytest.mark.parametrize(
+ "type_, binary, expected",
+ [
+ ("VARCHAR", True, True),
+ ("VARCHAR", False, False),
+ # Numeric and temporal comparison is exact everywhere.
+ ("BIGINT", False, True),
+ ("TIMESTAMP", False, True),
+ ("DOUBLE", False, True),
+ ],
+)
+def test_equality_mirrors_safely_only_guards_string_columns(
+ app: Flask, type_: str, binary: bool, expected: bool
+) -> None:
+ class _Spec(BaseEngineSpec):
+ binary_string_comparison = binary
+
+ with app.app_context():
+ assert equality_mirrors_safely(_column(type_), _Spec) is expected
+
+
+def test_equality_mirrors_safely_fails_closed_on_an_unresolvable_type(
+ app: Flask,
+) -> None:
+ """
+ The gate exists to stop a silent wrong answer, so a column whose type it
+ cannot read is treated as the risky case rather than waved through.
+ """
+ column = MagicMock()
+ type(column).type_generic = PropertyMock(side_effect=ValueError("no type"))
+
+ with app.app_context():
+ assert equality_mirrors_safely(column, BaseEngineSpec) is False
+
+
+def test_no_mapped_column_leaves_the_matrix_alone(app: Flask) -> None:
+ """Nothing to reason about, and the resolver bails out on it anyway."""
+ with app.app_context():
+ assert equality_mirrors_safely(None, BaseEngineSpec) is True
+
+
+@pytest.mark.parametrize(
+ "module, spec_name",
+ [
+ ("presto", "PrestoEngineSpec"),
+ ("hive", "HiveEngineSpec"),
+ ("trino", "TrinoEngineSpec"),
+ ("impala", "ImpalaEngineSpec"),
+ ("postgres", "PostgresEngineSpec"),
+ ("bigquery", "BigQueryEngineSpec"),
+ ("sqlite", "SqliteEngineSpec"),
+ ],
+)
+def test_the_byte_exact_engines_opt_in(module: str, spec_name: str) -> None:
+ """
+ The engines this feature targets compare text byte-exactly, so the gate
+ must not cost them the second canonical mapping (`lower(:value)` onto a
+ lowercased key).
+ """
+ spec = getattr(import_module(f"superset.db_engine_specs.{module}"), spec_name)
+ assert spec.binary_string_comparison is True
+
+
+@pytest.mark.parametrize("module, spec_name", [("mysql", "MySQLEngineSpec")])
+def test_a_case_insensitive_engine_does_not_opt_in(module: str, spec_name: str) -> None:
+ """
+ MySQL's default collation is `utf8mb4_0900_ai_ci`, which is exactly the
+ case the reviewer raised.
+ """
+ spec = getattr(import_module(f"superset.db_engine_specs.{module}"), spec_name)
+ assert spec.binary_string_comparison is False
+
+
+def test_the_base_spec_does_not_opt_in() -> None:
+ """A spec that has not said so does not mirror string equality."""
+ assert BaseEngineSpec.binary_string_comparison is False
+
+
+# ---------------------------------------------------------------------------
+# Time grain bucket widths
+# ---------------------------------------------------------------------------
+
+
+@pytest.mark.parametrize("grain", list(TimeGrain))
+def test_every_builtin_grain_has_a_known_bucket_width(
+ app: Flask, grain: TimeGrain
+) -> None:
+ """
+ The widening is only sound for a grain whose bucket width we know, so a
+ grain added upstream without a width here would silently stop mirroring.
+ This is the test that notices.
+ """
+ with app.app_context():
+ assert grain_bucket_width(grain.value, "sqlite") is not None
+
+
+def test_a_calendar_grain_widens_by_a_calendar_month(app: Flask) -> None:
+ """A month is not thirty days, and the month it lands in decides its width."""
+ with app.app_context():
+ width = grain_bucket_width(TimeGrain.MONTH.value, "sqlite")
+
+ assert width is not None
+ assert datetime(2026, 1, 31) + width == datetime(2026, 2, 28)
+ assert datetime(2026, 2, 1) + width == datetime(2026, 3, 1)
+
+
+def test_a_fractional_grain_has_a_width(app: Flask) -> None:
+ """
+ ``PT0.5H`` and ``P0.25Y`` are why the widths are written out rather than
+ parsed -- and the anchored week grains are intervals ``parse_duration``
+ rejects outright.
+ """
+ with app.app_context():
+ assert grain_bucket_width(TimeGrain.HALF_HOUR.value, "sqlite") == relativedelta(
+ minutes=30
+ )
+ assert grain_bucket_width(
+ TimeGrain.WEEK_ENDING_SATURDAY.value, "sqlite"
+ ) == relativedelta(days=7)
+
+
+def test_an_unknown_grain_has_no_known_width(app: Flask) -> None:
+ with app.app_context():
+ assert grain_bucket_width("P13X", "sqlite") is None
+ assert grain_bucket_width(None, "sqlite") is None
+
+
+def test_an_addon_grain_has_no_known_width(app: Flask) -> None:
+ """An operator-declared grain carries whatever duration string they typed."""
+ with app.app_context():
+ app.config["TIME_GRAIN_ADDONS"] = {"PT2S": "2 second"}
+ try:
+ assert grain_bucket_width("PT2S", "sqlite") is None
+ finally:
+ app.config["TIME_GRAIN_ADDONS"] = {}
+
+
+def test_a_builtin_grain_an_operator_redefined_has_no_known_width(
+ app: Flask,
+) -> None:
+ """
+ ``TIME_GRAIN_ADDON_EXPRESSIONS`` replaces a built-in grain's SQL for one
+ engine, so its duration no longer bounds the displacement *there* -- but it
+ still does on every other engine.
+ """
+ with app.app_context():
+ app.config["TIME_GRAIN_ADDON_EXPRESSIONS"] = {
+ "sqlite": {"P1D": "DATETIME({col}, 'start of year')"}
+ }
+ try:
+ assert grain_bucket_width(TimeGrain.DAY.value, "sqlite") is None
+ assert grain_bucket_width(TimeGrain.DAY.value, "hive") is not None
+ finally:
+ app.config["TIME_GRAIN_ADDON_EXPRESSIONS"] = {}
+
+
+def test_the_width_table_is_keyed_on_grain_durations(app: Flask) -> None:
+ """Keys are the ISO duration a filter carries, not the enum member name."""
+ assert GRAIN_BUCKET_WIDTHS[TimeGrain.DAY] == relativedelta(days=1)
+ assert set(GRAIN_BUCKET_WIDTHS) == {grain.value for grain in TimeGrain}
+
+
+# ---------------------------------------------------------------------------
+# §4.1 — resolving the effective mapping, and the defensive bail-outs
+# ---------------------------------------------------------------------------
+
+
+def test_resolve_returns_the_mapping_when_everything_lines_up(app: Flask) -> None:
+ with app.app_context():
+ mapping = resolve_partition_mapping(_mapped_table())
+
+ assert mapping is not None
+ assert mapping.partition_column == "dt_epoch"
+ assert mapping.mapped_column == "event_time"
+ assert mapping.value_transform == "unix_timestamp(:value)"
+ assert mapping.is_monotonic is True
+
+
+def test_effective_mapped_column_follows_main_dttm_col(app: Flask) -> None:
+ """No explicit override: the mapping follows the default datetime column."""
+ with app.app_context():
+ mapping = resolve_partition_mapping(_mapped_table())
+
+ assert mapping is not None
+ assert mapping.mapped_column == "event_time"
+
+
+def test_explicit_override_wins_over_main_dttm_col(app: Flask) -> None:
+ table = _mapped_table(
+ mapped_column="country",
+ transform="lower(:value)",
+ monotonic=False,
+ partition_mapped_column="country",
+ )
+ table.partition_column = "region_key"
+
+ with app.app_context():
+ mapping = resolve_partition_mapping(table)
+
+ assert mapping is not None
+ assert mapping.mapped_column == "country"
+ assert mapping.partition_column == "region_key"
+ assert mapping.is_monotonic is False
+
+
+def test_resolve_returns_none_when_the_feature_flag_is_off(app: Flask) -> None:
+ table = _mapped_table()
+ with app.app_context():
+ with patch(
+ "superset.connectors.sqla.partition_mapping.feature_flag_manager."
+ "is_feature_enabled",
+ return_value=False,
+ ):
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_without_a_partition_column(app: Flask) -> None:
+ table = _mapped_table()
+ table.partition_column = None
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_partition_column_no_longer_exists(
+ app: Flask,
+) -> None:
+ """A column sync can drop the physical partition column out from under us."""
+ table = _mapped_table()
+ table.partition_column = "dt_epoch_gone"
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_the_mapped_column_no_longer_exists(
+ app: Flask,
+) -> None:
+ table = _mapped_table(main_dttm_col="vanished")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_on_self_mapping(app: Flask) -> None:
+ """
+ ``partition_column == effective mapped column`` mirrors a column onto itself.
+ Save-time validation rejects it, but rows predating that validation exist.
+ """
+ table = _mapped_table(
+ partition_column="event_time",
+ mapped_column="event_time",
+ )
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+@pytest.mark.parametrize("transform", [None, "", " "])
+def test_resolve_returns_none_without_a_transform(
+ app: Flask, transform: str | None
+) -> None:
+ table = _mapped_table(transform=transform)
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_the_transform_lacks_the_placeholder(
+ app: Flask,
+) -> None:
+ table = _mapped_table(transform="unix_timestamp(event_time)")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_for_a_non_deterministic_transform(app: Flask) -> None:
+ """
+ The query-time gate is `is_transform_active`, the same one the Explore
+ indicator reads. Anything narrower would let a transform that reached
+ storage without passing `UpdateDatasetCommand` -- through import, or a
+ hand-written bundle -- mirror a filter with a value frozen at probe time,
+ while the editor reported the mapping as inactive and nothing on screen
+ said otherwise.
+ """
+ table = _mapped_table(transform="unix_timestamp(:value) + rand()")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_for_a_multi_expression_transform(app: Flask) -> None:
+ """A select list is not an expression; the probe cannot align its columns."""
+ table = _mapped_table(transform="lower(:value), 'x'")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_for_an_unparseable_transform(app: Flask) -> None:
+ table = _mapped_table(transform="unix_timestamp(:value")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_the_mapped_column_has_an_advanced_data_type(
+ app: Flask,
+) -> None:
+ """
+ ``translate_filter`` builds its own predicate shape from *translated* values,
+ so the ``(operator, value)`` pair the operator matrix reasons about does not
+ exist. Mirroring anyway would silently apply the wrong values (§4.1).
+ """
+ table = _mapped_table()
+ for column in table.columns:
+ if column.column_name == "event_time":
+ column.advanced_data_type = "port"
+
+ with app.app_context():
+ with patch.dict(app.config["ADVANCED_DATA_TYPES"], {"port": MagicMock()}):
+ with patch(
+ "superset.connectors.sqla.partition_mapping.feature_flag_manager."
+ "is_feature_enabled",
+ side_effect=lambda flag: (
+ flag in {"PARTITION_FILTER_MAPPING", "ENABLE_ADVANCED_DATA_TYPES"}
+ ),
+ ):
+ assert resolve_partition_mapping(table) is None
+
+
+def test_advanced_data_type_does_not_block_when_the_flag_is_off(app: Flask) -> None:
+ """An inert ``advanced_data_type`` is not a reason to skip mirroring."""
+ table = _mapped_table()
+ for column in table.columns:
+ if column.column_name == "event_time":
+ column.advanced_data_type = "port"
+
+ with app.app_context():
+ with patch(
+ "superset.connectors.sqla.partition_mapping.feature_flag_manager."
+ "is_feature_enabled",
+ side_effect=lambda flag: flag == "PARTITION_FILTER_MAPPING",
+ ):
+ assert resolve_partition_mapping(table) is not None
+
+
+# ---------------------------------------------------------------------------
+# §5 — transform inspection helpers
+# ---------------------------------------------------------------------------
+
+
+@pytest.mark.parametrize(
+ "transform,expected",
+ [
+ ("unix_timestamp(:value)", True),
+ ("lower(:value)", True),
+ ("CAST(:value AS BIGINT)", True),
+ ("unix_timestamp(event_time)", False),
+ (":values", False),
+ ("", False),
+ (None, False),
+ ],
+)
+def test_contains_value_placeholder(transform: str | None, expected: bool) -> None:
+ assert contains_value_placeholder(transform) is expected
+
+
+@pytest.mark.parametrize(
+ "transform,expected",
+ [
+ ("unix_timestamp(:value)", False),
+ ("{{ current_username() }}", True),
+ ("lower({% if x %}:value{% endif %})", True),
+ ("lower(:value) -- {# comment #}", True),
+ ],
+)
+def test_contains_jinja(transform: str, expected: bool) -> None:
+ assert contains_jinja(transform) is expected
+
+
+@pytest.mark.parametrize(
+ "transform",
+ [
+ "unix_timestamp(:value)",
+ "lower(:value)",
+ "CAST(:value AS BIGINT)",
+ "date_format(:value, 'yyyyMMdd')",
+ ],
+)
+def test_pure_transforms_report_no_non_deterministic_functions(
+ transform: str,
+) -> None:
+ assert find_non_deterministic_functions(transform, "hive") == set()
+
+
+@pytest.mark.parametrize(
+ "transform,expected_name",
+ [
+ ("date_diff(:value, now())", "NOW"),
+ ("CAST(:value AS BIGINT) + rand()", "RAND"),
+ ("CAST(:value AS DATE) - current_date", "CURRENT_DATE"),
+ ],
+)
+def test_non_deterministic_functions_are_reported(
+ transform: str, expected_name: str
+) -> None:
+ """
+ The probe runs at a different moment and in a different session from the
+ chart query, and its result is cached, so anything time- or
+ randomness-dependent freezes a snapshot of probe time into the predicate.
+ """
+ assert expected_name in find_non_deterministic_functions(transform, "hive")
+
+
+def test_niladic_unix_timestamp_is_rejected_but_the_unary_form_is_not() -> None:
+ """
+ On Hive/Impala ``unix_timestamp()`` means "now" while ``unix_timestamp(x)``
+ -- the canonical temporal transform -- is pure. The distinction is the whole
+ reason this check inspects arity rather than just the name.
+ """
+ assert find_non_deterministic_functions("unix_timestamp(:value)", "hive") == set()
+ assert find_non_deterministic_functions(
+ "unix_timestamp(:value) - unix_timestamp()", "hive"
+ )
+
+
+# ---------------------------------------------------------------------------
+# §4.2 — probe evaluation
+# ---------------------------------------------------------------------------
+
+
+def _database_returning(values: list[Any]) -> Database:
+ """A real ``Database`` (so the dialect is real) with only ``get_df`` stubbed."""
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ return_value=pd.DataFrame(
+ [values], columns=[f"v{i}" for i in range(len(values))]
+ )
+ )
+ return database
+
+
+def _database_returning_frame(frame: pd.DataFrame) -> Database:
+ """
+ ``_database_returning`` for a probe result whose column dtypes matter.
+
+ The flat-list sibling builds its frame from one Python list, so pandas
+ infers a single dtype and the row-versus-cell distinction cannot be seen.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ return_value=frame
+ )
+ return database
+
+
+def _probe(database: Database) -> MagicMock:
+ """
+ The stubbed ``get_df``, typed for call assertions.
+
+ ``Database.get_df`` is a real method, so mypy reads its declared signature
+ rather than the mock that replaced it and rejects ``.call_args`` and
+ friends.
+ """
+ return cast(MagicMock, database.get_df)
+
+
+def test_evaluate_transform_returns_one_value_per_input(app: Flask) -> None:
+ database = _database_returning([1767225600, 1769904000])
+
+ with app.app_context():
+ result = evaluate_transform(
+ database,
+ None,
+ "default",
+ "unix_timestamp(:value)",
+ ["2026-01-01 00:00:00", "2026-02-01 00:00:00"],
+ )
+
+ assert result == [1767225600, 1769904000]
+ _probe(database).assert_called_once()
+
+
+def test_evaluate_transform_binds_values_rather_than_interpolating(
+ app: Flask,
+) -> None:
+ """
+ Filter values are attacker-controlled (a Gamma user picks them), so they must
+ be bound and escaped, never pasted into the probe SQL.
+ """
+ database = _database_returning(["o''brien"])
+
+ with app.app_context():
+ evaluate_transform(database, None, None, "lower(:value)", ["O'Brien"])
+
+ sql = _probe(database).call_args.kwargs["sql"]
+ assert "O'Brien" not in sql
+ assert "O''Brien" in sql
+
+
+def test_evaluate_transform_dedupes_repeated_values(app: Flask) -> None:
+ """Three inputs, two distinct: the probe evaluates the transform twice."""
+ database = _database_returning(["us", "us"])
+
+ with app.app_context():
+ result = evaluate_transform(
+ database, None, None, "lower(:value)", ["US", "US", "us"]
+ )
+
+ assert result == ["us", "us", "us"]
+ sql = _probe(database).call_args.kwargs["sql"]
+ assert sql.count("lower") == 2
+
+
+def test_evaluate_transform_fails_open_on_a_short_result_row(app: Flask) -> None:
+ """A row narrower than the probe asked for means the results cannot be
+ aligned back to their inputs; pruning is skipped rather than guessed at."""
+ database = _database_returning(["us"])
+
+ with app.app_context():
+ assert (
+ evaluate_transform(database, None, None, "lower(:value)", ["US", "CA"])
+ is None
+ )
+
+
+def test_evaluate_transform_fails_open_on_a_wide_result_row(app: Flask) -> None:
+ """
+ Too many columns is the dangerous direction. A transform whose select list
+ holds two expressions returns 2N columns for N inputs, and reading the first
+ N interleaves the expressions instead of taking one per value -- a predicate
+ built from the wrong values rather than one that is merely short. Here
+ `lower('US'), 'x', lower('CA'), 'x'` would have yielded `('us', 'x')` and
+ dropped every CA row.
+ """
+ database = _database_returning(["us", "x", "ca", "x"])
+
+ with app.app_context():
+ assert (
+ evaluate_transform(database, None, None, "lower(:value), 'x'", ["US", "CA"])
Review Comment:
Fixed. The test uses a valid transform so `get_df` is actually reached and the interleaving case the docstring describes is the one being asserted; changing the width guard from `!=` to `<` now fails it.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4382933576
##########
superset/commands/dataset/importers/v0.py:
##########
@@ -244,8 +256,10 @@ def import_from_dict(data: dict[str, Any], sync: Optional[list[str]] = None) ->
parsed = make_url_safe(db_obj.sqlalchemy_uri)
if parsed.password and parsed.password != PASSWORD_MASK:
db_obj.set_sqlalchemy_uri(db_obj.sqlalchemy_uri)
+ imported.extend(db_obj.tables or [])
Review Comment:
`db_obj.tables` is every dataset attached to the database, not only the ones this bundle imported, so `_repair_partition_mappings()` also runs on unrelated datasets. Importing a legacy bundle that contains only dataset B therefore sends dataset A through `clear_unmapped_partition_transforms`, which drops A's parked transform and monotonicity declaration (for example one saved while the feature flag was off). Should this collect only the datasets the import actually wrote, rather than expanding the database relationship?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,3889 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Writing the value into the probe
+--------------------------------
+The probe evaluates the transform at a *literal*, because it runs with no bound
+parameters at all -- so every value is written into SQL text by the driver's
+literal renderer and read back by the engine's lexer, and the two do not always
+agree. SQLAlchemy's default renderer doubles apostrophes and leaves backslashes
+alone; Hive honours backslash escapes and not doubling, so ``'O''Brien'`` is
+read there as two adjacent literals and ``'x\\''`` ends four characters into a
+value the filter carries whole. A disagreement is either a mirror built from a
+value nobody filtered on -- dropping rows the filter keeps -- or, where the
+value closes its own quote, an expression of the filterer's choosing running in
+the probe.
+
+Which side is right is not knowable from the driver: it is a per-session server
+setting (``standard_conforming_strings``, ``NO_BACKSLASH_ESCAPES``,
+``spark.sql.parser.escapedStringLiterals``), and SQLAlchemy's own view of it is
+only correct on a dialect that has connected. So escaping is not what makes
+this safe. `literal_round_trips` renders the literal and reads it back in the
+engine's own dialect instead, and a value that does not survive the trip is not
+mirrored -- the usual trade, pruning for correctness. `probe_sql_is_evaluable`
+re-reads the finished statement behind it.
+
+The probe's *answers* make the same trip, in the other direction. The chart
+query is compiled with ``literal_binds``, so a probed partition key is rendered
+into its SQL by the same renderer and read by the same lexer -- and
+``concat(:value, chr(92), 'b')`` turns the unremarkable input ``a`` into the key
+``a\\b``, which Hive reads back as ``a`` followed by a backspace. So
+`_predicates_from_probe` asks `literal_round_trips` about each result too, and
+declines the request rather than emitting a predicate no row can satisfy: the
+mirror is ``AND``-ed onto the query, so a mirror that matches nothing costs the
+chart its rows rather than its pruning.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Mapping, Sequence
+from dataclasses import dataclass
+from datetime import date, datetime, time, timedelta
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: The opening and closing delimiters of each kind of Jinja block. The probe
+#: would render these in a different context at a different time from the chart
+#: query, so a transform holding one is rejected at save time.
+JINJA_BLOCK_DELIMITERS = (("{{", "}}"), ("{%", "%}"), ("{#", "#}"))
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: A PostgreSQL Unicode-escaped identifier, ``U&"..."``.
+#:
+#: The second construct that breaks the premise above, and in the same way:
+#: ``U&"\\0071uery_to_xml"(...)`` parses as an anonymous function whose name is
+#: the *literal* ``\\0071uery_to_xml``, so the function denylist is matching a
+#: name the engine never sees -- PostgreSQL decodes the escape and runs
+#: ``query_to_xml``, handing a dataset owner rows from outside their RLS scope
+#: through the preview's ``emitted_predicate``.
+#:
+#: Normalizing the escapes and re-checking would be the other repair, and is
+#: worse: it means reimplementing one engine's identifier decoding well enough
+#: to be a security boundary. Refusing the construct is exact, and costs
+#: nothing real -- a transform is a scalar function of ``:value``, and there is
+#: no reason to name a function or column through an escape sequence.
+#:
+#: Refused on every engine, like the executable comment, so a transform stored
+#: on SQLite cannot detonate when the dataset is re-pointed at PostgreSQL. The
+#: ``&`` may be separated from the ``U`` by nothing at all, but whitespace or a
+#: comment between the prefix and the string is not accepted by PostgreSQL
+#: either, so the strict form is the whole surface.
+#:
+#: Matched in raw text, so the prefix is refused inside a string literal too.
+#: That is the same trade the executable comment makes and has the same
+#: justification: a gate whose contract is to fire *before* the parse cannot
+#: ask the parse whether the text was quoted. ``concat(:value, 'u&"x"')`` is
+#: refused, which costs an owner nothing anyone writes.
+UNICODE_ESCAPED_IDENTIFIER_RE = re.compile(r'\bU&"', re.IGNORECASE)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate: a transform such as
+#: ``datediff(day, :value, LOCALTIMESTAMP)`` for a relative partition key is
+#: evaluated once and then keeps emitting yesterday's answer, so the chart
+#: silently drops rows after midnight.
+#:
+#: Matched by SQL function name, so every engine's spelling of "now" has to be
+#: named -- the ANSI four were not enough. Listed rather than delegated to the
+#: engine specs because the risk is the same everywhere and a spec that had not
+#: got round to declaring its own would fail open; a name no engine has is
+#: inert, so over-listing costs nothing.
+NON_DETERMINISTIC_FUNCTIONS = {
+ # ANSI, and the engines that spell it this way.
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "LOCALTIME",
+ "LOCALTIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+ # PostgreSQL. `now()` is statement-stable; these two are not even that.
+ "CLOCK_TIMESTAMP",
+ "STATEMENT_TIMESTAMP",
+ "TIMEOFDAY",
+ # MySQL and MariaDB.
+ "CURDATE",
+ "CURTIME",
+ "SYSDATE",
+ "UTC_DATE",
+ "UTC_TIME",
+ "UTC_TIMESTAMP",
+ "UUID_SHORT",
+ # Oracle.
+ "SYSTIMESTAMP",
+ "SYS_GUID",
+ # SQL Server.
+ "GETDATE",
+ "GETUTCDATE",
+ "SYSDATETIME",
+ "SYSUTCDATETIME",
+ "SYSDATETIMEOFFSET",
+ "NEWID",
+ # BigQuery.
+ "CURRENT_DATETIME",
+ "GENERATE_UUID",
+ # Snowflake.
+ "RANDSTR",
+ "UUID_STRING",
+ # ClickHouse.
+ "NOW64",
+ "RANDCANONICAL",
+ "GENERATEUUIDV4",
+ # H2 and Derby, which the test fixtures use.
+ "RANDOM_UUID",
+}
+
+#: The wall-clock names an engine evaluates with no parentheses at all.
+#:
+#: These parse as *column references*, not functions, so the name-based walk
+#: below cannot see them: `datediff(UTC_DATE, :value)` on MySQL and
+#: `:value - SYSDATE` on Oracle both cleared the gate and froze probe time into
+#: a cached mirror.
+#:
+#: A subset of `NON_DETERMINISTIC_FUNCTIONS` rather than the whole of it,
+#: because refusing a bare name costs an owner a column genuinely called that.
+#: Only the names SQL lets you write without ``()`` are listed -- the datetime
+#: keywords -- so `rand`, `uuid` and `newid`, which always need parentheses and
+#: are plausible column names, stay out.
+BARE_WALL_CLOCK_KEYWORDS = frozenset(
+ {
+ "current_date",
+ "current_time",
+ "current_timestamp",
+ "localtime",
+ "localtimestamp",
+ "utc_date",
+ "utc_time",
+ "utc_timestamp",
+ "sysdate",
+ "systimestamp",
+ }
+)
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+class Unmirrorable:
+ """
+ A filter no mirror can stand in for, and why.
+
+ Returned by `ExploreMixin.mirror_probe_request` for a value the engine
+ compares more coarsely than the filter carries, one it cannot render as a
+ literal, one whose rendered literal the engine would not read back as the
+ same value, one in a time frame the transform would discard, or an ``IN``
+ list with a member of any of those kinds. An object rather than `None`,
+ because `None` is a filter value in its own right.
+
+ The reason rides along because the preview has to explain the decline to
+ the owner, and the two declines want different advice: "the engine compares
+ less of this value than you typed, so map a column it compares in full" is
+ sound guidance for a `DATE` column and actively misleading for an
+ offset-bearing bound on a `TIMESTAMP` one, which already is such a column.
+ Carried rather than re-derived so the preview's explanation cannot come
+ apart from the chart path's decision.
+
+ Lives here rather than beside that method so the preview can read it too:
+ `superset.models.helpers` imports this module, so these can only cross the
+ boundary in this direction. Both callers recognise the same instances -- a
+ preview that answered "valid" for a request the chart path declines is the
+ drift this is here to prevent.
+ """
+
+ __slots__ = ("reason",)
+
+ def __init__(self, reason: str) -> None:
+ self.reason = reason
+
+ def __repr__(self) -> str:
+ return f"<Unmirrorable {self.reason}>"
+
+
+#: The ordinary decline: whatever the mirror cannot be built from, with the
+#: engine's own comparison resolution as the reason an owner can act on.
+UNMIRRORABLE = Unmirrorable("resolution")
+
+#: A value carrying a UTC offset, declined whatever the column's resolution.
+#: A transform such as ``CAST(:value AS TIMESTAMP)`` drops the offset, so even
+#: an engine that compares the whole instant would be probed in the wrong
+#: frame -- which is not something mapping a different column fixes.
+UNMIRRORABLE_OFFSET = Unmirrorable("offset")
+
+#: A value the driver and the engine would not spell the same way, declined
+#: whatever the column's resolution and whatever the operator. Nothing about
+#: the column or the transform fixes it -- see `literal_round_trips` -- so the
+#: advice the resolution reason carries would send an owner after the wrong
+#: thing entirely.
+UNMIRRORABLE_ESCAPING = Unmirrorable("escaping")
+
+
+def is_unmirrorable(value: Any) -> bool:
+ """Whether `mirror_probe_request` declined this request."""
+ return isinstance(value, Unmirrorable)
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def _native_generic_type(
+ column: "TableColumn",
+) -> utils.GenericDataType | None:
+ """
+ What the engine spec makes of ``column``'s declared type.
+
+ `TableColumn.type_generic` answers ``TEMPORAL`` for every column carrying
+ ``is_dttm``, which is the right answer for a chart's time axis and the
+ wrong one for a comparison: an epoch ``BIGINT`` is a number to the engine
+ however it is labelled here. Falls back to the flag where the spec has no
+ answer, so a type Superset cannot resolve is no worse off than before.
+ """
+ try:
+ column_spec = column.db_engine_spec.get_column_spec(
+ column.type, db_extra=column.db_extra
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ column_spec = None
+ if column_spec is not None and column_spec.generic_type is not None:
+ return column_spec.generic_type
+ try:
+ return column.type_generic
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+#: A declared type naming an array: PostgreSQL's ``TEXT[]`` / ``INTEGER[][]``
+#: / ``int[3]``, and the ``ARRAY<...>`` / ``ARRAY(...)`` / ``Array(...)``
+#: spellings of Hive, Spark, Trino, BigQuery and ClickHouse.
+#: The bracket body is written so no two runs can match the same blanks:
+#: ``\s*\d*\s*`` backtracks polynomially on a long run of spaces.
+_ARRAY_TYPE_RE = re.compile(r"(?:\[\s*(?:\d+\s*)?\])+\s*$|^\s*ARRAY\b", re.IGNORECASE)
+
+
+def declares_array_type(column_type: str | None) -> bool:
+ """
+ Whether a declared column type is an array, whatever the engine spec says.
+
+ The engine spec only reports ``MULTI_VALUE`` where it has opted into
+ ``supports_multivalue_columns``; PostgreSQL has not, and resolves ``TEXT[]``
+ to ``STRING`` and ``INTEGER[]`` to ``NUMERIC``. So an array partition column
+ there cleared the array refusal, previewed valid, and every equality chart
+ on the mapping failed with ``malformed array literal``. The declared type
+ is what the engine will compare, so it is read directly as well.
+ """
+ return bool(column_type and _ARRAY_TYPE_RE.search(column_type))
+
+
+#: Declared types whose comparison ignores trailing blanks.
+#:
+#: The fixed-width character types, which the SQL standard has compare as
+#: though both sides were padded to the same length -- so ``'US'`` and
+#: ``'US '`` are equal in a ``CHARACTER(3)``, while ``lower()`` of the two is
+#: not. Spelled out rather than matched by prefix because the variable-width
+#: names start with the same letters: ``VARCHAR`` and ``CHARACTER VARYING``
+#: compare the blanks and must not land here.
+PADDED_CHARACTER_TYPES = frozenset(
+ {
+ "CHAR",
+ "NCHAR",
+ # PostgreSQL's own name for ``CHARACTER``, which is what reflection
+ # reports for a ``CHAR(n)`` column there.
+ "BPCHAR",
+ "CHARACTER",
+ "NATIONAL CHAR",
+ "NATIONAL CHARACTER",
+ }
+)
+
+
+def _is_padded_character_type(column: TableColumn) -> bool:
+ """
+ Whether ``column``'s declared type compares without its trailing blanks.
+
+ Read off the declared type rather than the engine spec's resolved one: the
+ specs map ``CHAR`` and ``VARCHAR`` onto the same `sqlalchemy.String`, so
+ the distinction this needs is gone by then. The length suffix is dropped
+ and the name matched against `PADDED_CHARACTER_TYPES`, so an unfamiliar
+ spelling answers ``False`` and the engine-level flag decides as before --
+ this gate adds a decline rather than lifting one. A column with no
+ declared type has nothing to read, and answers the same way.
+ """
+ if not isinstance(column.type, str):
+ return False
+ native = re.sub(r"\s+", " ", column.type.strip().upper())
+ return native.split("(")[0].strip() in PADDED_CHARACTER_TYPES
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ Padding is asked about per column, because it is a property of the *type*
+ rather than of the engine. ``binary_string_comparison`` speaks for an
+ engine's default text comparison, and on PostgreSQL -- which declares it
+ -- a ``CHAR(2)`` still matches a filter for ``'US '`` against a stored
+ ``'US'``, because the standard says a padded character type compares
+ without its trailing blanks. The mirror ``region_key = lower('US ')`` then
+ excludes the row. So a fixed-width character type declines whatever the
+ engine says, and an engine that ignores trailing blanks on its *variable*
+ types says so by not declaring the flag at all (see `RedshiftEngineSpec`).
+
+ The type asked for is the engine spec's reading of the column's declared
+ type, not `TableColumn.type_generic`, which answers ``TEMPORAL`` for
+ anything carrying ``is_dttm``. A ``VARCHAR`` flagged temporal is still text
+ to the engine: on MySQL a filter for ``'2026-01-01T00:00:00'`` matches a
+ stored ``'...t00:00:00'``, while the mirror ``p = hex('...T...')`` excludes
+ it -- and asking the semantic flag skipped the check entirely.
+
+ A type the spec cannot classify declines, which is what the paragraph above
+ promises and what only the exception branch used to do. PostgreSQL's
+ ``citext`` matches no type pattern, so it answered ``None`` -- neither
+ string nor not-string -- and was waved through, which is precisely wrong
+ for a type whose whole purpose is case-insensitive comparison. Declining
+ costs the pruning; admitting it costs rows.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ # Ahead of the generic-type question, which a padded type can lose: the
+ # specs map ``CHARACTER`` onto no generic type at all on some engines, and
+ # a fixed-width character type is a string whether or not Superset can say
+ # so from the name.
+ if _is_padded_character_type(column):
+ return False
+ generic_type = _native_generic_type(column)
+ if generic_type is None:
+ return False
+ if generic_type != utils.GenericDataType.STRING:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_unicode_escaped_identifier(transform: str | None) -> bool:
+ """Whether the transform names something through a ``U&"..."`` escape.
+
+ See `UNICODE_ESCAPED_IDENTIFIER_RE`. Answered on raw text for the same
+ reason as the comment above: the parse reports a name the engine does not
+ use, which is exactly what makes the denylist blind to it.
+ """
+ return (
+ bool(transform)
+ and UNICODE_ESCAPED_IDENTIFIER_RE.search(transform or "") is not None
+ )
+
+
+#: Sequence pseudo-columns, which advance a sequence when they are *read*.
+#:
+#: ``orders_seq.NEXTVAL`` parses as a qualified column reference, not a
+#: function call, so neither `SQLStatement.is_mutating` -- which walks function
+#: names -- nor the function denylist can see it. The probe would then run
+#: ``SELECT orders_seq.NEXTVAL + 1 FROM DUAL`` and advance the sequence, again
+#: on every cache expiry, for a dataset editor holding neither SQL Lab nor a
+#: DML grant. Reading one is a write however the parser classifies it.
+#:
+#: The function spelling (``nextval('s')`` on PostgreSQL) is a different shape
+#: and is caught as a function; this is only about the suffix form.
+SEQUENCE_PSEUDO_COLUMNS = frozenset({"nextval", "currval"})
+
+#: The same thing written as a call.
+#:
+#: Only the suffix form parses as a column; `nextval('s')` on PostgreSQL and
+#: DuckDB, `NEXTVAL(s)`/`SETVAL(s, 1)` on MySQL and MariaDB, and SQL Server's
+#: `NEXT VALUE FOR s` all parse as functions. `SQLStatement.is_mutating` walks
+#: function names on PostgreSQL alone -- deliberately, since the same names are
+#: read-only elsewhere -- so every other engine let these through.
+#:
+#: Matched on the name whatever the engine, because advancing a sequence is a
+#: write wherever it happens and a transform has no reason to call one.
+SEQUENCE_FUNCTIONS = frozenset(
+ {"nextval", "setval", "next_value_for", "nextvalfor", "prevval", "lastval"}
+)
+
+
+def references_sequence(statement: SQLStatement) -> bool:
+ """Whether the statement reads or advances a sequence.
+
+ Both spellings: the pseudo-column suffix, which parses as a column (see
+ `SEQUENCE_PSEUDO_COLUMNS`), and the call, which parses as a function (see
+ `SEQUENCE_FUNCTIONS`).
+
+ Answered on the parse rather than on raw text, because position is what
+ makes it the construct: a column or alias merely *called* ``nextval`` is
+ an ordinary column, and a string literal holding the word is text.
+ """
+ return bool(
+ statement.get_column_names() & SEQUENCE_PSEUDO_COLUMNS
+ or statement.get_disallowed_functions(set(SEQUENCE_FUNCTIONS))
+ )
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """
+ Whether the transform contains a balanced Jinja block.
+
+ A block is an opening delimiter followed, anywhere later, by its closing
+ one -- the same thing ``{{.*?}}`` and its two siblings match under
+ ``re.DOTALL``. Scanned with `str.find` rather than that pattern, because a
+ lazy match retried from every opening delimiter is quadratic in a run of
+ them, and this runs on stored transforms with no length bound of its own:
+ `is_transform_active` reads whatever the column holds. The earliest opening
+ delimiter is the only one worth trying, since any closing delimiter after a
+ later one is also after it.
+ """
+ if not transform:
+ return False
+ for opening, closing in JINJA_BLOCK_DELIMITERS:
+ start = transform.find(opening)
+ if start != -1 and transform.find(closing, start + len(opening)) != -1:
+ return True
+ return False
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+
+ Three spellings have to be looked for, because one name reaches the parse
+ three ways: as a function call, as a zero-argument call a dialect resolves
+ itself, and -- for the datetime keywords -- as a bare word that parses as a
+ column reference.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ # The parenthesis-free spellings, which parse as columns rather than
+ # functions and so are invisible to the walk above. See
+ # `BARE_WALL_CLOCK_KEYWORDS`.
+ found |= {
+ name.upper() for name in BARE_WALL_CLOCK_KEYWORDS & statement.get_column_names()
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ # An array holds no scalar a transform could return, so no mirror onto it
+ # can ever compare. Refused for the mapping rather than only per value, so
+ # the Explore glyph stops promising one: a probe of ``:value`` succeeds and
+ # records a working transform, and only the later type gate declined.
+ if declares_array_type(columns_by_name[partition_column].type):
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error( # noqa: C901
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ And it must be a *read*. Shape is a separate question from effect: a bare
+ scalar expression can still write, so `SQLStatement.is_mutating` is asked
+ too -- the same question SQL Lab and the chart executor ask before letting
+ SQL run. See the gate itself for what that reaches and what it does not.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ # Also ahead of the parse, and for a stronger reason than cost: every gate
+ # below reasons about the parse tree, and this is the one construct that
+ # makes the parse tree describe a different statement from the one the
+ # engine runs. Checked here as well as in `validate_transform` because this
+ # is the door a row written by an earlier release still comes through.
+ if contains_executable_comment(transform):
+ return str(
+ _(
+ "A partition value transform cannot contain a MySQL "
+ "executable comment, which the database executes and every "
+ "validator reads as a comment."
+ )
+ )
+
+ if contains_unicode_escaped_identifier(transform):
+ return str(
+ _(
+ "A partition value transform cannot name anything through a "
+ 'U&"..." escape sequence, which the database decodes and '
+ "every validator reads literally."
+ )
+ )
+
+ # Same door, same reason: the name the denylist below would match is not
+ # the name the engine resolves. See `UNICODE_ESCAPED_IDENTIFIER_RE`.
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The read-only gate, which nothing above implies. The shape gates ask what
+ # the transform *selects*; this asks what evaluating it *does*, and a bare
+ # scalar expression can still write. `nextval(:value)` on PostgreSQL
+ # advances a sequence: one function call, no clause, no sub-query, and not
+ # in the default `DISALLOWED_SQL_FUNCTIONS` either -- so every gate above
+ # passes it and the probe then runs it. `setval` is the same shape, and
+ # `exp.Execute` and the opaque-`exp.Command` forms arrive the same way.
+ #
+ # The large-object writers (`lo_export`, `lowrite`, `lo_from_bytea`, ...)
+ # are caught here too, and the shipped denylist happens to name them as
+ # well -- but that is config an operator can replace, while this is not.
+ #
+ # `is_mutating` is the same question SQL Lab, `get_virtual_table_metadata`
+ # and the chart executor ask before letting SQL run, so a transform is held
+ # to the bar the rest of Superset already sets rather than to one invented
+ # here. Unconditional rather than gated on `Database.allow_dml`: a transform
+ # is a scalar function of `:value` by definition, so there is no legitimate
+ # mutating one, and the probe runs on a cache schedule nobody chose -- a
+ # write would repeat every time the entry expired.
+ #
+ # It bears saying what this does not reach. A user-defined function whose
+ # body writes is a plain call no parser can tell from `lower(:value)`, and
+ # `is_mutating`'s function-name walk is PostgreSQL-only by design, since the
+ # same names are read-only elsewhere. Neither residual is specific to this
+ # feature -- a dataset editor can already have the engine evaluate an
+ # arbitrary expression through a calculated column or a virtual dataset's
+ # SQL -- and closing them means authorizing the preview against the
+ # database, not parsing harder.
+ if statement.is_mutating():
+ return str(
+ _(
+ "A partition value transform cannot change data. It is "
+ "evaluated against the database to check that it mirrors, so "
+ "it has to be a read."
+ )
+ )
+
+ # Not reached by the walk above, which is why it is its own gate: a
+ # sequence pseudo-column is a *column* to the parser and a write to the
+ # engine. See `SEQUENCE_PSEUDO_COLUMNS`.
+ if references_sequence(statement):
+ return str(
+ _(
+ "A partition value transform cannot read a sequence. "
+ "NEXTVAL advances the sequence every time it is evaluated, "
+ "and the transform is evaluated on a cache schedule."
+ )
+ )
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the
+ probe uninspected. Rendering is not what makes that true: a string element
+ is checked by `literal_round_trips` before it is rendered -- the dialect's
+ literal processor and the engine's lexer do not always agree about what a
+ rendered literal says -- and `probe_sql_is_evaluable` re-reads the finished
+ query, which is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def _placeholder_is_bindable(transform: str) -> bool:
+ """
+ Whether SQLAlchemy's ``text()`` can see ``:value`` as a bound parameter.
+
+ `VALUE_PLACEHOLDER_RE` is ``:value\b``, which matches the placeholder in a
+ Postgres cast such as ``:value::bigint``. SQLAlchemy's own bind scan is
+ ``(?<![:\\w$]):([\\w$]+)(?![:\\w$])`` -- note the trailing exclusion -- so a
+ following colon stops it: ``text(":value::bigint")`` reports a parameter
+ named ``valu``, and ``.bindparams(bindparam("value"))`` then raises
+ ``ArgumentError``.
+
+ `_probe` swallows that, so the only symptom was a perfectly valid transform
+ whose mapping silently never pruned, and a preview reporting an engine
+ failure for SQL that was never sent. Every write-side gate passes the
+ transform: it parses, it is a bare expression, and the placeholder *is* in
+ an executable position.
+
+ Answered by attempting the bind itself rather than by pattern-matching
+ ``::`` or reading ``text()``'s private parameter map, so this cannot
+ disagree with what `build_probe_sql` is about to do -- on any dialect, or on
+ a SQLAlchemy whose scan changes.
+ """
+ try:
+ sa.text(transform).bindparams(sa.bindparam("value", value=None))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return False
+ return True
+
+
+def escape_foreign_colons(transform: str) -> str:
+ """
+ ``transform`` with every colon but the ``:value`` placeholder escaped.
+
+ `sqlalchemy.text` reads any ``:word`` as a bind parameter, including one
+ inside a string literal, and an unbound parameter renders as ``NULL``
+ under literal binds rather than raising. So ``:value || \':suffix\'``
+ compiled to ``'us' || 'NULL'``: the mirror asked for a partition value no
+ row holds and the chart dropped rows, with no error for `_probe` to
+ swallow and nothing on screen to say so.
+
+ Escaped rather than refused, because a colon in a literal is ordinary --
+ ``concat(:value, \':\', region)`` builds a composite key -- and the
+ placeholder is the only colon this module means to interpret. `text()`
+ reads ``\\:`` as a literal colon.
+
+ Only the bound path needs this. A `RawProbeValue` or an unbindable
+ placeholder is substituted as text by `parse_skeleton`, which never hands
+ the transform to `text()` at all.
+ """
+ pieces: list[str] = []
+ cursor = 0
+ for match in VALUE_PLACEHOLDER_RE.finditer(transform):
+ pieces.append(transform[cursor : match.start()].replace(":", r"\:"))
+ pieces.append(match.group(0))
+ cursor = match.end()
+ pieces.append(transform[cursor:].replace(":", r"\:"))
+ return "".join(pieces)
+
+
+def literal_round_trips(value: Any, dialect: Dialect | None, engine: str) -> bool:
+ """
+ Whether the engine reads a rendered ``value`` back as that same value.
+
+ The probe runs with no bound parameters, so every value reaches the engine
+ as literal text the driver wrote (see `build_probe_sql`). Whether that text
+ says what the value says is a question about two independent spellings: the
+ driver's escaping, and the engine's lexer. SQLAlchemy's default renderer
+ doubles apostrophes and passes backslashes through; Hive and Spark honour
+ the backslash and not the doubling, so ``'O''Brien'`` is read there as two
+ adjacent literals -- the transform is evaluated at ``OBrien``, and the
+ mirror asks for a partition key that holds none of the rows the filter
+ keeps. The same gap in the other direction lets a value close its own quote
+ and have the rest of it read as SQL.
+
+ Escaping is not the repair. Whether a backslash introduces an escape is a
+ per-session server setting -- ``standard_conforming_strings`` on Postgres,
+ ``NO_BACKSLASH_ESCAPES`` on MySQL, ``escapedStringLiterals`` on Spark -- and
+ nothing in the engine specs exposes it. SQLAlchemy reads it off the server
+ into ``_backslash_escapes`` during ``initialize(connection)``, which the
+ probe's dialect never reaches: `_dialect_for` asks the ``Database`` for a
+ dialect, not for a connection, so Postgres renders ``a\\b`` as
+ ``'a\\\\b'`` and a server with the standard setting reads four
+ characters. An engine-spec flag would have to be defaulted, and either
+ default is wrong for a dozen engines: one leaves the hole open, the other
+ corrupts the probed value.
+
+ So the premise is verified rather than declared, the way
+ `probe_sql_is_evaluable` verifies the finished statement. A value that does
+ not survive the round trip is not mirrored, which costs the query its
+ pruning and nothing else.
+
+ The short-circuit is a proof, not a guess, and it matters for cost: a
+ 200-member ``IN`` list would otherwise parse 200 times on the chart path.
+ If the renderer emitted the value between two quotes and changed nothing in
+ it, and the value carries neither a quote nor a backslash, then no lexer in
+ play can read it as anything but itself. Both exclusions are load-bearing:
+ on Hive ``a\\b`` renders verbatim and reads as ``a`` followed by a
+ backspace.
+
+ :param value: a filter value about to be rendered into the probe
+ :param dialect: the dialect that will render it, as `_dialect_for` reports
+ :param engine: ``database.backend``, whose lexer reads the result
+ :return: whether the two agree about what the literal says
+ """
+ if isinstance(value, RawProbeValue):
+ # Already SQL, with no single value for a parse to be compared against:
+ # its elements are checked before they are rendered, by
+ # `ExploreMixin._array_mirror_probe_value`. A backslash surviving into
+ # the finished text is refused here all the same, as the backstop for a
+ # renderer this module does not own.
+ return "\\" not in value.sql
+ if not isinstance(value, str):
+ # Numbers and instants are not written between delimiters, so there is
+ # no escaping for the two sides to disagree about.
+ return True
+
+ rendered = _compile_literal(sa.literal(value), dialect)
+ if rendered == f"'{value}'" and "'" not in value and "\\" not in value:
Review Comment:
A probe result containing a NUL passes this short-circuit, since it has no quote or backslash and renders as `'<value>'` unchanged. On SQLite, mapping text column `c` to text partition column `p` with `:value || char(0)` returns `'a\x00'` for `c = 'a'`; the guard accepts it, and the mirrored statement then fails with `ProgrammingError: the query contains a null character`, so the chart errors instead of just losing pruning. Should a value containing `\x00` be treated as not round-tripping here?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "geido (via GitHub)" <gi...@apache.org>.
geido commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4387401237
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,3889 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Writing the value into the probe
+--------------------------------
+The probe evaluates the transform at a *literal*, because it runs with no bound
+parameters at all -- so every value is written into SQL text by the driver's
+literal renderer and read back by the engine's lexer, and the two do not always
+agree. SQLAlchemy's default renderer doubles apostrophes and leaves backslashes
+alone; Hive honours backslash escapes and not doubling, so ``'O''Brien'`` is
+read there as two adjacent literals and ``'x\\''`` ends four characters into a
+value the filter carries whole. A disagreement is either a mirror built from a
+value nobody filtered on -- dropping rows the filter keeps -- or, where the
+value closes its own quote, an expression of the filterer's choosing running in
+the probe.
+
+Which side is right is not knowable from the driver: it is a per-session server
+setting (``standard_conforming_strings``, ``NO_BACKSLASH_ESCAPES``,
+``spark.sql.parser.escapedStringLiterals``), and SQLAlchemy's own view of it is
+only correct on a dialect that has connected. So escaping is not what makes
+this safe. `literal_round_trips` renders the literal and reads it back in the
+engine's own dialect instead, and a value that does not survive the trip is not
+mirrored -- the usual trade, pruning for correctness. `probe_sql_is_evaluable`
+re-reads the finished statement behind it.
+
+The probe's *answers* make the same trip, in the other direction. The chart
+query is compiled with ``literal_binds``, so a probed partition key is rendered
+into its SQL by the same renderer and read by the same lexer -- and
+``concat(:value, chr(92), 'b')`` turns the unremarkable input ``a`` into the key
+``a\\b``, which Hive reads back as ``a`` followed by a backspace. So
+`_predicates_from_probe` asks `literal_round_trips` about each result too, and
+declines the request rather than emitting a predicate no row can satisfy: the
+mirror is ``AND``-ed onto the query, so a mirror that matches nothing costs the
+chart its rows rather than its pruning.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Mapping, Sequence
+from dataclasses import dataclass
+from datetime import date, datetime, time, timedelta
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: The opening and closing delimiters of each kind of Jinja block. The probe
+#: would render these in a different context at a different time from the chart
+#: query, so a transform holding one is rejected at save time.
+JINJA_BLOCK_DELIMITERS = (("{{", "}}"), ("{%", "%}"), ("{#", "#}"))
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: A PostgreSQL Unicode-escaped identifier, ``U&"..."``.
+#:
+#: The second construct that breaks the premise above, and in the same way:
+#: ``U&"\\0071uery_to_xml"(...)`` parses as an anonymous function whose name is
+#: the *literal* ``\\0071uery_to_xml``, so the function denylist is matching a
+#: name the engine never sees -- PostgreSQL decodes the escape and runs
+#: ``query_to_xml``, handing a dataset owner rows from outside their RLS scope
+#: through the preview's ``emitted_predicate``.
+#:
+#: Normalizing the escapes and re-checking would be the other repair, and is
+#: worse: it means reimplementing one engine's identifier decoding well enough
+#: to be a security boundary. Refusing the construct is exact, and costs
+#: nothing real -- a transform is a scalar function of ``:value``, and there is
+#: no reason to name a function or column through an escape sequence.
+#:
+#: Refused on every engine, like the executable comment, so a transform stored
+#: on SQLite cannot detonate when the dataset is re-pointed at PostgreSQL. The
+#: ``&`` may be separated from the ``U`` by nothing at all, but whitespace or a
+#: comment between the prefix and the string is not accepted by PostgreSQL
+#: either, so the strict form is the whole surface.
+#:
+#: Matched in raw text, so the prefix is refused inside a string literal too.
+#: That is the same trade the executable comment makes and has the same
+#: justification: a gate whose contract is to fire *before* the parse cannot
+#: ask the parse whether the text was quoted. ``concat(:value, 'u&"x"')`` is
+#: refused, which costs an owner nothing anyone writes.
+UNICODE_ESCAPED_IDENTIFIER_RE = re.compile(r'\bU&"', re.IGNORECASE)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate: a transform such as
+#: ``datediff(day, :value, LOCALTIMESTAMP)`` for a relative partition key is
+#: evaluated once and then keeps emitting yesterday's answer, so the chart
+#: silently drops rows after midnight.
+#:
+#: Matched by SQL function name, so every engine's spelling of "now" has to be
+#: named -- the ANSI four were not enough. Listed rather than delegated to the
+#: engine specs because the risk is the same everywhere and a spec that had not
+#: got round to declaring its own would fail open; a name no engine has is
+#: inert, so over-listing costs nothing.
+NON_DETERMINISTIC_FUNCTIONS = {
+ # ANSI, and the engines that spell it this way.
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "LOCALTIME",
+ "LOCALTIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+ # PostgreSQL. `now()` is statement-stable; these two are not even that.
+ "CLOCK_TIMESTAMP",
+ "STATEMENT_TIMESTAMP",
+ "TIMEOFDAY",
+ # MySQL and MariaDB.
+ "CURDATE",
+ "CURTIME",
+ "SYSDATE",
+ "UTC_DATE",
+ "UTC_TIME",
+ "UTC_TIMESTAMP",
+ "UUID_SHORT",
+ # Oracle.
+ "SYSTIMESTAMP",
+ "SYS_GUID",
+ # SQL Server.
+ "GETDATE",
+ "GETUTCDATE",
+ "SYSDATETIME",
+ "SYSUTCDATETIME",
+ "SYSDATETIMEOFFSET",
+ "NEWID",
+ # BigQuery.
+ "CURRENT_DATETIME",
+ "GENERATE_UUID",
+ # Snowflake.
+ "RANDSTR",
+ "UUID_STRING",
+ # ClickHouse.
+ "NOW64",
+ "RANDCANONICAL",
+ "GENERATEUUIDV4",
+ # H2 and Derby, which the test fixtures use.
+ "RANDOM_UUID",
+}
+
+#: The wall-clock names an engine evaluates with no parentheses at all.
+#:
+#: These parse as *column references*, not functions, so the name-based walk
+#: below cannot see them: `datediff(UTC_DATE, :value)` on MySQL and
+#: `:value - SYSDATE` on Oracle both cleared the gate and froze probe time into
+#: a cached mirror.
+#:
+#: A subset of `NON_DETERMINISTIC_FUNCTIONS` rather than the whole of it,
+#: because refusing a bare name costs an owner a column genuinely called that.
+#: Only the names SQL lets you write without ``()`` are listed -- the datetime
+#: keywords -- so `rand`, `uuid` and `newid`, which always need parentheses and
+#: are plausible column names, stay out.
+BARE_WALL_CLOCK_KEYWORDS = frozenset(
+ {
+ "current_date",
+ "current_time",
+ "current_timestamp",
+ "localtime",
+ "localtimestamp",
+ "utc_date",
+ "utc_time",
+ "utc_timestamp",
+ "sysdate",
+ "systimestamp",
+ }
+)
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+class Unmirrorable:
+ """
+ A filter no mirror can stand in for, and why.
+
+ Returned by `ExploreMixin.mirror_probe_request` for a value the engine
+ compares more coarsely than the filter carries, one it cannot render as a
+ literal, one whose rendered literal the engine would not read back as the
+ same value, one in a time frame the transform would discard, or an ``IN``
+ list with a member of any of those kinds. An object rather than `None`,
+ because `None` is a filter value in its own right.
+
+ The reason rides along because the preview has to explain the decline to
+ the owner, and the two declines want different advice: "the engine compares
+ less of this value than you typed, so map a column it compares in full" is
+ sound guidance for a `DATE` column and actively misleading for an
+ offset-bearing bound on a `TIMESTAMP` one, which already is such a column.
+ Carried rather than re-derived so the preview's explanation cannot come
+ apart from the chart path's decision.
+
+ Lives here rather than beside that method so the preview can read it too:
+ `superset.models.helpers` imports this module, so these can only cross the
+ boundary in this direction. Both callers recognise the same instances -- a
+ preview that answered "valid" for a request the chart path declines is the
+ drift this is here to prevent.
+ """
+
+ __slots__ = ("reason",)
+
+ def __init__(self, reason: str) -> None:
+ self.reason = reason
+
+ def __repr__(self) -> str:
+ return f"<Unmirrorable {self.reason}>"
+
+
+#: The ordinary decline: whatever the mirror cannot be built from, with the
+#: engine's own comparison resolution as the reason an owner can act on.
+UNMIRRORABLE = Unmirrorable("resolution")
+
+#: A value carrying a UTC offset, declined whatever the column's resolution.
+#: A transform such as ``CAST(:value AS TIMESTAMP)`` drops the offset, so even
+#: an engine that compares the whole instant would be probed in the wrong
+#: frame -- which is not something mapping a different column fixes.
+UNMIRRORABLE_OFFSET = Unmirrorable("offset")
+
+#: A value the driver and the engine would not spell the same way, declined
+#: whatever the column's resolution and whatever the operator. Nothing about
+#: the column or the transform fixes it -- see `literal_round_trips` -- so the
+#: advice the resolution reason carries would send an owner after the wrong
+#: thing entirely.
+UNMIRRORABLE_ESCAPING = Unmirrorable("escaping")
+
+
+def is_unmirrorable(value: Any) -> bool:
+ """Whether `mirror_probe_request` declined this request."""
+ return isinstance(value, Unmirrorable)
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def _native_generic_type(
+ column: "TableColumn",
+) -> utils.GenericDataType | None:
+ """
+ What the engine spec makes of ``column``'s declared type.
+
+ `TableColumn.type_generic` answers ``TEMPORAL`` for every column carrying
+ ``is_dttm``, which is the right answer for a chart's time axis and the
+ wrong one for a comparison: an epoch ``BIGINT`` is a number to the engine
+ however it is labelled here. Falls back to the flag where the spec has no
+ answer, so a type Superset cannot resolve is no worse off than before.
+ """
+ try:
+ column_spec = column.db_engine_spec.get_column_spec(
+ column.type, db_extra=column.db_extra
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ column_spec = None
+ if column_spec is not None and column_spec.generic_type is not None:
+ return column_spec.generic_type
+ try:
+ return column.type_generic
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+#: A declared type naming an array: PostgreSQL's ``TEXT[]`` / ``INTEGER[][]``
+#: / ``int[3]``, and the ``ARRAY<...>`` / ``ARRAY(...)`` / ``Array(...)``
+#: spellings of Hive, Spark, Trino, BigQuery and ClickHouse.
+#: The bracket body is written so no two runs can match the same blanks:
+#: ``\s*\d*\s*`` backtracks polynomially on a long run of spaces.
+_ARRAY_TYPE_RE = re.compile(r"(?:\[\s*(?:\d+\s*)?\])+\s*$|^\s*ARRAY\b", re.IGNORECASE)
+
+
+def declares_array_type(column_type: str | None) -> bool:
+ """
+ Whether a declared column type is an array, whatever the engine spec says.
+
+ The engine spec only reports ``MULTI_VALUE`` where it has opted into
+ ``supports_multivalue_columns``; PostgreSQL has not, and resolves ``TEXT[]``
+ to ``STRING`` and ``INTEGER[]`` to ``NUMERIC``. So an array partition column
+ there cleared the array refusal, previewed valid, and every equality chart
+ on the mapping failed with ``malformed array literal``. The declared type
+ is what the engine will compare, so it is read directly as well.
+ """
+ return bool(column_type and _ARRAY_TYPE_RE.search(column_type))
+
+
+#: Declared types whose comparison ignores trailing blanks.
+#:
+#: The fixed-width character types, which the SQL standard has compare as
+#: though both sides were padded to the same length -- so ``'US'`` and
+#: ``'US '`` are equal in a ``CHARACTER(3)``, while ``lower()`` of the two is
+#: not. Spelled out rather than matched by prefix because the variable-width
+#: names start with the same letters: ``VARCHAR`` and ``CHARACTER VARYING``
+#: compare the blanks and must not land here.
+PADDED_CHARACTER_TYPES = frozenset(
+ {
+ "CHAR",
+ "NCHAR",
+ # PostgreSQL's own name for ``CHARACTER``, which is what reflection
+ # reports for a ``CHAR(n)`` column there.
+ "BPCHAR",
+ "CHARACTER",
+ "NATIONAL CHAR",
+ "NATIONAL CHARACTER",
+ }
+)
+
+
+def _is_padded_character_type(column: TableColumn) -> bool:
+ """
+ Whether ``column``'s declared type compares without its trailing blanks.
+
+ Read off the declared type rather than the engine spec's resolved one: the
+ specs map ``CHAR`` and ``VARCHAR`` onto the same `sqlalchemy.String`, so
+ the distinction this needs is gone by then. The length suffix is dropped
+ and the name matched against `PADDED_CHARACTER_TYPES`, so an unfamiliar
+ spelling answers ``False`` and the engine-level flag decides as before --
+ this gate adds a decline rather than lifting one. A column with no
+ declared type has nothing to read, and answers the same way.
+ """
+ if not isinstance(column.type, str):
+ return False
+ native = re.sub(r"\s+", " ", column.type.strip().upper())
+ return native.split("(")[0].strip() in PADDED_CHARACTER_TYPES
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ Padding is asked about per column, because it is a property of the *type*
+ rather than of the engine. ``binary_string_comparison`` speaks for an
+ engine's default text comparison, and on PostgreSQL -- which declares it
+ -- a ``CHAR(2)`` still matches a filter for ``'US '`` against a stored
+ ``'US'``, because the standard says a padded character type compares
+ without its trailing blanks. The mirror ``region_key = lower('US ')`` then
+ excludes the row. So a fixed-width character type declines whatever the
+ engine says, and an engine that ignores trailing blanks on its *variable*
+ types says so by not declaring the flag at all (see `RedshiftEngineSpec`).
+
+ The type asked for is the engine spec's reading of the column's declared
+ type, not `TableColumn.type_generic`, which answers ``TEMPORAL`` for
+ anything carrying ``is_dttm``. A ``VARCHAR`` flagged temporal is still text
+ to the engine: on MySQL a filter for ``'2026-01-01T00:00:00'`` matches a
+ stored ``'...t00:00:00'``, while the mirror ``p = hex('...T...')`` excludes
+ it -- and asking the semantic flag skipped the check entirely.
+
+ A type the spec cannot classify declines, which is what the paragraph above
+ promises and what only the exception branch used to do. PostgreSQL's
+ ``citext`` matches no type pattern, so it answered ``None`` -- neither
+ string nor not-string -- and was waved through, which is precisely wrong
+ for a type whose whole purpose is case-insensitive comparison. Declining
+ costs the pruning; admitting it costs rows.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ # Ahead of the generic-type question, which a padded type can lose: the
+ # specs map ``CHARACTER`` onto no generic type at all on some engines, and
+ # a fixed-width character type is a string whether or not Superset can say
+ # so from the name.
+ if _is_padded_character_type(column):
+ return False
+ generic_type = _native_generic_type(column)
+ if generic_type is None:
+ return False
+ if generic_type != utils.GenericDataType.STRING:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_unicode_escaped_identifier(transform: str | None) -> bool:
+ """Whether the transform names something through a ``U&"..."`` escape.
+
+ See `UNICODE_ESCAPED_IDENTIFIER_RE`. Answered on raw text for the same
+ reason as the comment above: the parse reports a name the engine does not
+ use, which is exactly what makes the denylist blind to it.
+ """
+ return (
+ bool(transform)
+ and UNICODE_ESCAPED_IDENTIFIER_RE.search(transform or "") is not None
+ )
+
+
+#: Sequence pseudo-columns, which advance a sequence when they are *read*.
+#:
+#: ``orders_seq.NEXTVAL`` parses as a qualified column reference, not a
+#: function call, so neither `SQLStatement.is_mutating` -- which walks function
+#: names -- nor the function denylist can see it. The probe would then run
+#: ``SELECT orders_seq.NEXTVAL + 1 FROM DUAL`` and advance the sequence, again
+#: on every cache expiry, for a dataset editor holding neither SQL Lab nor a
+#: DML grant. Reading one is a write however the parser classifies it.
+#:
+#: The function spelling (``nextval('s')`` on PostgreSQL) is a different shape
+#: and is caught as a function; this is only about the suffix form.
+SEQUENCE_PSEUDO_COLUMNS = frozenset({"nextval", "currval"})
+
+#: The same thing written as a call.
+#:
+#: Only the suffix form parses as a column; `nextval('s')` on PostgreSQL and
+#: DuckDB, `NEXTVAL(s)`/`SETVAL(s, 1)` on MySQL and MariaDB, and SQL Server's
+#: `NEXT VALUE FOR s` all parse as functions. `SQLStatement.is_mutating` walks
+#: function names on PostgreSQL alone -- deliberately, since the same names are
+#: read-only elsewhere -- so every other engine let these through.
+#:
+#: Matched on the name whatever the engine, because advancing a sequence is a
+#: write wherever it happens and a transform has no reason to call one.
+SEQUENCE_FUNCTIONS = frozenset(
+ {"nextval", "setval", "next_value_for", "nextvalfor", "prevval", "lastval"}
+)
+
+
+def references_sequence(statement: SQLStatement) -> bool:
+ """Whether the statement reads or advances a sequence.
+
+ Both spellings: the pseudo-column suffix, which parses as a column (see
+ `SEQUENCE_PSEUDO_COLUMNS`), and the call, which parses as a function (see
+ `SEQUENCE_FUNCTIONS`).
+
+ Answered on the parse rather than on raw text, because position is what
+ makes it the construct: a column or alias merely *called* ``nextval`` is
+ an ordinary column, and a string literal holding the word is text.
+ """
+ return bool(
+ statement.get_column_names() & SEQUENCE_PSEUDO_COLUMNS
+ or statement.get_disallowed_functions(set(SEQUENCE_FUNCTIONS))
+ )
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """
+ Whether the transform contains a balanced Jinja block.
+
+ A block is an opening delimiter followed, anywhere later, by its closing
+ one -- the same thing ``{{.*?}}`` and its two siblings match under
+ ``re.DOTALL``. Scanned with `str.find` rather than that pattern, because a
+ lazy match retried from every opening delimiter is quadratic in a run of
+ them, and this runs on stored transforms with no length bound of its own:
+ `is_transform_active` reads whatever the column holds. The earliest opening
+ delimiter is the only one worth trying, since any closing delimiter after a
+ later one is also after it.
+ """
+ if not transform:
+ return False
+ for opening, closing in JINJA_BLOCK_DELIMITERS:
+ start = transform.find(opening)
+ if start != -1 and transform.find(closing, start + len(opening)) != -1:
+ return True
+ return False
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+
+ Three spellings have to be looked for, because one name reaches the parse
+ three ways: as a function call, as a zero-argument call a dialect resolves
+ itself, and -- for the datetime keywords -- as a bare word that parses as a
+ column reference.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ # The parenthesis-free spellings, which parse as columns rather than
+ # functions and so are invisible to the walk above. See
+ # `BARE_WALL_CLOCK_KEYWORDS`.
+ found |= {
+ name.upper() for name in BARE_WALL_CLOCK_KEYWORDS & statement.get_column_names()
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ # An array holds no scalar a transform could return, so no mirror onto it
+ # can ever compare. Refused for the mapping rather than only per value, so
+ # the Explore glyph stops promising one: a probe of ``:value`` succeeds and
+ # records a working transform, and only the later type gate declined.
+ if declares_array_type(columns_by_name[partition_column].type):
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error( # noqa: C901
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ And it must be a *read*. Shape is a separate question from effect: a bare
+ scalar expression can still write, so `SQLStatement.is_mutating` is asked
+ too -- the same question SQL Lab and the chart executor ask before letting
+ SQL run. See the gate itself for what that reaches and what it does not.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ # Also ahead of the parse, and for a stronger reason than cost: every gate
+ # below reasons about the parse tree, and this is the one construct that
+ # makes the parse tree describe a different statement from the one the
+ # engine runs. Checked here as well as in `validate_transform` because this
+ # is the door a row written by an earlier release still comes through.
+ if contains_executable_comment(transform):
+ return str(
+ _(
+ "A partition value transform cannot contain a MySQL "
+ "executable comment, which the database executes and every "
+ "validator reads as a comment."
+ )
+ )
+
+ if contains_unicode_escaped_identifier(transform):
+ return str(
+ _(
+ "A partition value transform cannot name anything through a "
+ 'U&"..." escape sequence, which the database decodes and '
+ "every validator reads literally."
+ )
+ )
+
+ # Same door, same reason: the name the denylist below would match is not
+ # the name the engine resolves. See `UNICODE_ESCAPED_IDENTIFIER_RE`.
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The read-only gate, which nothing above implies. The shape gates ask what
+ # the transform *selects*; this asks what evaluating it *does*, and a bare
+ # scalar expression can still write. `nextval(:value)` on PostgreSQL
+ # advances a sequence: one function call, no clause, no sub-query, and not
+ # in the default `DISALLOWED_SQL_FUNCTIONS` either -- so every gate above
+ # passes it and the probe then runs it. `setval` is the same shape, and
+ # `exp.Execute` and the opaque-`exp.Command` forms arrive the same way.
+ #
+ # The large-object writers (`lo_export`, `lowrite`, `lo_from_bytea`, ...)
+ # are caught here too, and the shipped denylist happens to name them as
+ # well -- but that is config an operator can replace, while this is not.
+ #
+ # `is_mutating` is the same question SQL Lab, `get_virtual_table_metadata`
+ # and the chart executor ask before letting SQL run, so a transform is held
+ # to the bar the rest of Superset already sets rather than to one invented
+ # here. Unconditional rather than gated on `Database.allow_dml`: a transform
+ # is a scalar function of `:value` by definition, so there is no legitimate
+ # mutating one, and the probe runs on a cache schedule nobody chose -- a
+ # write would repeat every time the entry expired.
+ #
+ # It bears saying what this does not reach. A user-defined function whose
+ # body writes is a plain call no parser can tell from `lower(:value)`, and
+ # `is_mutating`'s function-name walk is PostgreSQL-only by design, since the
+ # same names are read-only elsewhere. Neither residual is specific to this
+ # feature -- a dataset editor can already have the engine evaluate an
+ # arbitrary expression through a calculated column or a virtual dataset's
+ # SQL -- and closing them means authorizing the preview against the
+ # database, not parsing harder.
+ if statement.is_mutating():
+ return str(
+ _(
+ "A partition value transform cannot change data. It is "
+ "evaluated against the database to check that it mirrors, so "
+ "it has to be a read."
+ )
+ )
+
+ # Not reached by the walk above, which is why it is its own gate: a
+ # sequence pseudo-column is a *column* to the parser and a write to the
+ # engine. See `SEQUENCE_PSEUDO_COLUMNS`.
+ if references_sequence(statement):
+ return str(
+ _(
+ "A partition value transform cannot read a sequence. "
+ "NEXTVAL advances the sequence every time it is evaluated, "
+ "and the transform is evaluated on a cache schedule."
+ )
+ )
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the
+ probe uninspected. Rendering is not what makes that true: a string element
+ is checked by `literal_round_trips` before it is rendered -- the dialect's
+ literal processor and the engine's lexer do not always agree about what a
+ rendered literal says -- and `probe_sql_is_evaluable` re-reads the finished
+ query, which is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def _placeholder_is_bindable(transform: str) -> bool:
+ """
+ Whether SQLAlchemy's ``text()`` can see ``:value`` as a bound parameter.
+
+ `VALUE_PLACEHOLDER_RE` is ``:value\b``, which matches the placeholder in a
+ Postgres cast such as ``:value::bigint``. SQLAlchemy's own bind scan is
+ ``(?<![:\\w$]):([\\w$]+)(?![:\\w$])`` -- note the trailing exclusion -- so a
+ following colon stops it: ``text(":value::bigint")`` reports a parameter
+ named ``valu``, and ``.bindparams(bindparam("value"))`` then raises
+ ``ArgumentError``.
+
+ `_probe` swallows that, so the only symptom was a perfectly valid transform
+ whose mapping silently never pruned, and a preview reporting an engine
+ failure for SQL that was never sent. Every write-side gate passes the
+ transform: it parses, it is a bare expression, and the placeholder *is* in
+ an executable position.
+
+ Answered by attempting the bind itself rather than by pattern-matching
+ ``::`` or reading ``text()``'s private parameter map, so this cannot
+ disagree with what `build_probe_sql` is about to do -- on any dialect, or on
+ a SQLAlchemy whose scan changes.
+ """
+ try:
+ sa.text(transform).bindparams(sa.bindparam("value", value=None))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return False
+ return True
+
+
+def escape_foreign_colons(transform: str) -> str:
+ """
+ ``transform`` with every colon but the ``:value`` placeholder escaped.
+
+ `sqlalchemy.text` reads any ``:word`` as a bind parameter, including one
+ inside a string literal, and an unbound parameter renders as ``NULL``
+ under literal binds rather than raising. So ``:value || \':suffix\'``
+ compiled to ``'us' || 'NULL'``: the mirror asked for a partition value no
+ row holds and the chart dropped rows, with no error for `_probe` to
+ swallow and nothing on screen to say so.
+
+ Escaped rather than refused, because a colon in a literal is ordinary --
+ ``concat(:value, \':\', region)`` builds a composite key -- and the
+ placeholder is the only colon this module means to interpret. `text()`
+ reads ``\\:`` as a literal colon.
+
+ Only the bound path needs this. A `RawProbeValue` or an unbindable
+ placeholder is substituted as text by `parse_skeleton`, which never hands
+ the transform to `text()` at all.
+ """
+ pieces: list[str] = []
+ cursor = 0
+ for match in VALUE_PLACEHOLDER_RE.finditer(transform):
+ pieces.append(transform[cursor : match.start()].replace(":", r"\:"))
+ pieces.append(match.group(0))
+ cursor = match.end()
+ pieces.append(transform[cursor:].replace(":", r"\:"))
+ return "".join(pieces)
+
+
+def literal_round_trips(value: Any, dialect: Dialect | None, engine: str) -> bool:
+ """
+ Whether the engine reads a rendered ``value`` back as that same value.
+
+ The probe runs with no bound parameters, so every value reaches the engine
+ as literal text the driver wrote (see `build_probe_sql`). Whether that text
+ says what the value says is a question about two independent spellings: the
+ driver's escaping, and the engine's lexer. SQLAlchemy's default renderer
+ doubles apostrophes and passes backslashes through; Hive and Spark honour
+ the backslash and not the doubling, so ``'O''Brien'`` is read there as two
+ adjacent literals -- the transform is evaluated at ``OBrien``, and the
+ mirror asks for a partition key that holds none of the rows the filter
+ keeps. The same gap in the other direction lets a value close its own quote
+ and have the rest of it read as SQL.
+
+ Escaping is not the repair. Whether a backslash introduces an escape is a
+ per-session server setting -- ``standard_conforming_strings`` on Postgres,
+ ``NO_BACKSLASH_ESCAPES`` on MySQL, ``escapedStringLiterals`` on Spark -- and
+ nothing in the engine specs exposes it. SQLAlchemy reads it off the server
+ into ``_backslash_escapes`` during ``initialize(connection)``, which the
+ probe's dialect never reaches: `_dialect_for` asks the ``Database`` for a
+ dialect, not for a connection, so Postgres renders ``a\\b`` as
+ ``'a\\\\b'`` and a server with the standard setting reads four
+ characters. An engine-spec flag would have to be defaulted, and either
+ default is wrong for a dozen engines: one leaves the hole open, the other
+ corrupts the probed value.
+
+ So the premise is verified rather than declared, the way
+ `probe_sql_is_evaluable` verifies the finished statement. A value that does
+ not survive the round trip is not mirrored, which costs the query its
+ pruning and nothing else.
+
+ The short-circuit is a proof, not a guess, and it matters for cost: a
+ 200-member ``IN`` list would otherwise parse 200 times on the chart path.
+ If the renderer emitted the value between two quotes and changed nothing in
+ it, and the value carries neither a quote nor a backslash, then no lexer in
+ play can read it as anything but itself. Both exclusions are load-bearing:
+ on Hive ``a\\b`` renders verbatim and reads as ``a`` followed by a
+ backspace.
+
+ :param value: a filter value about to be rendered into the probe
+ :param dialect: the dialect that will render it, as `_dialect_for` reports
+ :param engine: ``database.backend``, whose lexer reads the result
+ :return: whether the two agree about what the literal says
+ """
+ if isinstance(value, RawProbeValue):
+ # Already SQL, with no single value for a parse to be compared against:
+ # its elements are checked before they are rendered, by
+ # `ExploreMixin._array_mirror_probe_value`. A backslash surviving into
+ # the finished text is refused here all the same, as the backstop for a
+ # renderer this module does not own.
+ return "\\" not in value.sql
+ if not isinstance(value, str):
+ # Numbers and instants are not written between delimiters, so there is
+ # no escaping for the two sides to disagree about.
+ return True
+
+ rendered = _compile_literal(sa.literal(value), dialect)
+ if rendered == f"'{value}'" and "'" not in value and "\\" not in value:
+ return True
+
+ try:
+ return (
+ SQLStatement(f"SELECT {rendered}", engine).get_select_literal_value()
+ == value
+ )
+ except SupersetParseError:
+ # A rendered literal the engine's own dialect will not parse is the
+ # strongest form of disagreement there is.
+ return False
+
+
+def value_round_trips(database: Database, value: Any) -> bool:
+ """
+ `literal_round_trips` for a caller holding a database, not a dialect.
+
+ Which renderer and which lexer apply is this module's business, so the two
+ callers outside it -- the chart path's own gate in
+ `ExploreMixin.mirror_probe_request` and the mapping summary Explore reads
+ -- ask in these terms and stay out of it.
+
+ :param database: the database whose driver renders and whose engine reads
+ :param value: a filter value about to be rendered into the probe
+ :return: whether the two agree about what the literal says
+ """
+ return literal_round_trips(value, _dialect_for(database), database.backend)
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text. That is not itself a boundary:
+ the processor's escaping is not always the escaping the engine honours, and
+ a value can close its own quote through the gap. The boundary is
+ `literal_round_trips` on the way in -- which callers must have run, like
+ `stored_expression_error` below -- and `probe_sql_is_evaluable` on the way
+ out.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ bindable = _placeholder_is_bindable(transform)
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ elif bindable:
+ # Every other colon escaped first: `text()` would read one inside a
+ # string literal as a second bind parameter and render it `NULL`.
+ # See `escape_foreign_colons`.
+ clause = sa.text(escape_foreign_colons(transform)).bindparams(
+ sa.bindparam("value", value=value)
+ )
+ rendered = _compile_literal(clause, dialect)
+ else:
+ # `text()` cannot see the placeholder (see
+ # `_placeholder_is_bindable`), so the value is rendered by the
+ # dialect's own literal processor first and substituted as SQL
+ # text. The same two steps in the other order: binding exists to
+ # get the value through that processor, and `_compile_literal`
+ # inlines the result either way, so this is the same string by a
+ # different route -- not a loosening of the "never interpolate a
+ # raw value" rule. `parse_skeleton` substitutes literally, so the
+ # rendered literal arrives here exactly as it was rendered, which
+ # is what makes `literal_round_trips`' verdict on it good for this
+ # branch as much as for the bound one.
+ rendered = parse_skeleton(
+ transform, _compile_literal(sa.literal(value), dialect)
+ )
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Five things have to hold, and all five are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+ * No comment, anywhere. A value that closes its own quote has to hide the
+ text `build_probe_sql` appended after it, and a comment is the only way
+ to do that and still balance the quotes -- so this is what makes the
+ alias check above sufficient rather than merely necessary. Read off the
+ parse rather than the text, so a comment *inside* a literal is data and
+ costs no pruning, and so the question is asked in the engine's own
+ dialect. A transform has no legitimate reason to carry one either; see
+ `EXECUTABLE_COMMENT_RE`.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ # Before the parse, because this gate's whole contract is that what the
+ # parse describes is what the engine will run, and an executable comment is
+ # precisely the text where that stops being true. The transform is already
+ # refused for carrying one; this covers the compiled statement, so no later
+ # change to how values are rendered can reintroduce it behind the gates
+ # below.
+ if contains_executable_comment(sql) or contains_unicode_escaped_identifier(sql):
+ return False
+
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if not isinstance(statement, SQLStatement):
+ # A dialect whose statements this gate cannot take apart -- KQL -- gets
+ # no probe rather than an unchecked one. It never had one: the clause
+ # inspection below is implemented for SQL statements only, and the
+ # alternative to declining here is an `AttributeError` that `_probe`
+ # swallows into the same outcome, less legibly.
+ return False
+ if statement.has_comment():
+ return False
+ if statement.has_subquery():
+ return False
+ if statement.get_clause_names() - {"from"}:
+ return False
+ if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+ """
+ The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+ Parsed rather than string-compared so that the comparison in
+ `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+ not parse answers ``None``, which no statement carrying a FROM can match --
+ the probe then declines, which is the right way for an unreadable engine
+ constant to fail.
+ """
+ if not from_suffix.strip():
+ return None
+ try:
+ return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+ except SupersetParseError:
+ return None
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+ text_answers: list[tuple[int, Any]] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ :param text_answers: optional sink. When given, every date or timestamp in
+ ``values`` is also asked as the text a simple filter would bind, in the
+ same round trip, and ``(index, answer)`` is appended for each -- see
+ `_declined_for_reading_by_type` for why. A transform that refuses text
+ is asked again with ``values`` alone, so a refusal never costs pruning.
+ """
+ if not values:
+ return None
+
+ if text_answers is not None:
+ indexes = [
+ index
+ for index, value in enumerate(values)
+ if isinstance(value, date) and not is_unmirrorable(value)
+ ]
+ if indexes:
+ combined = evaluate_transform(
+ database,
+ catalog,
+ schema,
+ transform,
+ values + [_as_filter_text(values[index]) for index in indexes],
+ )
+ if combined is not None:
Review Comment:
I think a transform that refuses the text still slips through here. `TO_DATE(:value, 'YYYY-MM-DD')` onto a day key raises ORA-01830 on `'2026-01-12 06:30:00'`, so this falls back to the typed answer (year 0012) unchecked: the preview says Valid and the range returns 0 rows (48 with the flag off), `Last week` too. Could a refused text form decline the temporal mirror instead?

[mp4](https://gist.githubusercontent.com/geido/2e9a0de274464f8bac4b8ac43e8888e9/raw/final2-oracle-todate-daykey.mp4) · [v$sql and sqlplus replay](https://gist.githubusercontent.com/geido/2e9a0de274464f8bac4b8ac43e8888e9/raw/final2-oracle-todate-daykey-oracle-evidence.txt)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "hughhhh (via GitHub)" <gi...@apache.org>.
hughhhh commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4319668154
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2730 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+#: Returned by `ExploreMixin.mirror_probe_request` for a filter no mirror can
+#: stand in for: one the engine compares more coarsely than the value carries, a
+#: value it cannot render as a literal, or an ``IN`` list with a member of
+#: either kind. A sentinel rather than `None`, because `None` is a filter value
+#: in its own right.
+#:
+#: Lives here rather than beside that method so the preview can read it too:
+#: `superset.models.helpers` imports this module, so the sentinel can only cross
+#: the boundary in this direction. Both callers have to recognise the same
+#: object -- a preview that answered "valid" for a request the chart path
+#: declines is the drift this is here to prevent.
+UNMIRRORABLE = object()
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error( # noqa: C901
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ And it must be a *read*. Shape is a separate question from effect: a bare
+ scalar expression can still write, so `SQLStatement.is_mutating` is asked
+ too -- the same question SQL Lab and the chart executor ask before letting
+ SQL run. See the gate itself for what that reaches and what it does not.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ # Also ahead of the parse, and for a stronger reason than cost: every gate
+ # below reasons about the parse tree, and this is the one construct that
+ # makes the parse tree describe a different statement from the one the
+ # engine runs. Checked here as well as in `validate_transform` because this
+ # is the door a row written by an earlier release still comes through.
+ if contains_executable_comment(transform):
+ return str(
+ _(
+ "A partition value transform cannot contain a MySQL "
+ "executable comment, which the database executes and every "
+ "validator reads as a comment."
+ )
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The read-only gate, which nothing above implies. The shape gates ask what
+ # the transform *selects*; this asks what evaluating it *does*, and a bare
+ # scalar expression can still write. `nextval(:value)` on PostgreSQL
+ # advances a sequence: one function call, no clause, no sub-query, and not
+ # in the default `DISALLOWED_SQL_FUNCTIONS` either -- so every gate above
+ # passes it and the probe then runs it. `setval` is the same shape, and
+ # `exp.Execute` and the opaque-`exp.Command` forms arrive the same way.
+ #
+ # The large-object writers (`lo_export`, `lowrite`, `lo_from_bytea`, ...)
+ # are caught here too, and the shipped denylist happens to name them as
+ # well -- but that is config an operator can replace, while this is not.
+ #
+ # `is_mutating` is the same question SQL Lab, `get_virtual_table_metadata`
+ # and the chart executor ask before letting SQL run, so a transform is held
+ # to the bar the rest of Superset already sets rather than to one invented
+ # here. Unconditional rather than gated on `Database.allow_dml`: a transform
+ # is a scalar function of `:value` by definition, so there is no legitimate
+ # mutating one, and the probe runs on a cache schedule nobody chose -- a
+ # write would repeat every time the entry expired.
+ #
+ # It bears saying what this does not reach. A user-defined function whose
+ # body writes is a plain call no parser can tell from `lower(:value)`, and
+ # `is_mutating`'s function-name walk is PostgreSQL-only by design, since the
+ # same names are read-only elsewhere. Neither residual is specific to this
+ # feature -- a dataset editor can already have the engine evaluate an
+ # arbitrary expression through a calculated column or a virtual dataset's
+ # SQL -- and closing them means authorizing the preview against the
+ # database, not parsing harder.
+ if statement.is_mutating():
+ return str(
+ _(
+ "A partition value transform cannot change data. It is "
+ "evaluated against the database to check that it mirrors, so "
+ "it has to be a read."
+ )
+ )
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the probe
+ uninspected -- string elements are escaped by the dialect's own literal
+ processor. `probe_sql_is_evaluable` then re-reads the finished query, which
+ is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def _placeholder_is_bindable(transform: str) -> bool:
+ """
+ Whether SQLAlchemy's ``text()`` can see ``:value`` as a bound parameter.
+
+ `VALUE_PLACEHOLDER_RE` is ``:value\b``, which matches the placeholder in a
+ Postgres cast such as ``:value::bigint``. SQLAlchemy's own bind scan is
+ ``(?<![:\\w$]):([\\w$]+)(?![:\\w$])`` -- note the trailing exclusion -- so a
+ following colon stops it: ``text(":value::bigint")`` reports a parameter
+ named ``valu``, and ``.bindparams(bindparam("value"))`` then raises
+ ``ArgumentError``.
+
+ `_probe` swallows that, so the only symptom was a perfectly valid transform
+ whose mapping silently never pruned, and a preview reporting an engine
+ failure for SQL that was never sent. Every write-side gate passes the
+ transform: it parses, it is a bare expression, and the placeholder *is* in
+ an executable position.
+
+ Answered by attempting the bind itself rather than by pattern-matching
+ ``::`` or reading ``text()``'s private parameter map, so this cannot
+ disagree with what `build_probe_sql` is about to do -- on any dialect, or on
+ a SQLAlchemy whose scan changes.
+ """
+ try:
+ sa.text(transform).bindparams(sa.bindparam("value", value=None))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return False
+ return True
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ bindable = _placeholder_is_bindable(transform)
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ elif bindable:
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ rendered = _compile_literal(clause, dialect)
+ else:
+ # `text()` cannot see the placeholder (see
+ # `_placeholder_is_bindable`), so the value is rendered by the
+ # dialect's own literal processor first and substituted as SQL
+ # text. The same two steps in the other order: binding exists to
+ # get the value through that processor, and `_compile_literal`
+ # inlines the result either way, so this is the same string by a
+ # different route -- not a loosening of the "never interpolate a
+ # raw value" rule. `parse_skeleton` substitutes literally, so a
+ # rendered literal containing a backslash is safe here.
+ rendered = parse_skeleton(
+ transform, _compile_literal(sa.literal(value), dialect)
+ )
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Four things have to hold, and all four are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ # Before the parse, because this gate's whole contract is that what the
+ # parse describes is what the engine will run, and an executable comment is
+ # precisely the text where that stops being true. The transform is already
+ # refused for carrying one; this covers the compiled statement, so no later
+ # change to how values are rendered can reintroduce it behind the gates
+ # below.
+ if contains_executable_comment(sql):
+ return False
+
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if not isinstance(statement, SQLStatement):
+ # A dialect whose statements this gate cannot take apart -- KQL -- gets
+ # no probe rather than an unchecked one. It never had one: the clause
+ # inspection below is implemented for SQL statements only, and the
+ # alternative to declining here is an `AttributeError` that `_probe`
+ # swallows into the same outcome, less legibly.
+ return False
+ if statement.has_subquery():
+ return False
+ if statement.get_clause_names() - {"from"}:
+ return False
+ if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+ """
+ The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+ Parsed rather than string-compared so that the comparison in
+ `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+ not parse answers ``None``, which no statement carrying a FROM can match --
+ the probe then declines, which is the right way for an unreadable engine
+ constant to fail.
+ """
+ if not from_suffix.strip():
+ return None
+ try:
+ return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+ except SupersetParseError:
+ return None
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=values is not None and not any(value is None for value in values),
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ from_suffix = database.db_engine_spec.select_without_from_suffix
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ from_suffix,
+ )
+ if not probe_sql_is_evaluable(
+ sql, database.backend, len(distinct), from_suffix
+ ):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _execution_identity(database: Database) -> str | None:
+ """
+ Who the warehouse will run the probe as, when that can vary by caller.
+
+ `_probe_cache_key` keys on the `Database` record, which is the *connection*
+ -- not the identity it is opened under. Two hooks make that identity a
+ function of the Superset user instead:
+
+ * ``impersonate_user`` on the database, which hands the effective username
+ to `db_engine_spec.impersonate_user`;
+ * ``DB_CONNECTION_MUTATOR``, which receives the effective username and may
+ return an entirely different account's URL.
+
+ Under either one, a cached probe result computed under user A's grants was
+ served to user B, and the preview echoed it back in ``emitted_predicate``.
+ A transform wrapping a read-capable function the denylist does not name --
+ Oracle's ``DBMS_XMLGEN.GETXML`` is the worked example -- then leaks across
+ users who were never allowed the same rows.
+
+ Returns ``None`` when neither hook is configured, which is the common case
+ and deliberately leaves the key as it was: the cache exists to keep a
+ synchronous warehouse round trip off the chart-query path, and keying every
+ deployment on the username would cost every deployment the hit rate to fix
+ the two that need it.
+
+ The *Superset* username rather than the resolved warehouse account, because
+ it is the input both hooks branch on, and reading it needs no URL parse and
+ puts no credential in the key.
+ """
+ if not (database.impersonate_user or app.config["DB_CONNECTION_MUTATOR"]):
+ return None
+ return get_username()
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _mirror_verdict_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str:
+ """
+ `_probe_cache_key` without the values.
+
+ Whether a transform can be evaluated at all is a property of the transform
+ and the connection, not of the filter that happened to be probing it, so
+ one chart's answer settles the question for the next one.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ # Whether a transform *can* be evaluated is a property of the
+ # transform and the connection -- but under impersonation the
+ # connection is per-user, and a function one account may call can
+ # be refused to another. See `_execution_identity`.
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_verdict:{digest}"
+
+
+def record_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ *,
+ mirrors: bool,
+) -> None:
+ """
+ Remember whether this transform produced a mirror, for the UI to read.
+
+ Advisory only. Nothing in the query path consults it: a probe that failed
+ once is retried on the next chart exactly as it is today, because declining
+ to prune for a whole cache timeout over one transient engine blip is the
+ trade `evaluate_transform` deliberately refuses -- see the comment where it
+ declines to cache a failure.
+
+ What this is for is the *claim*. `is_transform_active` parses the transform
+ and no more, so a transform the database rejects -- a misspelled function
+ is the common case -- is "active", and the editor's banner and Explore's
+ pruning glyph promise a speed-up that never happens. A promise is exactly
+ the thing that may be withheld on one bad answer and restored on a good
+ one, which is why this is a separate entry from the probe's own results
+ rather than a relaxation of that rule.
+
+ Written by `_run_probe`, so the preview endpoint -- which shares the
+ evaluator -- settles the question before the owner has even saved.
+ """
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(
+ _mirror_verdict_cache_key(database, catalog, schema, transform),
+ mirrors,
+ timeout=timeout,
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform verdict", exc_info=True)
+
+
+def known_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> bool | None:
+ """
+ The last verdict `record_mirror_verdict` stored, or `None` if there is none.
+
+ `None` is the honest answer on a cold cache and is deliberately not `False`:
+ reporting a working mapping as broken until something probes it would
+ trade one wrong claim for another. The alternative -- probing from the
+ read side -- would put a warehouse round trip on every Explore and
+ dashboard load, and a failing transform is not cached at all, so it would
+ be a round trip every single time.
+ """
+ try:
+ verdict = cache_manager.cache.get(
+ _mirror_verdict_cache_key(database, catalog, schema, transform)
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return verdict if isinstance(verdict, bool) else None
+
+
+def _compile_literal(element: Any, dialect: Dialect | None) -> str:
+ """
+ Compile with inline literals, undoing the paramstyle's percent doubling.
+
+ Both ``TextClause`` and literal compilation run the dialect's
+ ``post_process_text``, which doubles every ``%`` whenever the identifier
+ preparer asks it to -- true for MySQL and Postgres and for every spec
+ inheriting their paramstyle. That doubling exists so a later DBAPI
+ parameter-interpolation pass can undo it, and the probe has no such pass:
+ it executes with no bound parameters at all. So a transform of
+ ``date_format(:value, '%Y%m%d')`` reaches the warehouse asking for the
+ literal string ``%%Y%%m%%d``, the probe returns that instead of a date, and
+ the mirrored predicate drops every row the filter keeps.
+
+ The same normalization ``Database.compile_sqla_query`` applies for the same
+ reason. ``_double_percents`` is private and not guaranteed on a third-party
+ dialect, hence the ``getattr`` default.
+ """
+ compiled = str(
+ element.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
+ )
+ if dialect is not None and getattr(
+ dialect.identifier_preparer, "_double_percents", False
+ ):
+ compiled = compiled.replace("%%", "%")
+ return compiled
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be *asked* to stand in for itself, and the transform
+ cannot carry Jinja or call a non-deterministic function. Tier 2
+ (``blocking=False``) is everything that merely leaves the mapping inactive
+ -- including a self-mapping nobody asked for, where the partition column
+ merely happens to be the default datetime column.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column == partition_column:
+ # Asked for explicitly, so report it as the mistake it is.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+ elif not partition_mapped_column and main_dttm_col == partition_column:
+ # Resolved onto itself only because the default datetime column happens
+ # to be the partition column -- a state metadata sync could produce
+ # without anyone asking for it. The mapping is inert either way, since
+ # `resolve_partition_mapping` bails out on it, so this reports and lets
+ # the write through: blocking here means a dataset already in the state
+ # can never be saved again, not even to change its description, and
+ # there is no field whose edit would clear the error first.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "%(name)s is both the partition column and the default "
+ "datetime column, so the mapping points at itself and "
+ "stays inactive. Set a mapped column override, or change "
+ "the default datetime column.",
+ name=partition_column,
+ ),
+ blocking=False,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def drop_unmapped_value_transforms(
+ columns: list[dict[str, Any]] | None,
+ *,
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ names_by_id: dict[int, str] | None = None,
+) -> list[str]:
+ """
+ Null the value transform on every *incoming* column the mapping cannot mirror.
+
+ The write-side twin of `DatasetDAO.clear_unmapped_partition_transforms`,
+ which answers for the model. A mapping has exactly one mirrored column, so
+ at most one column may carry a transform. One parked on any other column is
+ invisible -- no row but the mapped one renders a transform -- and yet it is
+ stored, and it goes live the moment the mapped column resolves back to it.
+ Clearing an override is enough to do that: a null
+ ``partition_mapped_column`` means "follow ``main_dttm_col``".
+
+ Ungated on the feature flag, unlike its model-level twin, and the difference
+ is what each one discards. That one drops stored configuration, so with the
+ flag off it would be pure loss. This one drops only a value the request in
+ hand is asking to write where the invariant says none may live -- and the
+ flag-off window is precisely when such a value gets parked for later, since
+ the editor hides these fields and the model-level pass declines to run.
+
+ Three writers reach the columns with no effective model-level pass between
+ them, which is why this exists at all: the deprecated
+ ``POST /datasource/save/``, which writes straight through
+ `update_from_object` and so never had one; and a
+ ``PUT /api/v1/dataset/<pk>`` or a dataset import made while the flag is
+ off, where the pass runs on both sides of the write and declines on both.
+
+ Mutates the payload in place, because every caller hands its own request
+ dict straight on to the code that writes it. Returns the names it cleared,
+ so the caller can say so in a log: this is a silent correction to a payload
+ whose author may have meant it.
+
+ A column whose payload mentions neither field is left alone. "Incoming" is
+ the whole scope -- a transform already in storage on a column this request
+ says nothing about is the model-level pass's business, under its own flag.
+
+ The mapped column resolves the way every other reader resolves it,
+ ``partition_mapped_column or main_dttm_col``, and resolves to nothing
+ without a partition column -- in which case no column may hold a transform
+ either.
+
+ :param names_by_id: how to read the name off a payload entry that gives
+ only an ``id``. `DatasetDAO._upsert_columns` identifies an existing
+ column by its primary key and lets ``column_name`` be omitted -- the
+ column keeps the name it has -- so without this an ordinary PUT looked
+ like a payload of nameless columns, none of which matched the mapped
+ one, and every transform in it was dropped. Callers whose writer keys
+ on the name instead (`update_from_object`, the importer) pass nothing.
+ An entry this cannot name is left alone rather than guessed at.
+ """
+ mapped_column = (
+ (partition_mapped_column or main_dttm_col) if partition_column else None
+ )
+ cleared: list[str] = []
+ for column in columns or []:
+ name = column.get("column_name")
+ if name is None and names_by_id is not None:
+ column_id = column.get("id")
+ if column_id is not None:
+ name = names_by_id.get(column_id)
+ if name is None or name == mapped_column:
+ continue
+ if column.get("partition_value_transform") or column.get(
+ "partition_transform_is_monotonic"
+ ):
+ column["partition_value_transform"] = None
+ column["partition_transform_is_monotonic"] = False
+ cleared.append(name)
+ return cleared
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if contains_executable_comment(transform):
+ # Blocking, and checked on raw text next to the Jinja gate because no
+ # parse reports it: sqlglot reads `/*!50000 ... */` as comment data
+ # while MySQL and MariaDB execute it, so every shape gate downstream
+ # inspects a statement the engine will not run. See
+ # `EXECUTABLE_COMMENT_RE`.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform cannot contain a MySQL executable "
+ "comment (/*! ... */ or /*M! ... */). Those are comments "
+ "to every validator and statement text to the database, "
+ "so what would run is not what was checked."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_bare_expression(transform, engine):
+ # Blocking, and deliberately placed in `validate_transform` rather than
+ # only at the probe: one issue here closes the PUT, the importer, the
+ # query-time gate through `is_transform_active`, the Explore indicator's
+ # active verdict and the preview endpoint, all of which already consult
+ # this function.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform must be a single SQL expression. It "
+ "cannot carry a FROM, WHERE, GROUP BY or any other clause, "
+ "and it cannot contain a sub-query."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not contains_value_placeholder(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform must contain the :value placeholder, "
+ "which stands for the filter value being mirrored."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not placeholder_is_executable(transform, engine):
+ # Blocking, and for the same reason the shape gate above is: this is
+ # the function the PUT, the importer, `is_transform_active`, the
+ # Explore indicator and the preview all consult, so one issue here
+ # closes every door at once. A placeholder inside a string literal is
+ # a sub-query the engine will run once a filter value closes the quote;
+ # one inside a comment silently eats the probe's own alias.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The :value placeholder must appear where the engine will "
+ "evaluate it. It cannot sit inside a string literal or a "
+ "comment."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if functions := find_non_deterministic_functions(transform, engine):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform calls %(functions)s, whose result "
+ "depends on when and where it runs. The transform is "
+ "evaluated in a separate session and the result is cached, "
+ "so the emitted predicate would freeze a snapshot of that "
+ "moment.",
+ functions=", ".join(sorted(functions)),
+ ),
+ blocking=True,
+ )
+ ]
+
+ return []
+
+
+@lru_cache(maxsize=LRU_CACHE_MAX_SIZE)
+def is_transform_active(transform: str | None, engine: str) -> bool:
+ """
+ Whether Superset will mirror filters through this transform.
+
+ `validate_transform` with the messages discarded, so the Explore indicator
+ cannot advertise a mapping the save path recorded as inactive. Anything
+ cheaper here would be a second, weaker statement of the same rule, free to
+ drift from the one the save path applies.
+
+ Blocking issues count too. Jinja and non-deterministic transforms are
+ rejected on PUT, but `CreateDatasetCommand` and import do not validate the
+ mapping, so one can still reach the database -- and it would never mirror a
+ filter either.
+
+ Memoized because `partition_filter_mapping_summary` is serialized on every
+ Explore and dashboard load and this parses the transform. The key is
+ everything the answer depends on: `validate_transform` reads no session, no
+ locale and no config beyond `SQL_MAX_PARSE_LENGTH`, which bounds the parser
+ rather than changing a verdict within that bound.
+ """
+ return not validate_transform(transform, engine)
+
+
+def preview_partition_mapping( # pylint: disable=too-many-return-statements
+ datasource: SqlaTable,
+ *,
+ mapped_column: str,
+ value_transform: str | None,
+ sample_values: list[str],
+ operator: FilterOperator = FilterOperator.EQUALS,
+ is_monotonic: bool = False,
+ partition_column: str | None = None,
+) -> dict[str, Any]:
+ """
+ Evaluate a candidate mapping and describe the predicate it would emit.
+
+ Shares the evaluator -- and therefore the probe cache -- with the query
+ path, so preview and runtime cannot drift and a previewed transform warms
+ the chart path for free. The predicate itself comes from
+ `build_mirrored_predicates`, the same builder the query path uses, so
+ operator shapes cannot drift either: what the panel shows is what a chart
+ would emit.
+
+ Validation runs first and the engine second: a half-typed transform is by
+ definition unparseable, so most of what a text input produces costs zero
+ queries.
+
+ Every part of the mapping is taken from the request rather than the stored
+ dataset. The editor previews while the owner is still editing -- a mapping
+ that has to be saved before it can be checked is not a preview.
+ """
+ partition_column = partition_column or datasource.partition_column
+ if not partition_column:
+ return {
+ "valid": False,
+ "reason": "unconfigured",
+ "error": _("No partition column is set."),
+ }
+
+ columns_by_name = {str(column.column_name): column for column in datasource.columns}
+ if mapped_column not in columns_by_name:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _("%(name)s is not a column on this dataset.", name=mapped_column),
+ }
+
+ # The bail-out `resolve_partition_mapping` makes at query time, and that
+ # `partition_filter_mapping_summary` repeats for the Explore indicator.
+ # Without it here, preview reports a valid emitted predicate for a mapping
+ # no chart will ever mirror -- the one answer a preview panel must not give.
+ if has_active_advanced_data_type(columns_by_name[mapped_column]):
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _(
+ "%(name)s has an advanced data type, so its filters are "
+ "translated into their own predicate shape and cannot be "
+ "mirrored onto the partition column.",
+ name=mapped_column,
+ ),
+ }
+
+ engine = datasource.database.backend
+ for issue in validate_partition_mapping(
+ column_names=set(columns_by_name),
+ partition_column=str(partition_column),
+ partition_mapped_column=mapped_column,
+ main_dttm_col=datasource.main_dttm_col,
+ transform=value_transform,
+ engine=engine,
+ ):
+ return {
+ "valid": False,
+ # The parse failure is the one an owner sees constantly, and it is
+ # the only one the mockup gives its own headline to.
+ "reason": (
+ "parse"
+ if issue.field == "partition_value_transform"
+ and not is_parseable(value_transform, engine)
+ else "validation"
+ ),
+ "error": str(issue.message),
+ }
+
+ # The policy every other stored expression goes through. The save path
+ # applies it in `UpdateDatasetCommand._validate_partition_mapping`, but
+ # preview evaluates a candidate transform that has not been saved, so
+ # without this the gate had a door around it. See
+ # `stored_expression_error` for what is being kept out and why.
+ if reason := stored_expression_error(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ cast(str, value_transform),
+ ):
+ return {"valid": False, "reason": "validation", "error": reason}
+
+ mapping = PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=mapped_column,
+ value_transform=cast(str, value_transform),
+ is_monotonic=is_monotonic,
+ equality_is_safe=equality_mirrors_safely(
+ columns_by_name[mapped_column], datasource.database.db_engine_spec
+ ),
+ )
+ sample_input = _render_sample_input(
+ datasource, mapped_column, operator, sample_values
+ )
+
+ if operator not in PREVIEWABLE_OPERATORS:
+ # Checked before `mirrors`, which lets `TEMPORAL_RANGE` through when the
+ # transform is declared monotonic -- and the single sample value would
+ # then reach `handle_comparison_filter`, which has no case for a range
+ # and raises. The request schema rejects it too; this keeps the function
+ # honest for any other caller.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is mirrored as a pair of bounds, which "
+ "a preview of a single value cannot describe.",
+ operator=operator.value,
+ ),
+ }
+
+ if not mapping.mirrors(operator):
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is only mirrored when the transform "
Review Comment:
Already addressed by @eschutho in a533814e7b: when `=`/`IN` is withdrawn by `equality_mirrors_safely`, preview returns its own message about case and trailing-space equality instead of the generic "preserves ordering" one. Resolving.
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2395 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+#: Returned by `ExploreMixin.mirror_probe_request` for a filter no mirror can
+#: stand in for: one the engine compares more coarsely than the value carries, a
+#: value it cannot render as a literal, or an ``IN`` list with a member of
+#: either kind. A sentinel rather than `None`, because `None` is a filter value
+#: in its own right.
+#:
+#: Lives here rather than beside that method so the preview can read it too:
+#: `superset.models.helpers` imports this module, so the sentinel can only cross
+#: the boundary in this direction. Both callers have to recognise the same
+#: object -- a preview that answered "valid" for a request the chart path
+#: declines is the drift this is here to prevent.
+UNMIRRORABLE = object()
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error(
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the probe
+ uninspected -- string elements are escaped by the dialect's own literal
+ processor. `probe_sql_is_evaluable` then re-reads the finished query, which
+ is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ else:
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ rendered = _compile_literal(clause, dialect)
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Four things have to hold, and all four are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if not isinstance(statement, SQLStatement):
+ # A dialect whose statements this gate cannot take apart -- KQL -- gets
+ # no probe rather than an unchecked one. It never had one: the clause
+ # inspection below is implemented for SQL statements only, and the
+ # alternative to declining here is an `AttributeError` that `_probe`
+ # swallows into the same outcome, less legibly.
+ return False
+ if statement.has_subquery():
+ return False
+ if statement.get_clause_names() - {"from"}:
+ return False
+ if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+ """
+ The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+ Parsed rather than string-compared so that the comparison in
+ `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+ not parse answers ``None``, which no statement carrying a FROM can match --
+ the probe then declines, which is the right way for an unreadable engine
+ constant to fail.
+ """
+ if not from_suffix.strip():
+ return None
+ try:
+ return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+ except SupersetParseError:
+ return None
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=values is not None and not any(value is None for value in values),
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ from_suffix = database.db_engine_spec.select_without_from_suffix
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ from_suffix,
+ )
+ if not probe_sql_is_evaluable(
+ sql, database.backend, len(distinct), from_suffix
+ ):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _mirror_verdict_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str:
+ """
+ `_probe_cache_key` without the values.
+
+ Whether a transform can be evaluated at all is a property of the transform
+ and the connection, not of the filter that happened to be probing it, so
+ one chart's answer settles the question for the next one.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_verdict:{digest}"
+
+
+def record_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ *,
+ mirrors: bool,
+) -> None:
+ """
+ Remember whether this transform produced a mirror, for the UI to read.
+
+ Advisory only. Nothing in the query path consults it: a probe that failed
+ once is retried on the next chart exactly as it is today, because declining
+ to prune for a whole cache timeout over one transient engine blip is the
+ trade `evaluate_transform` deliberately refuses -- see the comment where it
+ declines to cache a failure.
+
+ What this is for is the *claim*. `is_transform_active` parses the transform
+ and no more, so a transform the database rejects -- a misspelled function
+ is the common case -- is "active", and the editor's banner and Explore's
+ pruning glyph promise a speed-up that never happens. A promise is exactly
+ the thing that may be withheld on one bad answer and restored on a good
+ one, which is why this is a separate entry from the probe's own results
+ rather than a relaxation of that rule.
+
+ Written by `_run_probe`, so the preview endpoint -- which shares the
+ evaluator -- settles the question before the owner has even saved.
+ """
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(
+ _mirror_verdict_cache_key(database, catalog, schema, transform),
+ mirrors,
+ timeout=timeout,
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform verdict", exc_info=True)
+
+
+def known_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> bool | None:
+ """
+ The last verdict `record_mirror_verdict` stored, or `None` if there is none.
+
+ `None` is the honest answer on a cold cache and is deliberately not `False`:
+ reporting a working mapping as broken until something probes it would
+ trade one wrong claim for another. The alternative -- probing from the
+ read side -- would put a warehouse round trip on every Explore and
+ dashboard load, and a failing transform is not cached at all, so it would
+ be a round trip every single time.
+ """
+ try:
+ verdict = cache_manager.cache.get(
+ _mirror_verdict_cache_key(database, catalog, schema, transform)
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return verdict if isinstance(verdict, bool) else None
+
+
+def _compile_literal(element: Any, dialect: Dialect | None) -> str:
+ """
+ Compile with inline literals, undoing the paramstyle's percent doubling.
+
+ Both ``TextClause`` and literal compilation run the dialect's
+ ``post_process_text``, which doubles every ``%`` whenever the identifier
+ preparer asks it to -- true for MySQL and Postgres and for every spec
+ inheriting their paramstyle. That doubling exists so a later DBAPI
+ parameter-interpolation pass can undo it, and the probe has no such pass:
+ it executes with no bound parameters at all. So a transform of
+ ``date_format(:value, '%Y%m%d')`` reaches the warehouse asking for the
+ literal string ``%%Y%%m%%d``, the probe returns that instead of a date, and
+ the mirrored predicate drops every row the filter keeps.
+
+ The same normalization ``Database.compile_sqla_query`` applies for the same
+ reason. ``_double_percents`` is private and not guaranteed on a third-party
+ dialect, hence the ``getattr`` default.
+ """
+ compiled = str(
+ element.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
+ )
+ if dialect is not None and getattr(
+ dialect.identifier_preparer, "_double_percents", False
+ ):
+ compiled = compiled.replace("%%", "%")
+ return compiled
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be *asked* to stand in for itself, and the transform
+ cannot carry Jinja or call a non-deterministic function. Tier 2
+ (``blocking=False``) is everything that merely leaves the mapping inactive
+ -- including a self-mapping nobody asked for, where the partition column
+ merely happens to be the default datetime column.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column == partition_column:
+ # Asked for explicitly, so report it as the mistake it is.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+ elif not partition_mapped_column and main_dttm_col == partition_column:
+ # Resolved onto itself only because the default datetime column happens
+ # to be the partition column -- a state metadata sync could produce
+ # without anyone asking for it. The mapping is inert either way, since
+ # `resolve_partition_mapping` bails out on it, so this reports and lets
+ # the write through: blocking here means a dataset already in the state
+ # can never be saved again, not even to change its description, and
+ # there is no field whose edit would clear the error first.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "%(name)s is both the partition column and the default "
+ "datetime column, so the mapping points at itself and "
+ "stays inactive. Set a mapped column override, or change "
+ "the default datetime column.",
+ name=partition_column,
+ ),
+ blocking=False,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_bare_expression(transform, engine):
+ # Blocking, and deliberately placed in `validate_transform` rather than
+ # only at the probe: one issue here closes the PUT, the importer, the
+ # query-time gate through `is_transform_active`, the Explore indicator's
+ # active verdict and the preview endpoint, all of which already consult
+ # this function.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform must be a single SQL expression. It "
+ "cannot carry a FROM, WHERE, GROUP BY or any other clause, "
+ "and it cannot contain a sub-query."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not contains_value_placeholder(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform must contain the :value placeholder, "
+ "which stands for the filter value being mirrored."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not placeholder_is_executable(transform, engine):
+ # Blocking, and for the same reason the shape gate above is: this is
+ # the function the PUT, the importer, `is_transform_active`, the
+ # Explore indicator and the preview all consult, so one issue here
+ # closes every door at once. A placeholder inside a string literal is
+ # a sub-query the engine will run once a filter value closes the quote;
+ # one inside a comment silently eats the probe's own alias.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The :value placeholder must appear where the engine will "
+ "evaluate it. It cannot sit inside a string literal or a "
+ "comment."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if functions := find_non_deterministic_functions(transform, engine):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform calls %(functions)s, whose result "
+ "depends on when and where it runs. The transform is "
+ "evaluated in a separate session and the result is cached, "
+ "so the emitted predicate would freeze a snapshot of that "
+ "moment.",
+ functions=", ".join(sorted(functions)),
+ ),
+ blocking=True,
+ )
+ ]
+
+ return []
+
+
+@lru_cache(maxsize=LRU_CACHE_MAX_SIZE)
+def is_transform_active(transform: str | None, engine: str) -> bool:
+ """
+ Whether Superset will mirror filters through this transform.
+
+ `validate_transform` with the messages discarded, so the Explore indicator
+ cannot advertise a mapping the save path recorded as inactive. Anything
+ cheaper here would be a second, weaker statement of the same rule, free to
+ drift from the one the save path applies.
+
+ Blocking issues count too. Jinja and non-deterministic transforms are
+ rejected on PUT, but `CreateDatasetCommand` and import do not validate the
+ mapping, so one can still reach the database -- and it would never mirror a
+ filter either.
+
+ Memoized because `partition_filter_mapping_summary` is serialized on every
+ Explore and dashboard load and this parses the transform. The key is
+ everything the answer depends on: `validate_transform` reads no session, no
+ locale and no config beyond `SQL_MAX_PARSE_LENGTH`, which bounds the parser
+ rather than changing a verdict within that bound.
+ """
+ return not validate_transform(transform, engine)
+
+
+def preview_partition_mapping( # pylint: disable=too-many-return-statements
+ datasource: SqlaTable,
+ *,
+ mapped_column: str,
+ value_transform: str | None,
+ sample_values: list[str],
+ operator: FilterOperator = FilterOperator.EQUALS,
+ is_monotonic: bool = False,
+ partition_column: str | None = None,
+) -> dict[str, Any]:
+ """
+ Evaluate a candidate mapping and describe the predicate it would emit.
+
+ Shares the evaluator -- and therefore the probe cache -- with the query
+ path, so preview and runtime cannot drift and a previewed transform warms
+ the chart path for free. The predicate itself comes from
+ `build_mirrored_predicates`, the same builder the query path uses, so
+ operator shapes cannot drift either: what the panel shows is what a chart
+ would emit.
+
+ Validation runs first and the engine second: a half-typed transform is by
+ definition unparseable, so most of what a text input produces costs zero
+ queries.
+
+ Every part of the mapping is taken from the request rather than the stored
+ dataset. The editor previews while the owner is still editing -- a mapping
+ that has to be saved before it can be checked is not a preview.
+ """
+ partition_column = partition_column or datasource.partition_column
+ if not partition_column:
+ return {
+ "valid": False,
+ "reason": "unconfigured",
+ "error": _("No partition column is set."),
+ }
+
+ columns_by_name = {str(column.column_name): column for column in datasource.columns}
+ if mapped_column not in columns_by_name:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _("%(name)s is not a column on this dataset.", name=mapped_column),
+ }
+
+ # The bail-out `resolve_partition_mapping` makes at query time, and that
+ # `partition_filter_mapping_summary` repeats for the Explore indicator.
+ # Without it here, preview reports a valid emitted predicate for a mapping
+ # no chart will ever mirror -- the one answer a preview panel must not give.
+ if has_active_advanced_data_type(columns_by_name[mapped_column]):
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _(
+ "%(name)s has an advanced data type, so its filters are "
+ "translated into their own predicate shape and cannot be "
+ "mirrored onto the partition column.",
+ name=mapped_column,
+ ),
+ }
+
+ engine = datasource.database.backend
+ for issue in validate_partition_mapping(
+ column_names=set(columns_by_name),
+ partition_column=str(partition_column),
+ partition_mapped_column=mapped_column,
+ main_dttm_col=datasource.main_dttm_col,
+ transform=value_transform,
+ engine=engine,
+ ):
+ return {
+ "valid": False,
+ # The parse failure is the one an owner sees constantly, and it is
+ # the only one the mockup gives its own headline to.
+ "reason": (
+ "parse"
+ if issue.field == "partition_value_transform"
+ and not is_parseable(value_transform, engine)
+ else "validation"
+ ),
+ "error": str(issue.message),
+ }
+
+ # The policy every other stored expression goes through. The save path
+ # applies it in `UpdateDatasetCommand._validate_partition_mapping`, but
+ # preview evaluates a candidate transform that has not been saved, so
+ # without this the gate had a door around it. See
+ # `stored_expression_error` for what is being kept out and why.
+ if reason := stored_expression_error(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ cast(str, value_transform),
+ ):
+ return {"valid": False, "reason": "validation", "error": reason}
+
+ mapping = PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=mapped_column,
+ value_transform=cast(str, value_transform),
+ is_monotonic=is_monotonic,
+ equality_is_safe=equality_mirrors_safely(
+ columns_by_name[mapped_column], datasource.database.db_engine_spec
+ ),
+ )
+ sample_input = _render_sample_input(
+ datasource, mapped_column, operator, sample_values
+ )
+
+ if operator not in PREVIEWABLE_OPERATORS:
+ # Checked before `mirrors`, which lets `TEMPORAL_RANGE` through when the
+ # transform is declared monotonic -- and the single sample value would
+ # then reach `handle_comparison_filter`, which has no case for a range
+ # and raises. The request schema rejects it too; this keeps the function
+ # honest for any other caller.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is mirrored as a pair of bounds, which "
+ "a preview of a single value cannot describe.",
+ operator=operator.value,
+ ),
+ }
+
+ if not mapping.mirrors(operator):
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is only mirrored when the transform "
+ "preserves ordering, which this one is not declared to do.",
+ operator=operator.value,
+ ),
+ }
+
+ return _preview_probe(
+ datasource,
+ mapping,
+ columns_by_name[mapped_column],
+ operator,
+ sample_values,
+ sample_input,
+ )
+
+
+def _preview_probe(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ mapped_col: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+ sample_input: str,
+) -> dict[str, Any]:
+ """
+ The half of a preview that needs the warehouse.
+
+ Split out from `preview_partition_mapping` so that the gates which answer
+ from the stored mapping alone stay readable as the single run of guard
+ clauses they are. Everything here has either run a query or decided not to.
+ """
+ value = datasource.mirror_probe_request(
+ operator,
+ _probe_input(datasource, mapped_col, operator, sample_values),
+ mapped_col,
+ )
+ if value is UNMIRRORABLE:
+ # The same step the chart path applies, so the preview cannot promise a
+ # mirror the query declines. Its own reason: the transform is fine and
+ # the engine evaluates it, the filter just carries more of the value
+ # than the engine compares on this column -- which is the column's type
+ # talking, not a broken expression.
+ return {
+ "valid": False,
+ "reason": "resolution",
+ "sample_input": sample_input,
+ "error": _(
+ "This engine compares less of a %(operator)s value on "
+ "%(column)s than the filter carries, so there is no mirror a "
+ "predicate on the partition column could stand in for. Map a "
+ "column the engine compares in full to mirror this operator.",
+ operator=operator.value,
+ column=mapped_col.column_name,
+ ),
+ }
+ errors: list[str] = []
+ type_errors: list[str] = []
+ predicates = build_mirrored_predicates(
+ datasource,
+ mapping,
+ [(operator, value)],
+ errors=errors,
+ type_errors=type_errors,
+ )
+ if type_errors:
+ # Its own reason, because "the database would not evaluate this" and
+ # "it evaluated and answered with the wrong kind of thing" are
+ # different problems with different fixes, and the owner is the only
+ # one who can tell which transform they meant to write.
+ return {
+ "valid": False,
+ "reason": "type",
+ "sample_input": sample_input,
+ "error": type_errors[0],
+ }
+ if not predicates:
+ return {
+ "valid": False,
+ "reason": "engine",
+ "sample_input": sample_input,
+ "error": (
+ _(
+ "The transform could not be evaluated against the "
+ "database: %(reason)s",
+ reason=errors[0],
+ )
+ if errors
+ else _("The transform could not be evaluated against the database.")
+ ),
+ }
+
+ return {
+ "valid": True,
+ "sample_input": sample_input,
+ "emitted_predicate": _render_predicate(datasource, predicates[0]),
+ }
+
+
+def _probe_input(
+ datasource: SqlaTable,
+ column: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+) -> Any:
+ """
+ The sample values as the query path would bind them.
+
+ The request carries samples as strings, and the probe is keyed on exactly
+ what it is handed, so passing them through raw asks the engine a different
+ question from the one a chart asks. A sample of ``2025`` on a numeric
+ column has to arrive as the integer the chart compares: under a transform
+ of ``typeof(:value)`` the raw string previewed ``'text'`` where the chart
+ emitted ``'integer'``. And because `_probe_cache_key` keys on each value's
+ ``repr``, the two also missed each other's cache entirely -- so the "a
+ previewed transform warms the chart path for free" claim in
+ `preview_partition_mapping`'s docstring did not actually hold.
+
+ Coerced by `filter_values_handler`, the same function the query path uses,
+ rather than by a second implementation of the same rules. Everything the
+ query path then does to the coerced value -- rendering an expression as a
+ literal, widening a bound, declining a comparison the engine resolves too
+ coarsely -- is `ExploreMixin.mirror_probe_request`'s, and the caller hands
+ this result straight to it.
+
+ Ranges are not previewable (see `PREVIEWABLE_OPERATORS`), so the bound
+ conversion `_collect_partition_mirror_range` applies -- a ``datetime`` into
+ the column's stored representation -- has no counterpart here.
+
+ :returns: `UNMIRRORABLE` where the samples cannot be coerced at all
+ """
+ is_list = operator == FilterOperator.IN
+ column_spec = datasource.db_engine_spec.get_column_spec(native_type=column.type)
+ handled = datasource.filter_values_handler(
+ # `list[str]` is not a `list[FilterValue]` to mypy, invariantly, even
+ # though every `str` is a `FilterValue`.
+ values=cast(FilterValues, sample_values if is_list else sample_values[0]),
+ operator=operator,
+ target_generic_type=(
+ column_spec.generic_type if column_spec else utils.GenericDataType.STRING
+ ),
+ target_native_type=column.type,
+ is_list_target=is_list,
+ db_engine_spec=datasource.db_engine_spec,
+ db_extra=datasource.db_extra,
+ )
+ # No `ColumnElement` conversion here: an epoch-milliseconds sample comes back
+ # as engine SQL rather than a value, and `mirror_probe_request` renders it --
+ # the same step, on the same values, as for a chart filter.
+ return handled
+
+
+def _render_sample_input(
+ datasource: SqlaTable,
+ mapped_column: str,
+ operator: FilterOperator,
+ values: list[str],
+) -> str:
+ """
+ The filter being previewed, written the way an owner would read it.
+
+ Display-only -- it is never executed -- but it is still read as SQL, so the
+ column is quoted and the values are rendered by the dialect rather than
+ concatenated raw. A column named ``order date`` would otherwise come out as
+ two bare words.
+ """
+ quoted = datasource.quote_identifier(mapped_column)
+ if operator == FilterOperator.IN:
+ rendered = ", ".join(
+ _render_literal(datasource.database, value) for value in values
+ )
+ return f"{quoted} IN ({rendered})"
+ return (
+ f"{quoted} {operator.value} {_render_literal(datasource.database, values[0])}"
+ )
+
+
+def _render_predicate(datasource: SqlaTable, predicate: ColumnElement[Any]) -> str:
+ """
+ Compile a mirrored predicate to the text a reader would see in View query.
+
+ Every value in it is a probed constant by this point, so ``literal_binds``
+ renders the same literals the chart query carries.
+ """
+ return _compile_literal(predicate, _dialect_for(datasource.database)).replace(
+ "\n", " "
+ )
+
+
+def _render_literal(database: Database, value: Any) -> str:
+ """
+ Render a value the way it appears in the generated SQL.
+
+ Compiled by the dialect rather than formatted by hand. `str()` would render
+ a NULL as the Python repr `None` and leave a date unquoted, neither of which
+ is SQL, and hand-rolled quote-doubling would only ever have been right for
+ strings.
+ """
+ return _compile_literal(sa.literal(value), _dialect_for(database))
+
+
+def build_mirrored_predicates(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ requests: list[tuple[FilterOperator, Any]],
+ *,
+ errors: list[str] | None = None,
+ type_errors: list[str] | None = None,
+) -> list[ColumnElement[Any]]:
+ """
+ Turn collected ``(operator, value)`` mirror requests into predicates.
+
+ ``requests`` is expected to be deduplicated by the caller. Every value is
+ resolved in a single probe round trip -- one per chart query at most -- then
+ emitted as a literal constant, so "View query" shows the reader an ordinary
+ ``WHERE`` clause rather than an inline expression.
+
+ A strict bound is emitted non-strictly; see `mirror_operator`. That happens
+ here, at the one point where a ``FilterOperator`` becomes SQL, rather than
+ at the collection sites in `ExploreMixin`: the preview endpoint calls this
+ directly, so this is what keeps the predicate the editor shows an owner and
+ the predicate the chart carries from disagreeing.
+
+ :param errors: optional sink; see `evaluate_transform`.
+ :param type_errors: optional sink for a probe result the partition column
+ cannot hold -- see `probed_value_type_error`. Separate from ``errors``
+ because the two say different things to an owner: that one is "the
+ database would not evaluate this", and this one is "it evaluated, and
+ answered with the wrong kind of thing".
+ """
+ if not requests:
+ return []
+
+ partition_column = next(
+ (
+ column
+ for column in datasource.columns
+ if column.column_name == mapping.partition_column
+ ),
+ None,
+ )
+ if partition_column is None:
+ return []
+
+ # Flatten every value that needs probing into one list, remembering how many
+ # each request consumed so the results can be handed back out.
+ flat: list[Any] = []
+ spans: list[tuple[FilterOperator, int, int]] = []
+ for operator, value in requests:
+ values = list(value) if operator == FilterOperator.IN else [value]
+ spans.append((operator, len(flat), len(values)))
+ flat.extend(values)
+
+ evaluated = evaluate_transform(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ mapping.value_transform,
+ flat,
+ errors=errors,
+ )
+ if evaluated is None:
+ return []
+
+ if not _bounds_are_ordered(evaluated, spans):
+ return []
+
+ # Declining here is the last chance to decline at all: once these
+ # predicates are in the statement, a value the partition column cannot
+ # hold fails the whole chart rather than its pruning.
+ if reason := probed_value_type_error(partition_column, evaluated):
+ logger.warning(
+ "Partition transform returned a value the partition column cannot "
+ "hold; queries will not prune: %s",
+ reason,
+ )
+ if type_errors is not None:
+ type_errors.append(reason)
+ record_mirror_verdict(
Review Comment:
Fixed. The entry under `_mirror_verdict_cache_key` is now only the evaluability claim — whether the engine ran the transform at all — which really is a property of the transform and the connection. It is written from exactly one place, `_run_probe`; the dataset-specific type verdict is no longer cached there.
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2338 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error(
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the probe
+ uninspected -- string elements are escaped by the dialect's own literal
+ processor. `probe_sql_is_evaluable` then re-reads the finished query, which
+ is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ else:
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ rendered = _compile_literal(clause, dialect)
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Four things have to hold, and all four are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if not isinstance(statement, SQLStatement):
+ # A dialect whose statements this gate cannot take apart -- KQL -- gets
+ # no probe rather than an unchecked one. It never had one: the clause
+ # inspection below is implemented for SQL statements only, and the
+ # alternative to declining here is an `AttributeError` that `_probe`
+ # swallows into the same outcome, less legibly.
+ return False
+ if statement.has_subquery():
+ return False
+ if statement.get_clause_names() - {"from"}:
+ return False
+ if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+ """
+ The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+ Parsed rather than string-compared so that the comparison in
+ `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+ not parse answers ``None``, which no statement carrying a FROM can match --
+ the probe then declines, which is the right way for an unreadable engine
+ constant to fail.
+ """
+ if not from_suffix.strip():
+ return None
+ try:
+ return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+ except SupersetParseError:
+ return None
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=values is not None and not any(value is None for value in values),
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ from_suffix = database.db_engine_spec.select_without_from_suffix
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ from_suffix,
+ )
+ if not probe_sql_is_evaluable(
+ sql, database.backend, len(distinct), from_suffix
+ ):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _mirror_verdict_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str:
+ """
+ `_probe_cache_key` without the values.
+
+ Whether a transform can be evaluated at all is a property of the transform
+ and the connection, not of the filter that happened to be probing it, so
+ one chart's answer settles the question for the next one.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_verdict:{digest}"
+
+
+def record_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ *,
+ mirrors: bool,
+) -> None:
+ """
+ Remember whether this transform produced a mirror, for the UI to read.
+
+ Advisory only. Nothing in the query path consults it: a probe that failed
+ once is retried on the next chart exactly as it is today, because declining
+ to prune for a whole cache timeout over one transient engine blip is the
+ trade `evaluate_transform` deliberately refuses -- see the comment where it
+ declines to cache a failure.
+
+ What this is for is the *claim*. `is_transform_active` parses the transform
+ and no more, so a transform the database rejects -- a misspelled function
+ is the common case -- is "active", and the editor's banner and Explore's
+ pruning glyph promise a speed-up that never happens. A promise is exactly
+ the thing that may be withheld on one bad answer and restored on a good
+ one, which is why this is a separate entry from the probe's own results
+ rather than a relaxation of that rule.
+
+ Written by `_run_probe`, so the preview endpoint -- which shares the
+ evaluator -- settles the question before the owner has even saved.
+ """
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(
+ _mirror_verdict_cache_key(database, catalog, schema, transform),
+ mirrors,
+ timeout=timeout,
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform verdict", exc_info=True)
+
+
+def known_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> bool | None:
+ """
+ The last verdict `record_mirror_verdict` stored, or `None` if there is none.
+
+ `None` is the honest answer on a cold cache and is deliberately not `False`:
+ reporting a working mapping as broken until something probes it would
+ trade one wrong claim for another. The alternative -- probing from the
+ read side -- would put a warehouse round trip on every Explore and
+ dashboard load, and a failing transform is not cached at all, so it would
+ be a round trip every single time.
+ """
+ try:
+ verdict = cache_manager.cache.get(
+ _mirror_verdict_cache_key(database, catalog, schema, transform)
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return verdict if isinstance(verdict, bool) else None
+
+
+def _compile_literal(element: Any, dialect: Dialect | None) -> str:
+ """
+ Compile with inline literals, undoing the paramstyle's percent doubling.
+
+ Both ``TextClause`` and literal compilation run the dialect's
+ ``post_process_text``, which doubles every ``%`` whenever the identifier
+ preparer asks it to -- true for MySQL and Postgres and for every spec
+ inheriting their paramstyle. That doubling exists so a later DBAPI
+ parameter-interpolation pass can undo it, and the probe has no such pass:
+ it executes with no bound parameters at all. So a transform of
+ ``date_format(:value, '%Y%m%d')`` reaches the warehouse asking for the
+ literal string ``%%Y%%m%%d``, the probe returns that instead of a date, and
+ the mirrored predicate drops every row the filter keeps.
+
+ The same normalization ``Database.compile_sqla_query`` applies for the same
+ reason. ``_double_percents`` is private and not guaranteed on a third-party
+ dialect, hence the ``getattr`` default.
+ """
+ compiled = str(
+ element.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
+ )
+ if dialect is not None and getattr(
+ dialect.identifier_preparer, "_double_percents", False
+ ):
+ compiled = compiled.replace("%%", "%")
+ return compiled
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be *asked* to stand in for itself, and the transform
+ cannot carry Jinja or call a non-deterministic function. Tier 2
+ (``blocking=False``) is everything that merely leaves the mapping inactive
+ -- including a self-mapping nobody asked for, where the partition column
+ merely happens to be the default datetime column.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column == partition_column:
+ # Asked for explicitly, so report it as the mistake it is.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+ elif not partition_mapped_column and main_dttm_col == partition_column:
+ # Resolved onto itself only because the default datetime column happens
+ # to be the partition column -- a state metadata sync could produce
+ # without anyone asking for it. The mapping is inert either way, since
+ # `resolve_partition_mapping` bails out on it, so this reports and lets
+ # the write through: blocking here means a dataset already in the state
+ # can never be saved again, not even to change its description, and
+ # there is no field whose edit would clear the error first.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "%(name)s is both the partition column and the default "
+ "datetime column, so the mapping points at itself and "
+ "stays inactive. Set a mapped column override, or change "
+ "the default datetime column.",
+ name=partition_column,
+ ),
+ blocking=False,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_bare_expression(transform, engine):
+ # Blocking, and deliberately placed in `validate_transform` rather than
+ # only at the probe: one issue here closes the PUT, the importer, the
+ # query-time gate through `is_transform_active`, the Explore indicator's
+ # active verdict and the preview endpoint, all of which already consult
+ # this function.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform must be a single SQL expression. It "
+ "cannot carry a FROM, WHERE, GROUP BY or any other clause, "
+ "and it cannot contain a sub-query."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not contains_value_placeholder(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform must contain the :value placeholder, "
+ "which stands for the filter value being mirrored."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not placeholder_is_executable(transform, engine):
+ # Blocking, and for the same reason the shape gate above is: this is
+ # the function the PUT, the importer, `is_transform_active`, the
+ # Explore indicator and the preview all consult, so one issue here
+ # closes every door at once. A placeholder inside a string literal is
+ # a sub-query the engine will run once a filter value closes the quote;
+ # one inside a comment silently eats the probe's own alias.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The :value placeholder must appear where the engine will "
+ "evaluate it. It cannot sit inside a string literal or a "
+ "comment."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if functions := find_non_deterministic_functions(transform, engine):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform calls %(functions)s, whose result "
+ "depends on when and where it runs. The transform is "
+ "evaluated in a separate session and the result is cached, "
+ "so the emitted predicate would freeze a snapshot of that "
+ "moment.",
+ functions=", ".join(sorted(functions)),
+ ),
+ blocking=True,
+ )
+ ]
+
+ return []
+
+
+@lru_cache(maxsize=LRU_CACHE_MAX_SIZE)
+def is_transform_active(transform: str | None, engine: str) -> bool:
+ """
+ Whether Superset will mirror filters through this transform.
+
+ `validate_transform` with the messages discarded, so the Explore indicator
+ cannot advertise a mapping the save path recorded as inactive. Anything
+ cheaper here would be a second, weaker statement of the same rule, free to
+ drift from the one the save path applies.
+
+ Blocking issues count too. Jinja and non-deterministic transforms are
+ rejected on PUT, but `CreateDatasetCommand` and import do not validate the
+ mapping, so one can still reach the database -- and it would never mirror a
+ filter either.
+
+ Memoized because `partition_filter_mapping_summary` is serialized on every
+ Explore and dashboard load and this parses the transform. The key is
+ everything the answer depends on: `validate_transform` reads no session, no
+ locale and no config beyond `SQL_MAX_PARSE_LENGTH`, which bounds the parser
+ rather than changing a verdict within that bound.
+ """
+ return not validate_transform(transform, engine)
+
+
+def preview_partition_mapping( # pylint: disable=too-many-return-statements
+ datasource: SqlaTable,
+ *,
+ mapped_column: str,
+ value_transform: str | None,
+ sample_values: list[str],
+ operator: FilterOperator = FilterOperator.EQUALS,
+ is_monotonic: bool = False,
+ partition_column: str | None = None,
+) -> dict[str, Any]:
+ """
+ Evaluate a candidate mapping and describe the predicate it would emit.
+
+ Shares the evaluator -- and therefore the probe cache -- with the query
+ path, so preview and runtime cannot drift and a previewed transform warms
+ the chart path for free. The predicate itself comes from
+ `build_mirrored_predicates`, the same builder the query path uses, so
+ operator shapes cannot drift either: what the panel shows is what a chart
+ would emit.
+
+ Validation runs first and the engine second: a half-typed transform is by
+ definition unparseable, so most of what a text input produces costs zero
+ queries.
+
+ Every part of the mapping is taken from the request rather than the stored
+ dataset. The editor previews while the owner is still editing -- a mapping
+ that has to be saved before it can be checked is not a preview.
+ """
+ partition_column = partition_column or datasource.partition_column
+ if not partition_column:
+ return {
+ "valid": False,
+ "reason": "unconfigured",
+ "error": _("No partition column is set."),
+ }
+
+ columns_by_name = {str(column.column_name): column for column in datasource.columns}
+ if mapped_column not in columns_by_name:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _("%(name)s is not a column on this dataset.", name=mapped_column),
+ }
+
+ # The bail-out `resolve_partition_mapping` makes at query time, and that
+ # `partition_filter_mapping_summary` repeats for the Explore indicator.
+ # Without it here, preview reports a valid emitted predicate for a mapping
+ # no chart will ever mirror -- the one answer a preview panel must not give.
+ if has_active_advanced_data_type(columns_by_name[mapped_column]):
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _(
+ "%(name)s has an advanced data type, so its filters are "
+ "translated into their own predicate shape and cannot be "
+ "mirrored onto the partition column.",
+ name=mapped_column,
+ ),
+ }
+
+ engine = datasource.database.backend
+ for issue in validate_partition_mapping(
+ column_names=set(columns_by_name),
+ partition_column=str(partition_column),
+ partition_mapped_column=mapped_column,
+ main_dttm_col=datasource.main_dttm_col,
+ transform=value_transform,
+ engine=engine,
+ ):
+ return {
+ "valid": False,
+ # The parse failure is the one an owner sees constantly, and it is
+ # the only one the mockup gives its own headline to.
+ "reason": (
+ "parse"
+ if issue.field == "partition_value_transform"
+ and not is_parseable(value_transform, engine)
+ else "validation"
+ ),
+ "error": str(issue.message),
+ }
+
+ # The policy every other stored expression goes through. The save path
+ # applies it in `UpdateDatasetCommand._validate_partition_mapping`, but
+ # preview evaluates a candidate transform that has not been saved, so
+ # without this the gate had a door around it. See
+ # `stored_expression_error` for what is being kept out and why.
+ if reason := stored_expression_error(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ cast(str, value_transform),
+ ):
+ return {"valid": False, "reason": "validation", "error": reason}
+
+ mapping = PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=mapped_column,
+ value_transform=cast(str, value_transform),
+ is_monotonic=is_monotonic,
+ equality_is_safe=equality_mirrors_safely(
+ columns_by_name[mapped_column], datasource.database.db_engine_spec
+ ),
+ )
+ sample_input = _render_sample_input(
+ datasource, mapped_column, operator, sample_values
+ )
+
+ if operator not in PREVIEWABLE_OPERATORS:
+ # Checked before `mirrors`, which lets `TEMPORAL_RANGE` through when the
+ # transform is declared monotonic -- and the single sample value would
+ # then reach `handle_comparison_filter`, which has no case for a range
+ # and raises. The request schema rejects it too; this keeps the function
+ # honest for any other caller.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is mirrored as a pair of bounds, which "
+ "a preview of a single value cannot describe.",
+ operator=operator.value,
+ ),
+ }
+
+ if not mapping.mirrors(operator):
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is only mirrored when the transform "
+ "preserves ordering, which this one is not declared to do.",
+ operator=operator.value,
+ ),
+ }
+
+ value = _probe_input(
+ datasource, columns_by_name[mapped_column], operator, sample_values
+ )
+ errors: list[str] = []
+ type_errors: list[str] = []
+ predicates = build_mirrored_predicates(
+ datasource,
+ mapping,
+ [(operator, value)],
+ errors=errors,
+ type_errors=type_errors,
+ )
+ if type_errors:
+ # Its own reason, because "the database would not evaluate this" and
+ # "it evaluated and answered with the wrong kind of thing" are
+ # different problems with different fixes, and the owner is the only
+ # one who can tell which transform they meant to write.
+ return {
+ "valid": False,
+ "reason": "type",
+ "sample_input": sample_input,
+ "error": type_errors[0],
+ }
+ if not predicates:
+ return {
+ "valid": False,
+ "reason": "engine",
+ "sample_input": sample_input,
+ "error": (
+ _(
+ "The transform could not be evaluated against the "
+ "database: %(reason)s",
+ reason=errors[0],
+ )
+ if errors
+ else _("The transform could not be evaluated against the database.")
+ ),
+ }
+
+ return {
+ "valid": True,
+ "sample_input": sample_input,
+ "emitted_predicate": _render_predicate(datasource, predicates[0]),
+ }
+
+
+def _probe_input(
+ datasource: SqlaTable,
+ column: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+) -> Any:
+ """
+ The sample values as the query path would bind them.
+
+ The request carries samples as strings, and the probe is keyed on exactly
+ what it is handed, so passing them through raw asks the engine a different
+ question from the one a chart asks. A sample of ``2025`` on a numeric
+ column has to arrive as the integer the chart compares: under a transform
+ of ``typeof(:value)`` the raw string previewed ``'text'`` where the chart
+ emitted ``'integer'``. And because `_probe_cache_key` keys on each value's
+ ``repr``, the two also missed each other's cache entirely -- so the "a
+ previewed transform warms the chart path for free" claim in
+ `preview_partition_mapping`'s docstring did not actually hold.
+
+ Coerced by `filter_values_handler`, the same function the query path uses,
+ rather than by a second implementation of the same rules.
+
+ Ranges are not previewable (see `PREVIEWABLE_OPERATORS`), so the bound
+ conversion `_collect_partition_mirror_range` applies -- a ``datetime`` into
+ the column's stored representation -- has no counterpart here.
+ """
+ is_list = operator == FilterOperator.IN
+ column_spec = datasource.db_engine_spec.get_column_spec(native_type=column.type)
+ handled = datasource.filter_values_handler(
+ # `list[str]` is not a `list[FilterValue]` to mypy, invariantly, even
+ # though every `str` is a `FilterValue`.
+ values=cast(FilterValues, sample_values if is_list else sample_values[0]),
+ operator=operator,
+ target_generic_type=(
+ column_spec.generic_type if column_spec else utils.GenericDataType.STRING
+ ),
+ target_native_type=column.type,
+ is_list_target=is_list,
+ db_engine_spec=datasource.db_engine_spec,
+ db_extra=datasource.db_extra,
+ )
+
+ def bindable(value: Any) -> Any:
+ # An epoch-milliseconds sample on a temporal column comes back as
+ # engine SQL rather than a value, and SQL cannot be the value of a bind
+ # parameter -- carried as text so the probe substitutes it, the same way
+ # an array literal is.
+ if isinstance(value, ColumnElement):
+ return raw_probe_value(datasource.database, value)
+ return value
+
+ if is_list and isinstance(handled, (list, tuple)):
+ return [bindable(entry) for entry in handled]
+ return bindable(handled)
+
+
+def _render_sample_input(
+ datasource: SqlaTable,
+ mapped_column: str,
+ operator: FilterOperator,
+ values: list[str],
+) -> str:
+ """
+ The filter being previewed, written the way an owner would read it.
+
+ Display-only -- it is never executed -- but it is still read as SQL, so the
+ column is quoted and the values are rendered by the dialect rather than
+ concatenated raw. A column named ``order date`` would otherwise come out as
+ two bare words.
+ """
+ quoted = datasource.quote_identifier(mapped_column)
+ if operator == FilterOperator.IN:
+ rendered = ", ".join(
+ _render_literal(datasource.database, value) for value in values
+ )
+ return f"{quoted} IN ({rendered})"
+ return (
+ f"{quoted} {operator.value} {_render_literal(datasource.database, values[0])}"
+ )
+
+
+def _render_predicate(datasource: SqlaTable, predicate: ColumnElement[Any]) -> str:
+ """
+ Compile a mirrored predicate to the text a reader would see in View query.
+
+ Every value in it is a probed constant by this point, so ``literal_binds``
+ renders the same literals the chart query carries.
+ """
+ return _compile_literal(predicate, _dialect_for(datasource.database)).replace(
+ "\n", " "
+ )
+
+
+def _render_literal(database: Database, value: Any) -> str:
+ """
+ Render a value the way it appears in the generated SQL.
+
+ Compiled by the dialect rather than formatted by hand. `str()` would render
+ a NULL as the Python repr `None` and leave a date unquoted, neither of which
+ is SQL, and hand-rolled quote-doubling would only ever have been right for
+ strings.
+ """
+ return _compile_literal(sa.literal(value), _dialect_for(database))
+
+
+def build_mirrored_predicates(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ requests: list[tuple[FilterOperator, Any]],
+ *,
+ errors: list[str] | None = None,
+ type_errors: list[str] | None = None,
+) -> list[ColumnElement[Any]]:
+ """
+ Turn collected ``(operator, value)`` mirror requests into predicates.
+
+ ``requests`` is expected to be deduplicated by the caller. Every value is
+ resolved in a single probe round trip -- one per chart query at most -- then
+ emitted as a literal constant, so "View query" shows the reader an ordinary
+ ``WHERE`` clause rather than an inline expression.
+
+ A strict bound is emitted non-strictly; see `mirror_operator`. That happens
+ here, at the one point where a ``FilterOperator`` becomes SQL, rather than
+ at the collection sites in `ExploreMixin`: the preview endpoint calls this
+ directly, so this is what keeps the predicate the editor shows an owner and
+ the predicate the chart carries from disagreeing.
+
+ :param errors: optional sink; see `evaluate_transform`.
+ :param type_errors: optional sink for a probe result the partition column
+ cannot hold -- see `probed_value_type_error`. Separate from ``errors``
+ because the two say different things to an owner: that one is "the
+ database would not evaluate this", and this one is "it evaluated, and
+ answered with the wrong kind of thing".
+ """
+ if not requests:
+ return []
+
+ partition_column = next(
+ (
+ column
+ for column in datasource.columns
+ if column.column_name == mapping.partition_column
+ ),
+ None,
+ )
+ if partition_column is None:
+ return []
+
+ # Flatten every value that needs probing into one list, remembering how many
+ # each request consumed so the results can be handed back out.
+ flat: list[Any] = []
+ spans: list[tuple[FilterOperator, int, int]] = []
+ for operator, value in requests:
+ values = list(value) if operator == FilterOperator.IN else [value]
+ spans.append((operator, len(flat), len(values)))
+ flat.extend(values)
+
+ evaluated = evaluate_transform(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ mapping.value_transform,
+ flat,
+ errors=errors,
+ )
+ if evaluated is None:
+ return []
+
+ if not _bounds_are_ordered(evaluated, spans):
+ return []
+
+ # Declining here is the last chance to decline at all: once these
+ # predicates are in the statement, a value the partition column cannot
+ # hold fails the whole chart rather than its pruning.
+ if reason := probed_value_type_error(partition_column, evaluated):
+ logger.warning(
+ "Partition transform returned a value the partition column cannot "
+ "hold; queries will not prune: %s",
+ reason,
+ )
+ if type_errors is not None:
+ type_errors.append(reason)
+ record_mirror_verdict(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ mapping.value_transform,
+ mirrors=False,
+ )
+ return []
+
+ sqla_col = datasource.convert_tbl_column_to_sqla_col(partition_column)
+ predicates = _predicates_from_probe(
+ sqla_col, datasource.db_engine_spec, evaluated, spans
+ )
+ if not predicates:
+ return []
+
+ # A comparison against a NULL partition value is NULL, so a row parked in a
+ # NULL partition is dropped by the mirror even when the real filter matches
+ # it -- Hive and Impala's default partition, or a transform that returns
+ # NULL for an input it cannot convert. The mirror only has to be no
+ # narrower than the filter it stands in for, so admitting NULL partitions
+ # keeps those rows. Engines still prune; they read one extra partition.
+ return [sa.or_(sa.and_(*predicates), sqla_col.is_(None))]
+
+
+def _predicates_from_probe(
+ sqla_col: ColumnElement[Any],
+ db_engine_spec: type[BaseEngineSpec],
+ evaluated: list[Any],
+ spans: list[tuple[FilterOperator, int, int]],
+) -> list[ColumnElement[Any]]:
+ """
+ One predicate on the partition column per surviving mirror request.
+
+ A request whose probe answered `None` for any of its values is skipped
+ rather than emitted: `col = NULL` is `NULL`, so it would drop every row the
+ filter keeps. A strict bound is emitted non-strictly; see `mirror_operator`.
+ """
+ predicates: list[ColumnElement[Any]] = []
+ for operator, start, length in spans:
+ chunk = evaluated[start : start + length]
+ if any(value is None for value in chunk):
+ continue
+ if operator == FilterOperator.IN:
+ # The probe answers per value, so a transform over a mixed-number
+ # filter can answer with a mixed-number partition key -- and
+ # `in_` infers the bind type from the first element it is handed.
+ # Without this, probe results of `[33, 29.02]` emit
+ # `IN (33, 29)` and prune away the partition holding `29.02`.
+ predicates.append(sqla_col.in_(normalize_mixed_numbers(chunk)))
+ else:
+ predicates.append(
+ db_engine_spec.handle_comparison_filter(
+ sqla_col, mirror_operator(operator), chunk[0]
+ )
+ )
+ return predicates
+
+
+#: Operators whose value is the lower end of a range, and whose upper-end twins.
+#:
+#: Shared with `ExploreMixin._mirror_probe_input`, which rounds a bound *outward*
+#: where the engine resolves it more coarsely than the filter carries -- backward
+#: for a lower bound, forward for an upper one. Which end an operator names is
+#: the only thing separating the two directions in either caller, so the two have
+#: to agree on it rather than each classify for itself.
+LOWER_BOUND_OPERATORS = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+}
+UPPER_BOUND_OPERATORS = {
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+#: What Python type a probe result may have, per generic type of the partition
+#: column it is about to be compared against.
+#:
+#: Only the types a mismatch can actually break a query with are listed. An
+#: unresolvable column type is absent because there is nothing to check
+#: against, and ``MULTI_VALUE`` because this module does not mirror onto an
+#: array partition key at all.
+#: ``numbers.Number`` rather than ``(int, float)``: Postgres answers
+#: ``extract(epoch from ...)`` with a `Decimal`, which is the single commonest
+#: transform this feature has, and an engine is free to answer with any number
+#: type its driver prefers. What the check is for is a *string* where a number
+#: belongs, and every numeric type is equally not that.
+_PROBE_RESULT_TYPES: dict[utils.GenericDataType, tuple[type, ...]] = {
+ utils.GenericDataType.NUMERIC: (numbers.Number,),
+ utils.GenericDataType.BOOLEAN: (bool,),
+ # A day key such as ``to_char(:value, 'YYYYMMDD')`` is legitimately text.
+ utils.GenericDataType.TEMPORAL: (datetime, date, str),
Review Comment:
Fixed. `_reads_as_temporal` asks the engine whether it would read that text as an instant; a string the engine would not parse is declined for a temporal partition column rather than mirrored into a predicate the engine rejects.
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,1314 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` always -- ``T`` is a function
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import re
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLStatement
+from superset.utils import json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: Every entry point enforces it -- the typed column field, the import schema
+#: and the preview request -- because `is_transform_active` parses the stored
+#: value on each Explore load, and an unbounded string would make that parse
+#: the expensive part of rendering a chart.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+def mirrorable_operators(is_monotonic: bool) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ """
+ if is_monotonic:
+ return MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+ return set(MIRRORABLE_ALWAYS)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(self.is_monotonic)
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+ """
+ return VALUE_PLACEHOLDER_RE.sub(_PARSE_STANDIN, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(transform: str, engine: str) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
Review Comment:
Fixed. `stored_expression_error` requires `statement.is_bare_select_expression()` — rejected with "must be a single SQL expression, with no FROM, WHERE or other clause" — and refuses sub-queries unconditionally rather than under `ALLOW_ADHOC_SUBQUERY`. Those two together are what let the probe skip the table denylist and the RLS rewrite: with no FROM and no sub-query there is no table reference to govern.
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2730 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+#: Returned by `ExploreMixin.mirror_probe_request` for a filter no mirror can
+#: stand in for: one the engine compares more coarsely than the value carries, a
+#: value it cannot render as a literal, or an ``IN`` list with a member of
+#: either kind. A sentinel rather than `None`, because `None` is a filter value
+#: in its own right.
+#:
+#: Lives here rather than beside that method so the preview can read it too:
+#: `superset.models.helpers` imports this module, so the sentinel can only cross
+#: the boundary in this direction. Both callers have to recognise the same
+#: object -- a preview that answered "valid" for a request the chart path
+#: declines is the drift this is here to prevent.
+UNMIRRORABLE = object()
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
Review Comment:
Fixed. `_in_column_number_type` probes at the value the column would hold rather than at the submitted comparator, so `n = '1.0'` on an integer `n` mirrors through `T(1)` and not `T('1.0')`. Integer columns only — approximate and decimal columns are deliberately left alone, since how an engine renders those literals is not something the spec exposes.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "hughhhh (via GitHub)" <gi...@apache.org>.
hughhhh commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4319664119
##########
superset/commands/dataset/refresh.py:
##########
@@ -72,6 +72,22 @@ def run(self) -> Model:
ex.message,
)
+ # `fetch_metadata` writes the columns itself rather than going through
+ # `DatasetDAO.update`, so neither of the mapping's own repairs runs. It
+ # can drop the column `partition_column` names -- leaving a reference
+ # that fails `UpdateDatasetCommand`'s validation on every later edit,
+ # including a description-only PUT, which carries no columns payload and
+ # so cannot reach the branch that forgives a stored-only dangle -- and
+ # it can *set* `main_dttm_col`, which moves the effective mapped column
+ # and can bring a parked transform live.
+ #
+ # No flush needed to read the columns: `fetch_metadata` reassigns the
+ # relationship, so the surviving set is already correct in memory.
+ DatasetDAO.clear_dangling_partition_mapping(
+ self._model, {column.column_name for column in self._model.columns}
+ )
+ DatasetDAO.clear_unmapped_partition_transforms(self._model)
Review Comment:
Fixed. `clear_unmapped_partition_transforms` runs before the metadata change as well as after it, so the old mapping's real transform is no longer erased while a transform parked on the newly mapped column survives.
##########
superset/commands/dataset/update.py:
##########
@@ -416,6 +423,146 @@ def _validate_expressions(
)
)
+ def _validate_partition_mapping(self, exceptions: list[ValidationError]) -> None:
+ """
+ Validate the dataset's partition filter mapping.
+
+ Only the blocking (Tier 1) issues become validation errors. Tier 2
+ issues -- an unparseable transform, a transform missing `:value` --
+ deliberately let the save through and leave the mapping inactive, per
+ the PRD, so a half-written transform doesn't cost the owner the rest of
+ their edits. They are surfaced by the editor, not by rejecting the PUT.
+
+ The transform is authored by a dataset owner, the same principal and
+ trust level as a calculated-column expression, so it also goes through
+ `validate_stored_expression` -- the parser gate that already governs
+ stored expressions. That gate only applies to a transform that parses:
+ it rejects an unparseable expression outright, which would turn a Tier-2
+ issue into a blocking one and undo the paragraph above. Skipping it
+ there costs nothing -- an unparseable transform is never emitted into a
+ query -- and it is not a hole for templating, because Jinja in a
+ transform is already a Tier-1 blocking issue of its own.
+
+ Every path that *reads* a mapping is gated on the feature flag, so this
+ one is too: with the flag off nothing mirrors, and rejecting a save over
+ a mapping that can never be consumed would be a validation error the
+ owner has no way to act on.
+ """
+ if not is_feature_enabled("PARTITION_FILTER_MAPPING"):
+ return
+
+ self._model = cast(SqlaTable, self._model)
+
+ columns = self._properties.get("columns")
+ column_names = (
+ {column["column_name"] for column in columns}
+ if columns is not None
+ else {column.column_name for column in self._model.columns}
+ )
+
+ partition_column = self._properties.get(
+ "partition_column", self._model.partition_column
+ )
+ partition_mapped_column = self._properties.get(
+ "partition_mapped_column", self._model.partition_mapped_column
+ )
+ main_dttm_col = self._properties.get("main_dttm_col", self._model.main_dttm_col)
+ if not partition_column:
+ return
+
+ # A column payload drops every column it omits, and `update_columns`
+ # then runs `DatasetDAO.clear_dangling_partition_mapping` to drop a
+ # mapping whose columns went with them -- but that happens later, during
+ # `run()`. Validate the state that cleanup leaves behind, or a metadata
+ # sync that legitimately removes the mapped column is rejected before
+ # the cleanup meant to handle it ever runs, which is exactly the
+ # orphaned case the cleanup exists for.
+ #
+ # Only a *stored* reference is forgiven. Asking in this very request to
+ # map onto a column the same request does not define is a mistake worth
+ # reporting, not something to quietly clean up.
+ if columns is not None:
Review Comment:
Fixed. `RefreshDatasetCommand` runs `DatasetDAO.clear_dangling_partition_mapping` itself, so a reference the refresh drops is repaired there rather than left for the next PUT to fail on.
##########
superset/connectors/sqla/models.py:
##########
@@ -1689,6 +1726,8 @@ class SqlaTable(
"normalize_columns",
"always_filter_main_dttm",
"folders",
+ "partition_column",
Review Comment:
Fixed. `DuplicateDatasetCommand` now copies `partition_value_transform` and `partition_transform_is_monotonic` when it reconstructs the columns, so the clone's mapping survives.
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2338 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error(
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the probe
+ uninspected -- string elements are escaped by the dialect's own literal
+ processor. `probe_sql_is_evaluable` then re-reads the finished query, which
+ is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ else:
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
Review Comment:
Fixed. The question is answered by attempting the bind itself — `sa.text(transform).bindparams(sa.bindparam("value", value=None))` in a try — rather than by pattern-matching `::` or reading `text()`'s private parameter map, so it cannot disagree with what `build_probe_sql` is about to do on any dialect.
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,1314 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` always -- ``T`` is a function
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import re
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLStatement
+from superset.utils import json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: Every entry point enforces it -- the typed column field, the import schema
+#: and the preview request -- because `is_transform_active` parses the stored
+#: value on each Explore load, and an unbounded string would make that parse
+#: the expensive part of rendering a chart.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+def mirrorable_operators(is_monotonic: bool) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ """
+ if is_monotonic:
+ return MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+ return set(MIRRORABLE_ALWAYS)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(self.is_monotonic)
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+ """
+ return VALUE_PLACEHOLDER_RE.sub(_PARSE_STANDIN, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(transform: str, engine: str) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def stored_expression_error(
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ The same subquery, function-denylist and RLS policy every other stored
+ expression goes through, applied to a value transform. It matters more
+ here than the name suggests: `build_probe_sql` binds only `:value` and
+ splices the rest of the transform in as SQL text, which the engine then
+ executes, so an ungated transform is arbitrary SQL. A dataset editor
+ without SQL Lab could store `(SELECT secret FROM protected_table LIMIT 1)
+ || :value` and read the answer back out of the emitted predicate.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+ """
+ selections = []
+ for index, value in enumerate(values):
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ compiled = clause.compile(
+ dialect=dialect,
+ compile_kwargs={"literal_binds": True},
+ )
+ selections.append(f"{compiled} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ database.db_engine_spec.select_without_from_suffix,
+ )
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ row = frame.iloc[0]
+ if len(row) != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ len(row),
+ len(distinct),
+ )
+ return None
+ return [_to_python_scalar(row.iloc[index]) for index in range(len(distinct))]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be mapped onto itself, and the transform cannot carry
+ Jinja or call a non-deterministic function. Tier 2 (``blocking=False``) is
+ everything that merely leaves the mapping inactive.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ effective_mapped_column = partition_mapped_column or main_dttm_col
+ if effective_mapped_column and effective_mapped_column == partition_column:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not contains_value_placeholder(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform must contain the :value placeholder, "
+ "which stands for the filter value being mirrored."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if functions := find_non_deterministic_functions(transform, engine):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform calls %(functions)s, whose result "
+ "depends on when and where it runs. The transform is "
+ "evaluated in a separate session and the result is cached, "
+ "so the emitted predicate would freeze a snapshot of that "
+ "moment.",
+ functions=", ".join(sorted(functions)),
+ ),
+ blocking=True,
+ )
+ ]
+
+ return []
+
+
+@lru_cache(maxsize=LRU_CACHE_MAX_SIZE)
+def is_transform_active(transform: str | None, engine: str) -> bool:
+ """
+ Whether Superset will mirror filters through this transform.
+
+ `validate_transform` with the messages discarded, so the Explore indicator
+ cannot advertise a mapping the save path recorded as inactive. Anything
+ cheaper here would be a second, weaker statement of the same rule, free to
+ drift from the one the save path applies.
+
+ Blocking issues count too. Jinja and non-deterministic transforms are
+ rejected on PUT, but `CreateDatasetCommand` and import do not validate the
+ mapping, so one can still reach the database -- and it would never mirror a
+ filter either.
+
+ Memoized because `partition_filter_mapping_summary` is serialized on every
+ Explore and dashboard load and this parses the transform. The key is
+ everything the answer depends on: `validate_transform` reads no session, no
+ locale and no config beyond `SQL_MAX_PARSE_LENGTH`, which bounds the parser
+ rather than changing a verdict within that bound.
+ """
+ return not validate_transform(transform, engine)
+
+
+def preview_partition_mapping( # pylint: disable=too-many-return-statements
+ datasource: SqlaTable,
+ *,
+ mapped_column: str,
+ value_transform: str | None,
+ sample_values: list[str],
+ operator: FilterOperator = FilterOperator.EQUALS,
+ is_monotonic: bool = False,
+ partition_column: str | None = None,
+) -> dict[str, Any]:
+ """
+ Evaluate a candidate mapping and describe the predicate it would emit.
+
+ Shares the evaluator -- and therefore the probe cache -- with the query
+ path, so preview and runtime cannot drift and a previewed transform warms
+ the chart path for free. The predicate itself comes from
+ `build_mirrored_predicates`, the same builder the query path uses, so
+ operator shapes cannot drift either: what the panel shows is what a chart
+ would emit.
+
+ Validation runs first and the engine second: a half-typed transform is by
+ definition unparseable, so most of what a text input produces costs zero
+ queries.
+
+ Every part of the mapping is taken from the request rather than the stored
+ dataset. The editor previews while the owner is still editing -- a mapping
+ that has to be saved before it can be checked is not a preview.
+ """
+ partition_column = partition_column or datasource.partition_column
+ if not partition_column:
+ return {
+ "valid": False,
+ "reason": "unconfigured",
+ "error": _("No partition column is set."),
+ }
+
+ column_names = {str(column.column_name) for column in datasource.columns}
+ if mapped_column not in column_names:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _("%(name)s is not a column on this dataset.", name=mapped_column),
+ }
+
+ engine = datasource.database.backend
+ for issue in validate_partition_mapping(
+ column_names=column_names,
+ partition_column=str(partition_column),
+ partition_mapped_column=mapped_column,
+ main_dttm_col=datasource.main_dttm_col,
+ transform=value_transform,
+ engine=engine,
+ ):
+ return {
+ "valid": False,
+ # The parse failure is the one an owner sees constantly, and it is
+ # the only one the mockup gives its own headline to.
+ "reason": (
+ "parse"
+ if issue.field == "partition_value_transform"
+ and not is_parseable(value_transform, engine)
+ else "validation"
+ ),
+ "error": str(issue.message),
+ }
+
+ # The policy every other stored expression goes through. The save path
+ # applies it in `UpdateDatasetCommand._validate_partition_mapping`, but
+ # preview evaluates a candidate transform that has not been saved, so
+ # without this the gate had a door around it. See
+ # `stored_expression_error` for what is being kept out and why.
+ if reason := stored_expression_error(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ cast(str, value_transform),
+ ):
+ return {"valid": False, "reason": "validation", "error": reason}
+
+ mapping = PartitionMapping(
Review Comment:
Fixed. Preview now calls `has_active_advanced_data_type(columns_by_name[mapped_column])` and refuses before evaluating the transform, which is the same exclusion runtime resolution applies. Covered by `test_preview_refuses_a_mapped_column_with_an_advanced_data_type`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "hughhhh (via GitHub)" <gi...@apache.org>.
hughhhh commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4319672782
##########
superset/datasets/schemas.py:
##########
@@ -347,6 +373,18 @@ def fix_extra(self, data: dict[str, Any], **kwargs: Any) -> dict[str, Any]:
datetime_format = fields.String(
allow_none=True, validate=[Length(1, 100), validate_python_date_format]
)
+ partition_value_transform = fields.String(
+ allow_none=True, validate=Length(1, MAX_TRANSFORM_LENGTH)
+ )
+ # `load_default` so bundles predating the field do not claim their transform
+ # preserves ordering, which would silently enable range mirroring on import.
+ # `allow_none` because the column is nullable on purpose -- the legacy
+ # datasource editor writes NULL for any field its payload omits -- and export
+ # emits every field unconditionally, so an untouched export of such a dataset
+ # carries an explicit null that import would otherwise refuse outright.
+ partition_transform_is_monotonic = fields.Boolean(
+ allow_none=True, load_default=False
+ )
uuid = fields.UUID(allow_none=True)
Review Comment:
Fixed. `_default_omitted_monotonic_declarations` setdefaults the flag to `False` on every column carrying a transform before the import is applied, so an omitted declaration can no longer inherit a stored `True`.
##########
superset/models/helpers.py:
##########
@@ -4290,36 +4297,153 @@ def dttm_sql_literal(self, dttm: datetime, col: "TableColumn") -> str:
return f"""'{dttm.strftime("%Y-%m-%d %H:%M:%S.%f")}'"""
- def get_time_filter( # pylint: disable=too-many-arguments # noqa: C901
+ def _collect_partition_mirror_range(
self,
- time_col: "TableColumn",
+ mapping: Optional["PartitionMapping"],
+ sink: list[tuple[utils.FilterOperator, Any]],
+ column_name: str,
start_dttm: Optional[sa.DateTime],
end_dttm: Optional[sa.DateTime],
- time_grain: Optional[str] = None,
- label: Optional[str] = "__time",
- template_processor: Optional[BaseTemplateProcessor] = None,
- ) -> Optional[ColumnElement]:
- col = (
- time_col.get_timestamp_expression(
- time_grain=time_grain,
- label=label,
- template_processor=template_processor,
- )
- if time_grain
- else self.convert_tbl_column_to_sqla_col(
- time_col, label=label, template_processor=template_processor
- )
+ widen_bounds_by: Optional[relativedelta] = None,
+ ) -> None:
+ """
+ Record a time range for mirroring onto the partition column.
+
+ The bounds are adjusted first, by the same helper `get_time_filter` uses:
+ the mirrored predicate has to describe the same instants as the
+ timestamp predicate it stands in for, or the pruning is wrong by exactly
+ the dataset's timezone offset -- silently.
+
+ Either bound may be `None` for an open-ended range, in which case only
+ the bound that exists is mirrored.
+
+ `widen_bounds_by` is one grain bucket width, passed when the filter this
+ stands in for compares a *truncated* column. The real predicate then
+ keeps rows the raw bounds exclude, and widening both ends by one bucket
+ is the smallest range guaranteed to contain all of them -- see the "Time
+ grains" section of `superset.connectors.sqla.partition_mapping`. Note
+ the widened upper bound is `<=` rather than `<`: `ts < until + width`
+ only gives `T(ts) <= T(until + width)` for a transform that is monotonic
+ but not strictly so, such as `unix_timestamp` on a sub-second column.
+
+ A widened range can also be wide enough to fail `_bounds_are_ordered`
+ against a tighter filter on the same column. That fails open -- no
+ mirroring, no pruning, no dropped rows.
+ """
+ if mapping is None or column_name != mapping.mapped_column:
+ return
+ if not mapping.mirrors(utils.FilterOperator.TEMPORAL_RANGE):
+ return
+
+ # Resolve the column so the offset adjustment sees the same type
+ # `get_time_filter` does -- an offset the column's type cannot represent
+ # is dropped, and the mirrored bounds have to agree with the originals.
+ mapped_col = next(
+ (col for col in self.columns if col.column_name == column_name), None
)
+ start_dttm, end_dttm = self.adjust_time_bounds(start_dttm, end_dttm, mapped_col)
+
+ # Adjust first, then widen. `adjust_time_bounds` moves the naive UI
+ # bounds into the frame the column is *stored* in, and the grain
+ # truncation in the real predicate happens in that same frame, so the
+ # bucket width has to be added there too. The two commute for the
+ # hour-offset branch but not for the `ZoneInfo` one, where widening
+ # across a DST boundary first lands an hour out.
+ upper_operator = utils.FilterOperator.LESS_THAN
+ if widen_bounds_by is not None:
+ if start_dttm is not None:
+ start_dttm -= widen_bounds_by
+ if end_dttm is not None:
+ end_dttm += widen_bounds_by
+ upper_operator = utils.FilterOperator.LESS_THAN_OR_EQUALS
+
+ if start_dttm is not None:
+ sink.append((utils.FilterOperator.GREATER_THAN_OR_EQUALS, start_dttm))
Review Comment:
Fixed. The mirror is derived from what the engine reads back rather than from the Python datetime: `_engine_literal_resolution` measures how much of an instant the engine compares on that column, and `_round_bound_outward` widens the bound to it, so a truncating engine can no longer leave the mirror narrower than the predicate.
##########
superset/models/helpers.py:
##########
@@ -4292,36 +4389,621 @@ def dttm_sql_literal(self, dttm: datetime, col: "TableColumn") -> str:
return f"""'{dttm.strftime("%Y-%m-%d %H:%M:%S.%f")}'"""
- def get_time_filter( # pylint: disable=too-many-arguments # noqa: C901
+ def _mirror_probe_value(self, dttm: datetime, col: Optional["TableColumn"]) -> Any:
+ """
+ ``dttm`` in the mapped column's own stored representation.
+
+ The predicate this mirror stands in for compares the column against
+ `dttm_sql_literal(dttm, col)`, so the transform has to be probed with
+ the same value. On a column stored as an epoch integer, ``T`` is a
+ function of an integer: probing it with a `datetime` either returns
+ something unrelated to the partition keys or raises, and a raise costs
+ the dataset its pruning silently.
+
+ Only the ``python_date_format`` branches of `dttm_sql_literal` are
+ reproduced, because only those produce a *value*. `convert_dttm` yields
+ engine-specific SQL text, which cannot be bound as a parameter; its own
+ divergence from the probe is handled by widening the bounds instead.
+ """
+ if col is None:
+ return dttm
+
+ tf = col.python_date_format
Review Comment:
Fixed. `convert_dttm` is asked first and the `python_date_format` is applied only when it yields nothing, which is `dttm_sql_literal`'s own order — so a TIMESTAMP column carrying a `%Y%m%d` format is no longer mirrored through that format.
##########
superset/models/helpers.py:
##########
@@ -4292,36 +4389,644 @@ def dttm_sql_literal(self, dttm: datetime, col: "TableColumn") -> str:
return f"""'{dttm.strftime("%Y-%m-%d %H:%M:%S.%f")}'"""
- def get_time_filter( # pylint: disable=too-many-arguments # noqa: C901
+ def _mirror_probe_value(self, dttm: datetime, col: Optional["TableColumn"]) -> Any:
+ """
+ ``dttm`` in the mapped column's own stored representation.
+
+ The predicate this mirror stands in for compares the column against
+ `dttm_sql_literal(dttm, col)`, so the transform has to be probed with
+ the same value. On a column stored as an epoch integer, ``T`` is a
+ function of an integer: probing it with a `datetime` either returns
+ something unrelated to the partition keys or raises, and a raise costs
+ the dataset its pruning silently.
+
+ Only the ``python_date_format`` branches of `dttm_sql_literal` are
+ reproduced, because only those produce a *value*. `convert_dttm` yields
+ engine-specific SQL text, which cannot be bound as a parameter; its own
+ divergence from the probe is handled by widening the bounds instead
+ (`_engine_literal_resolution`).
+
+ In `dttm_sql_literal`'s own order, though: it asks ``convert_dttm``
+ first and reaches the format only when the engine answers nothing. A
+ column can carry both -- a TIMESTAMP with a ``%Y%m%d``
+ ``python_date_format``, or an entry in
+ ``python_date_format_by_column_name`` -- and applying the format
+ unconditionally probed a value the real predicate never compares.
+ ``event_time >= '2026-01-01 00:00:00'`` mirrored as
+ ``partition_col >= '20260101'``, and a January 15 row keyed
+ ``2026-01-15`` sorts below that string, so the chart lost a row the
+ filter keeps.
+
+ Where the engine does answer, the `datetime` is returned unchanged and
+ the widening path takes over -- which is exactly what already happens
+ for every temporal column that carries no format at all.
+ """
+ if col is None:
+ return dttm
+
+ if col.type and self.db_engine_spec.convert_dttm(
+ col.type, dttm, db_extra=self.db_extra
+ ):
+ # The format is unreachable in `dttm_sql_literal` for this column,
+ # so reproducing it here would describe a different bound.
+ return dttm
+
+ tf = col.python_date_format
+ if not tf and self.db_extra:
+ tf = self.db_extra.get("python_date_format_by_column_name", {}).get(
+ col.column_name
+ )
+ if not tf:
+ return dttm
+
+ if tf in EPOCH_FORMATS:
+ dttm_tz_aware = dttm
+ if dttm_tz_aware.tzinfo is None:
+ dttm_tz_aware = dttm_tz_aware.replace(tzinfo=timezone.utc)
+ return int(dttm_tz_aware.timestamp()) * EPOCH_FORMATS[tf]
+ return dttm.strftime(tf)
+
+ def _engine_literal_resolution(
+ self, dttm: datetime, col: Optional["TableColumn"]
+ ) -> LiteralResolution:
+ """
+ How much of ``dttm`` survives into this engine's literal for ``col``.
+
+ The real predicate compares `dttm_sql_literal(dttm, col)`, so whatever
+ that literal throws away is a bound the engine never sees. A mirror
+ derived from the full precision then describes a *narrower* range than
+ the predicate it stands in for -- and narrower means it drops rows the
+ filter keeps.
+
+ Two things get thrown away in practice:
+
+ - the sub-second part. SQLite renders a timestamp with
+ ``timespec="seconds"``.
+ - the time of day entirely. Every engine spec with a ``types.Date``
+ branch renders ``dttm.date().isoformat()``, so Presto, Trino,
+ BigQuery and some two dozen others answer `DATE '2026-01-01'` for a
+ bound of 10:00 -- and `T(DATE '2026-01-01')` is below the mirror's
+ own lower bound, so the whole first day is dropped.
+
+ Detected rather than enumerated per engine, because the branch depends
+ on the column's type as well as the spec: instants differing only in the
+ part under test render as the same text exactly when the engine has
+ thrown that part away.
+
+ The day test uses two fixed times of day rather than ``dttm`` and one
+ alternative, so a bound that happens to sit on the hour the alternative
+ uses cannot read as "no time at all". Neither probe sits at midnight on
+ purpose: SQLite renders a DATE column at exactly midnight as a bare
+ date, so a midnight probe would differ from its alternative for a
+ reason that has nothing to do with resolution.
+
+ Likewise both sub-second probes carry a non-zero remainder. Comparing
+ against ``dttm`` truncated to the second looks like the obvious test and
+ is wrong for the same formatting-boundary reason.
+ """
+ if col is None or not col.type:
+ return LiteralResolution.FULL
+
+ def render(moment: datetime) -> Optional[str]:
+ return self.db_engine_spec.convert_dttm(
+ col.type, moment, db_extra=self.db_extra
+ )
+
+ try:
+ early = render(dttm.replace(hour=1, minute=2, second=3, microsecond=444444))
+ late = render(
+ dttm.replace(hour=22, minute=33, second=44, microsecond=555555)
+ )
+ if early is not None and early == late:
+ return LiteralResolution.DAY
+
+ # Flooring to the second is a no-op on a bound that has no
+ # sub-second part, so there is nothing to detect.
+ if not dttm.microsecond:
+ return LiteralResolution.FULL
+
+ first = render(dttm.replace(microsecond=111111))
+ second = render(dttm.replace(microsecond=222222))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return LiteralResolution.FULL
+
+ if first is not None and first == second:
+ return LiteralResolution.SECOND
+ return LiteralResolution.FULL
+
+ def _round_bounds_outward(
self,
- time_col: "TableColumn",
+ start_dttm: Optional[datetime],
+ end_dttm: Optional[datetime],
+ col: Optional["TableColumn"],
+ ) -> tuple[Optional[datetime], Optional[datetime]]:
+ """
+ The bounds widened to whatever the engine's literal actually resolves to.
+
+ Rounding outward is never narrower than the predicate being mirrored,
+ which is the only property the mirror has to hold.
+ """
+ resolutions = {
+ self._engine_literal_resolution(bound, col)
+ for bound in (start_dttm, end_dttm)
+ if bound is not None
+ }
+
+ if LiteralResolution.DAY in resolutions:
+ # The engine compares a bare date, so the real predicate's lower
+ # bound is the start of that day and its upper bound admits the
+ # whole of the day before. Anything finer excludes rows it keeps.
+ if start_dttm is not None:
+ start_dttm = start_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ )
+ if end_dttm is not None and end_dttm != end_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ ):
+ end_dttm = end_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ ) + timedelta(days=1)
+ elif LiteralResolution.SECOND in resolutions:
+ if start_dttm is not None:
+ start_dttm = start_dttm.replace(microsecond=0)
+ if end_dttm is not None and end_dttm.microsecond:
+ end_dttm = end_dttm.replace(microsecond=0) + timedelta(seconds=1)
+
+ return start_dttm, end_dttm
+
+ def _literal_is_coarser_than(
+ self, dttm: datetime, col: Optional["TableColumn"]
+ ) -> bool:
+ """
+ Whether the engine's literal for ``dttm`` throws away part of it.
+
+ Unlike a range, an equality cannot be widened outward, so the only safe
+ answer when the engine compares less than the full value is to decline
+ the mirror.
+ """
+ resolution = self._engine_literal_resolution(dttm, col)
+ if resolution is LiteralResolution.DAY:
+ return dttm != dttm.replace(hour=0, minute=0, second=0, microsecond=0)
+ if resolution is LiteralResolution.SECOND:
+ return bool(dttm.microsecond)
+ return False
+
+ def _column_literal_resolution(
+ self, col: Optional["TableColumn"]
+ ) -> LiteralResolution:
+ """
+ How much of *any* value this engine compares on ``col``.
+
+ `_engine_literal_resolution` answers about a particular instant, which
+ is what a mirror derived from one needs. Two callers have no instant to
+ ask about -- the summary the Explore glyph reads, and a filter value
+ `_instant_from_filter_value` cannot read as an instant at all -- and
+ both need the column's own answer. Through one helper so that the glyph
+ and the query path cannot disagree about which column is coarse, which
+ is the same reason `mirrorable_operators` is computed once.
+
+ A non-temporal column has no answer, and asking anyway gets a wrong one:
+ SQLite's ``convert_dttm`` renders for ``types.String`` as well as for the
+ date types, so a reference instant makes a ``VARCHAR`` mapped column look
+ second-resolution -- and ``country = 'US'``, the text half of this
+ feature, reads as a value the engine compares coarsely. The per-instant
+ callers never meet this, because they arrive only with a value that
+ parsed as an instant.
+ """
+ if col is None or not col.is_dttm:
+ return LiteralResolution.FULL
+ return self._engine_literal_resolution(_RESOLUTION_REFERENCE_INSTANT, col)
+
+ def _round_bound_outward(
+ self,
+ instant: datetime,
+ col: Optional["TableColumn"],
+ *,
+ is_upper: bool,
+ ) -> datetime:
+ """
+ One bound widened to whatever the engine resolves ``col`` to.
+
+ `_round_bounds_outward` answers for a since/until pair, because a time
+ range is the shape it was written for. A single comparison is one end of
+ such a pair with the other end absent, and the widening is per-end
+ already -- a lower bound moves back, an upper bound forward.
+
+ Narrowing the return type is the other half of the point: a bound handed
+ in non-`None` comes back non-`None`, and saying so here saves every
+ caller from re-establishing it.
+ """
+ start_dttm, end_dttm = self._round_bounds_outward(
+ None if is_upper else instant,
+ instant if is_upper else None,
+ col,
+ )
+ rounded = end_dttm if is_upper else start_dttm
+ return rounded if rounded is not None else instant
+
+ def _mirror_probe_input(
+ self,
+ operator: utils.FilterOperator,
+ value: Any,
+ col: Optional["TableColumn"],
+ ) -> Any:
+ """
+ ``value`` in the representation the mirror may probe the transform at.
+
+ A simple filter on a temporal column carries a *string*.
+ `filter_values_handler` rewrites only an all-digit value, which it reads
+ as epoch milliseconds, so ``'2026-07-06 10:08:11'`` reaches here exactly
+ as the chart author typed it and is bound as text. The engine compares
+ that text against the column under its own cast, and on a ``DATE``
+ column the cast drops the time of day: the filter keeps the whole of
+ 2026-07-06 while a mirror probed at 10:08:11 keeps one instant of it,
+ which is narrower than the predicate it stands in for.
+
+ So the text is read back into the instant it denotes -- the only way
+ `_engine_literal_resolution`, which answers about a `datetime`, reaches
+ a filter value at all -- and where the engine compares less of that
+ instant than the filter carries, what to do about it is a property of
+ the *operator*:
+
+ * a bound rounds outward, through the helper the range collector uses.
+ Reading one extra bucket at the edge is the trade this feature makes
+ everywhere else too -- see `mirror_operator` -- and the original
+ predicate is still in the query to exclude the rows that bucket adds.
+ * an equality, or one member of an ``IN`` list, has nowhere to widen to.
+ These entries are ``AND``-ed onto the query, so "or the day either
+ side" is not something this sink can express, and the request is
+ declined with `_UNMIRRORABLE`. The query is then correct and unpruned,
+ which is the one failure mode this feature is allowed.
+
+ An instant carrying a UTC offset is declined for every operator, a
+ bound included. Rounding one outward would first have to place it in the
+ frame the partition column was written in, and guessing that frame is
+ how a mirror ends up a whole offset narrower than the filter -- see the
+ load-bearing assumption in
+ `superset.connectors.sqla.partition_mapping`.
+
+ A *string* `_instant_from_filter_value` cannot read at all is declined on
+ the same terms, and for the same reason one more step back: there is no
+ instant to round. ``'07/06/2026 10:08:11'`` is not ISO 8601, so the
+ parser leaves it alone -- and Postgres casts that same text to a DATE and
+ keeps the whole of July 6 while the probe, handed the string verbatim,
+ evaluates the transform at 10:08:11 and asks for a partition key no row
+ holds. That is exactly the narrowing the ISO-only parser was written to
+ prevent, reached through a value it declines to read, so the decline has
+ to travel with it. Which costs a non-ISO *date* its pruning too, because
+ telling July 6 from June 7 is the guess that started this.
+
+ Only a string. `_as_probe_input` has already run, so the engine SQL
+ `filter_values_handler` returns for an epoch-millisecond bound arrives
+ here as a `RawProbeValue` rather than text -- and that literal was
+ rendered by the engine at the engine's own resolution, so it is the one
+ thing on this path with nothing left to resolve.
+
+ Where the engine compares the whole instant, a string is returned
+ exactly as it arrived -- down to the type the probe binds and the cache
+ key it lands on, because every query that was already correct has to
+ stay byte-for-byte correct. A `datetime` is still converted, which it
+ has always needed: on a column stored as an epoch integer the transform
+ is a function of an integer, and a `datetime` is not the value the real
+ predicate compares.
+ """
+ parsed = _instant_from_filter_value(value)
+ if parsed is None:
+ if (
+ isinstance(value, str)
+ and self._column_literal_resolution(col) is not LiteralResolution.FULL
+ ):
+ return _UNMIRRORABLE
+ return value
+
+ if (
+ self._engine_literal_resolution(parsed.replace(tzinfo=None), col)
Review Comment:
Fixed. The `is_dttm` guard moved into `_engine_literal_resolution`, where it covers the per-instant callers too — the belief that they only ever arrive with a value that parsed as an instant was untrue of a text column holding ISO-shaped text, where the value parses and the column is still not temporal.
##########
superset/models/helpers.py:
##########
@@ -4292,36 +4389,661 @@ def dttm_sql_literal(self, dttm: datetime, col: "TableColumn") -> str:
return f"""'{dttm.strftime("%Y-%m-%d %H:%M:%S.%f")}'"""
- def get_time_filter( # pylint: disable=too-many-arguments # noqa: C901
+ def _mirror_probe_value(self, dttm: datetime, col: Optional["TableColumn"]) -> Any:
+ """
+ ``dttm`` in the mapped column's own stored representation.
+
+ The predicate this mirror stands in for compares the column against
+ `dttm_sql_literal(dttm, col)`, so the transform has to be probed with
+ the same value. On a column stored as an epoch integer, ``T`` is a
+ function of an integer: probing it with a `datetime` either returns
+ something unrelated to the partition keys or raises, and a raise costs
+ the dataset its pruning silently.
+
+ Only the ``python_date_format`` branches of `dttm_sql_literal` are
+ reproduced, because only those produce a *value*. `convert_dttm` yields
+ engine-specific SQL text, which cannot be bound as a parameter; its own
+ divergence from the probe is handled by widening the bounds instead
+ (`_engine_literal_resolution`).
+
+ In `dttm_sql_literal`'s own order, though: it asks ``convert_dttm``
+ first and reaches the format only when the engine answers nothing. A
+ column can carry both -- a TIMESTAMP with a ``%Y%m%d``
+ ``python_date_format``, or an entry in
+ ``python_date_format_by_column_name`` -- and applying the format
+ unconditionally probed a value the real predicate never compares.
+ ``event_time >= '2026-01-01 00:00:00'`` mirrored as
+ ``partition_col >= '20260101'``, and a January 15 row keyed
+ ``2026-01-15`` sorts below that string, so the chart lost a row the
+ filter keeps.
+
+ Where the engine does answer, the `datetime` is returned unchanged and
+ the widening path takes over -- which is exactly what already happens
+ for every temporal column that carries no format at all.
+ """
+ if col is None:
+ return dttm
+
+ if col.type and self.db_engine_spec.convert_dttm(
+ col.type, dttm, db_extra=self.db_extra
+ ):
+ # The format is unreachable in `dttm_sql_literal` for this column,
+ # so reproducing it here would describe a different bound.
+ return dttm
+
+ tf = col.python_date_format
+ if not tf and self.db_extra:
+ tf = self.db_extra.get("python_date_format_by_column_name", {}).get(
+ col.column_name
+ )
+ if not tf:
+ return dttm
+
+ if tf in EPOCH_FORMATS:
+ dttm_tz_aware = dttm
+ if dttm_tz_aware.tzinfo is None:
+ dttm_tz_aware = dttm_tz_aware.replace(tzinfo=timezone.utc)
+ return int(dttm_tz_aware.timestamp()) * EPOCH_FORMATS[tf]
+ return dttm.strftime(tf)
+
+ def _engine_literal_resolution(
+ self, dttm: datetime, col: Optional["TableColumn"]
+ ) -> LiteralResolution:
+ """
+ How much of ``dttm`` survives into this engine's literal for ``col``.
+
+ The real predicate compares `dttm_sql_literal(dttm, col)`, so whatever
+ that literal throws away is a bound the engine never sees. A mirror
+ derived from the full precision then describes a *narrower* range than
+ the predicate it stands in for -- and narrower means it drops rows the
+ filter keeps.
+
+ Two things get thrown away in practice:
+
+ - the sub-second part. SQLite renders a timestamp with
+ ``timespec="seconds"``.
+ - the time of day entirely. Every engine spec with a ``types.Date``
+ branch renders ``dttm.date().isoformat()``, so Presto, Trino,
+ BigQuery and some two dozen others answer `DATE '2026-01-01'` for a
+ bound of 10:00 -- and `T(DATE '2026-01-01')` is below the mirror's
+ own lower bound, so the whole first day is dropped.
+
+ Detected rather than enumerated per engine, because the branch depends
+ on the column's type as well as the spec: instants differing only in the
+ part under test render as the same text exactly when the engine has
+ thrown that part away.
+
+ The day test uses two fixed times of day rather than ``dttm`` and one
+ alternative, so a bound that happens to sit on the hour the alternative
+ uses cannot read as "no time at all". Neither probe sits at midnight on
+ purpose: SQLite renders a DATE column at exactly midnight as a bare
+ date, so a midnight probe would differ from its alternative for a
+ reason that has nothing to do with resolution.
+
+ Likewise both sub-second probes carry a non-zero remainder. Comparing
+ against ``dttm`` truncated to the second looks like the obvious test and
+ is wrong for the same formatting-boundary reason.
+
+ A non-temporal column has no answer here, and asking anyway gets a wrong
+ one. SQLite's ``convert_dttm`` renders for ``types.String`` as well as
+ for the date types, so a ``VARCHAR`` mapped column reads as
+ second-resolution -- and a filter value that happens to *look* like an
+ instant then has its bound rounded as though the engine had truncated
+ it. On a VARCHAR ``code`` mapped onto a VARCHAR ``p`` by ``:value``,
+ ``code < '2026-07-06T10:08:11.500000'`` was mirrored as
+ ``p <= '2026-07-06 10:08:12.000000'``; a space sorts before ``T``, so a
+ row holding ``2026-07-06T09:00:00`` fell outside the mirror while
+ matching the filter.
+
+ The guard lives here rather than in each caller so this and
+ `_column_literal_resolution` cannot disagree about which column is
+ coarse -- which is the same reason that helper delegates to this one.
+ """
+ if col is None or not col.type or not col.is_dttm:
+ return LiteralResolution.FULL
+
+ def render(moment: datetime) -> Optional[str]:
+ return self.db_engine_spec.convert_dttm(
+ col.type, moment, db_extra=self.db_extra
+ )
+
+ try:
+ early = render(dttm.replace(hour=1, minute=2, second=3, microsecond=444444))
+ late = render(
+ dttm.replace(hour=22, minute=33, second=44, microsecond=555555)
+ )
+ if early is not None and early == late:
+ return LiteralResolution.DAY
+
+ # Flooring to the second is a no-op on a bound that has no
+ # sub-second part, so there is nothing to detect.
+ if not dttm.microsecond:
+ return LiteralResolution.FULL
+
+ first = render(dttm.replace(microsecond=111111))
+ second = render(dttm.replace(microsecond=222222))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return LiteralResolution.FULL
+
+ if first is not None and first == second:
+ return LiteralResolution.SECOND
+ return LiteralResolution.FULL
+
+ def _round_bounds_outward(
self,
- time_col: "TableColumn",
+ start_dttm: Optional[datetime],
+ end_dttm: Optional[datetime],
+ col: Optional["TableColumn"],
+ ) -> tuple[Optional[datetime], Optional[datetime]]:
+ """
+ The bounds widened to whatever the engine's literal actually resolves to.
+
+ Rounding outward is never narrower than the predicate being mirrored,
+ which is the only property the mirror has to hold.
+ """
+ resolutions = {
+ self._engine_literal_resolution(bound, col)
+ for bound in (start_dttm, end_dttm)
+ if bound is not None
+ }
+
+ if LiteralResolution.DAY in resolutions:
+ # The engine compares a bare date, so the real predicate's lower
+ # bound is the start of that day and its upper bound admits the
+ # whole of the day before. Anything finer excludes rows it keeps.
+ if start_dttm is not None:
+ start_dttm = start_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ )
+ if end_dttm is not None and end_dttm != end_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ ):
+ end_dttm = end_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ ) + timedelta(days=1)
+ elif LiteralResolution.SECOND in resolutions:
+ if start_dttm is not None:
+ start_dttm = start_dttm.replace(microsecond=0)
+ if end_dttm is not None and end_dttm.microsecond:
+ end_dttm = end_dttm.replace(microsecond=0) + timedelta(seconds=1)
+
+ return start_dttm, end_dttm
+
+ def _literal_is_coarser_than(
+ self, dttm: datetime, col: Optional["TableColumn"]
+ ) -> bool:
+ """
+ Whether the engine's literal for ``dttm`` throws away part of it.
+
+ Unlike a range, an equality cannot be widened outward, so the only safe
+ answer when the engine compares less than the full value is to decline
+ the mirror.
+ """
+ resolution = self._engine_literal_resolution(dttm, col)
+ if resolution is LiteralResolution.DAY:
+ return dttm != dttm.replace(hour=0, minute=0, second=0, microsecond=0)
+ if resolution is LiteralResolution.SECOND:
+ return bool(dttm.microsecond)
+ return False
+
+ def _column_literal_resolution(
+ self, col: Optional["TableColumn"]
+ ) -> LiteralResolution:
+ """
+ How much of *any* value this engine compares on ``col``.
+
+ `_engine_literal_resolution` answers about a particular instant, which
+ is what a mirror derived from one needs. Two callers have no instant to
+ ask about -- the summary the Explore glyph reads, and a filter value
+ `_instant_from_filter_value` cannot read as an instant at all -- and
+ both need the column's own answer. Through one helper so that the glyph
+ and the query path cannot disagree about which column is coarse, which
+ is the same reason `mirrorable_operators` is computed once.
+
+ A non-temporal column has no answer, and asking anyway gets a wrong one:
+ SQLite's ``convert_dttm`` renders for ``types.String`` as well as for the
+ date types, so a reference instant makes a ``VARCHAR`` mapped column look
+ second-resolution -- and ``country = 'US'``, the text half of this
+ feature, reads as a value the engine compares coarsely.
+
+ That guard is `_engine_literal_resolution`'s, not this function's. It
+ used to be here, on the belief that the per-instant callers never met
+ the case because they arrive only with a value that parsed as an
+ instant -- which is untrue of a text column holding ISO-shaped text,
+ where the value parses and the column is still not temporal.
+ """
+ return self._engine_literal_resolution(_RESOLUTION_REFERENCE_INSTANT, col)
+
+ def _round_bound_outward(
+ self,
+ instant: datetime,
+ col: Optional["TableColumn"],
+ *,
+ is_upper: bool,
+ ) -> datetime:
+ """
+ One bound widened to whatever the engine resolves ``col`` to.
+
+ `_round_bounds_outward` answers for a since/until pair, because a time
+ range is the shape it was written for. A single comparison is one end of
+ such a pair with the other end absent, and the widening is per-end
+ already -- a lower bound moves back, an upper bound forward.
+
+ Narrowing the return type is the other half of the point: a bound handed
+ in non-`None` comes back non-`None`, and saying so here saves every
+ caller from re-establishing it.
+ """
+ start_dttm, end_dttm = self._round_bounds_outward(
+ None if is_upper else instant,
+ instant if is_upper else None,
+ col,
+ )
+ rounded = end_dttm if is_upper else start_dttm
+ return rounded if rounded is not None else instant
+
+ def _mirror_probe_input(
+ self,
+ operator: utils.FilterOperator,
+ value: Any,
+ col: Optional["TableColumn"],
+ ) -> Any:
+ """
+ ``value`` in the representation the mirror may probe the transform at.
+
+ A simple filter on a temporal column carries a *string*.
+ `filter_values_handler` rewrites only an all-digit value, which it reads
+ as epoch milliseconds, so ``'2026-07-06 10:08:11'`` reaches here exactly
+ as the chart author typed it and is bound as text. The engine compares
+ that text against the column under its own cast, and on a ``DATE``
+ column the cast drops the time of day: the filter keeps the whole of
+ 2026-07-06 while a mirror probed at 10:08:11 keeps one instant of it,
+ which is narrower than the predicate it stands in for.
+
+ So the text is read back into the instant it denotes -- the only way
+ `_engine_literal_resolution`, which answers about a `datetime`, reaches
+ a filter value at all -- and where the engine compares less of that
+ instant than the filter carries, what to do about it is a property of
+ the *operator*:
+
+ * a bound rounds outward, through the helper the range collector uses.
+ Reading one extra bucket at the edge is the trade this feature makes
+ everywhere else too -- see `mirror_operator` -- and the original
+ predicate is still in the query to exclude the rows that bucket adds.
+ * an equality, or one member of an ``IN`` list, has nowhere to widen to.
+ These entries are ``AND``-ed onto the query, so "or the day either
+ side" is not something this sink can express, and the request is
+ declined with `_UNMIRRORABLE`. The query is then correct and unpruned,
+ which is the one failure mode this feature is allowed.
+
+ An instant carrying a UTC offset is declined for every operator, a
+ bound included. Rounding one outward would first have to place it in the
+ frame the partition column was written in, and guessing that frame is
+ how a mirror ends up a whole offset narrower than the filter -- see the
+ load-bearing assumption in
+ `superset.connectors.sqla.partition_mapping`.
+
+ A *string* `_instant_from_filter_value` cannot read at all is declined on
+ the same terms, and for the same reason one more step back: there is no
+ instant to round. ``'07/06/2026 10:08:11'`` is not ISO 8601, so the
+ parser leaves it alone -- and Postgres casts that same text to a DATE and
+ keeps the whole of July 6 while the probe, handed the string verbatim,
+ evaluates the transform at 10:08:11 and asks for a partition key no row
+ holds. That is exactly the narrowing the ISO-only parser was written to
+ prevent, reached through a value it declines to read, so the decline has
+ to travel with it. Which costs a non-ISO *date* its pruning too, because
+ telling July 6 from June 7 is the guess that started this.
+
+ Only a string. `_as_probe_input` has already run, so the engine SQL
+ `filter_values_handler` returns for an epoch-millisecond bound arrives
+ here as a `RawProbeValue` rather than text -- and that literal was
+ rendered by the engine at the engine's own resolution, so it is the one
+ thing on this path with nothing left to resolve.
+
+ Where the engine compares the whole instant, a string is returned
+ exactly as it arrived -- down to the type the probe binds and the cache
+ key it lands on, because every query that was already correct has to
+ stay byte-for-byte correct. A `datetime` is still converted, which it
+ has always needed: on a column stored as an epoch integer the transform
+ is a function of an integer, and a `datetime` is not the value the real
+ predicate compares.
+ """
+ parsed = _instant_from_filter_value(value)
+ if parsed is None:
+ if (
+ isinstance(value, str)
+ and self._column_literal_resolution(col) is not LiteralResolution.FULL
+ ):
+ return _UNMIRRORABLE
+ return value
+
+ if (
+ self._engine_literal_resolution(parsed.replace(tzinfo=None), col)
Review Comment:
Fixed. An offset is kept rather than dropped so the caller can see it and decline, and an offset-bearing filter value on a full-resolution column is declined rather than passed to the probe for a cast that would drop it.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4174107534
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,1314 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` always -- ``T`` is a function
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import re
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLStatement
+from superset.utils import json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: Every entry point enforces it -- the typed column field, the import schema
+#: and the preview request -- because `is_transform_active` parses the stored
+#: value on each Explore load, and an unbounded string would make that parse
+#: the expensive part of rendering a chart.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
Review Comment:
Equality is not always preserved by a deterministic transform: with `country COLLATE NOCASE`, a binary partition key equal to `hex(country)`, and a stored `country='us'`, filtering for `'US'` matches the row but mirroring to `hex('US')` excludes it, even though the documented pipeline invariant holds. Could equality/IN mirroring require compatibility with the mapped column's comparison semantics rather than treating determinism alone as sufficient?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,1314 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` always -- ``T`` is a function
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import re
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLStatement
+from superset.utils import json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: Every entry point enforces it -- the typed column field, the import schema
+#: and the preview request -- because `is_transform_active` parses the stored
+#: value on each Explore load, and an unbounded string would make that parse
+#: the expensive part of rendering a chart.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+def mirrorable_operators(is_monotonic: bool) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ """
+ if is_monotonic:
+ return MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+ return set(MIRRORABLE_ALWAYS)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(self.is_monotonic)
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+ """
+ return VALUE_PLACEHOLDER_RE.sub(_PARSE_STANDIN, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(transform: str, engine: str) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def stored_expression_error(
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ The same subquery, function-denylist and RLS policy every other stored
+ expression goes through, applied to a value transform. It matters more
+ here than the name suggests: `build_probe_sql` binds only `:value` and
+ splices the rest of the transform in as SQL text, which the engine then
+ executes, so an ungated transform is arbitrary SQL. A dataset editor
+ without SQL Lab could store `(SELECT secret FROM protected_table LIMIT 1)
+ || :value` and read the answer back out of the emitted predicate.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+ """
+ selections = []
+ for index, value in enumerate(values):
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ compiled = clause.compile(
+ dialect=dialect,
+ compile_kwargs={"literal_binds": True},
+ )
+ selections.append(f"{compiled} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ database.db_engine_spec.select_without_from_suffix,
+ )
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ row = frame.iloc[0]
+ if len(row) != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ len(row),
+ len(distinct),
+ )
+ return None
+ return [_to_python_scalar(row.iloc[index]) for index in range(len(distinct))]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be mapped onto itself, and the transform cannot carry
+ Jinja or call a non-deterministic function. Tier 2 (``blocking=False``) is
+ everything that merely leaves the mapping inactive.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ effective_mapped_column = partition_mapped_column or main_dttm_col
+ if effective_mapped_column and effective_mapped_column == partition_column:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not contains_value_placeholder(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform must contain the :value placeholder, "
+ "which stands for the filter value being mirrored."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if functions := find_non_deterministic_functions(transform, engine):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform calls %(functions)s, whose result "
+ "depends on when and where it runs. The transform is "
+ "evaluated in a separate session and the result is cached, "
+ "so the emitted predicate would freeze a snapshot of that "
+ "moment.",
+ functions=", ".join(sorted(functions)),
+ ),
+ blocking=True,
+ )
+ ]
+
+ return []
+
+
+@lru_cache(maxsize=LRU_CACHE_MAX_SIZE)
+def is_transform_active(transform: str | None, engine: str) -> bool:
+ """
+ Whether Superset will mirror filters through this transform.
+
+ `validate_transform` with the messages discarded, so the Explore indicator
+ cannot advertise a mapping the save path recorded as inactive. Anything
+ cheaper here would be a second, weaker statement of the same rule, free to
+ drift from the one the save path applies.
+
+ Blocking issues count too. Jinja and non-deterministic transforms are
+ rejected on PUT, but `CreateDatasetCommand` and import do not validate the
+ mapping, so one can still reach the database -- and it would never mirror a
+ filter either.
+
+ Memoized because `partition_filter_mapping_summary` is serialized on every
+ Explore and dashboard load and this parses the transform. The key is
+ everything the answer depends on: `validate_transform` reads no session, no
+ locale and no config beyond `SQL_MAX_PARSE_LENGTH`, which bounds the parser
+ rather than changing a verdict within that bound.
+ """
+ return not validate_transform(transform, engine)
+
+
+def preview_partition_mapping( # pylint: disable=too-many-return-statements
+ datasource: SqlaTable,
+ *,
+ mapped_column: str,
+ value_transform: str | None,
+ sample_values: list[str],
+ operator: FilterOperator = FilterOperator.EQUALS,
+ is_monotonic: bool = False,
+ partition_column: str | None = None,
+) -> dict[str, Any]:
+ """
+ Evaluate a candidate mapping and describe the predicate it would emit.
+
+ Shares the evaluator -- and therefore the probe cache -- with the query
+ path, so preview and runtime cannot drift and a previewed transform warms
+ the chart path for free. The predicate itself comes from
+ `build_mirrored_predicates`, the same builder the query path uses, so
+ operator shapes cannot drift either: what the panel shows is what a chart
+ would emit.
+
+ Validation runs first and the engine second: a half-typed transform is by
+ definition unparseable, so most of what a text input produces costs zero
+ queries.
+
+ Every part of the mapping is taken from the request rather than the stored
+ dataset. The editor previews while the owner is still editing -- a mapping
+ that has to be saved before it can be checked is not a preview.
+ """
+ partition_column = partition_column or datasource.partition_column
+ if not partition_column:
+ return {
+ "valid": False,
+ "reason": "unconfigured",
+ "error": _("No partition column is set."),
+ }
+
+ column_names = {str(column.column_name) for column in datasource.columns}
+ if mapped_column not in column_names:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _("%(name)s is not a column on this dataset.", name=mapped_column),
+ }
+
+ engine = datasource.database.backend
+ for issue in validate_partition_mapping(
+ column_names=column_names,
+ partition_column=str(partition_column),
+ partition_mapped_column=mapped_column,
+ main_dttm_col=datasource.main_dttm_col,
+ transform=value_transform,
+ engine=engine,
+ ):
+ return {
+ "valid": False,
+ # The parse failure is the one an owner sees constantly, and it is
+ # the only one the mockup gives its own headline to.
+ "reason": (
+ "parse"
+ if issue.field == "partition_value_transform"
+ and not is_parseable(value_transform, engine)
+ else "validation"
+ ),
+ "error": str(issue.message),
+ }
+
+ # The policy every other stored expression goes through. The save path
+ # applies it in `UpdateDatasetCommand._validate_partition_mapping`, but
+ # preview evaluates a candidate transform that has not been saved, so
+ # without this the gate had a door around it. See
+ # `stored_expression_error` for what is being kept out and why.
+ if reason := stored_expression_error(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ cast(str, value_transform),
+ ):
+ return {"valid": False, "reason": "validation", "error": reason}
+
+ mapping = PartitionMapping(
Review Comment:
Preview can return a valid emitted predicate for a mapped column with an active advanced data type, although runtime resolution explicitly skips that column and chart queries never emit the mirror. Could preview apply the same advanced-type exclusion before evaluating the transform?
##########
superset/datasets/schemas.py:
##########
@@ -347,6 +373,12 @@ def fix_extra(self, data: dict[str, Any], **kwargs: Any) -> dict[str, Any]:
datetime_format = fields.String(
allow_none=True, validate=[Length(1, 100), validate_python_date_format]
)
+ partition_value_transform = fields.String(
+ allow_none=True, validate=Length(1, MAX_TRANSFORM_LENGTH)
+ )
+ # Bundles predating the field must not claim their transform preserves
+ # ordering, which would silently enable range mirroring on import.
+ partition_transform_is_monotonic = fields.Boolean(load_default=False)
Review Comment:
PUT accepts a null monotonicity flag and export includes that null, but this import field rejects it, so an unchanged exported dataset cannot be imported again. Could import accept the nullable value supported by the model and PUT schema?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,1314 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` always -- ``T`` is a function
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import re
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLStatement
+from superset.utils import json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: Every entry point enforces it -- the typed column field, the import schema
+#: and the preview request -- because `is_transform_active` parses the stored
+#: value on each Explore load, and an unbounded string would make that parse
+#: the expensive part of rendering a chart.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+def mirrorable_operators(is_monotonic: bool) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ """
+ if is_monotonic:
+ return MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+ return set(MIRRORABLE_ALWAYS)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(self.is_monotonic)
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+ """
+ return VALUE_PLACEHOLDER_RE.sub(_PARSE_STANDIN, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(transform: str, engine: str) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def stored_expression_error(
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ The same subquery, function-denylist and RLS policy every other stored
+ expression goes through, applied to a value transform. It matters more
+ here than the name suggests: `build_probe_sql` binds only `:value` and
+ splices the rest of the transform in as SQL text, which the engine then
+ executes, so an ungated transform is arbitrary SQL. A dataset editor
+ without SQL Lab could store `(SELECT secret FROM protected_table LIMIT 1)
+ || :value` and read the answer back out of the emitted predicate.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+ """
+ selections = []
+ for index, value in enumerate(values):
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ compiled = clause.compile(
+ dialect=dialect,
+ compile_kwargs={"literal_binds": True},
Review Comment:
On MySQL, this compilation doubles the percent signs in `date_format(:value, '%Y%m%d')`, but the probe executes without bound parameters, so the format becomes literal `%Y%m%d` rather than `20260115` and the added partition predicate drops matching rows. Could this apply the percent normalization already used by `Database.compile_sqla_query`?
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/DatasourceEditor.tsx:
##########
@@ -1250,6 +1356,124 @@ function DatasourceEditor({
[],
);
+ // Which column's row expand to open, for the "map a different column" links.
+ // Consumed by the Columns tab, which scrolls the row into view and expands it.
+ //
+ // Carries a nonce because the request is an event, not a state: clicking the
+ // same link twice -- after collapsing the row by hand in between -- asks for
+ // the same column name, and a bare string would make the second
+ // `setColumnToReveal` a no-op. React would bail out of the render, nothing
+ // downstream would see a change, and the row would stay shut.
+ const [columnToReveal, setColumnToReveal] = useState<{
+ name: string;
+ nonce: number;
+ } | null>(null);
+
+ const handlePartitionColumnChange = useCallback(
+ (columnName: string | null) => {
+ setDatasource(prev => ({
+ ...prev,
+ partition_column: columnName,
+ partition_mapped_column: nextMappedColumnOverride(
+ prev.partition_mapped_column,
+ columnName,
+ ),
+ }));
+ if (columnName) {
+ setDatabaseColumns(prev =>
+ applyPartitionColumnDefaults(prev, columnName),
+ );
+ }
+ },
+ [],
+ );
+
+ const handleNavigateToColumn = useCallback((columnName: string) => {
+ setActiveTabKey(TABS_KEYS.COLUMNS);
+ // Filter to the column as well as expanding it: on a wide table the row
+ // would otherwise open somewhere below the fold, which reads as the link
+ // having done nothing.
+ setColumnSearchTerm(columnName);
+ setColumnToReveal(previous => ({
+ name: columnName,
+ nonce: (previous?.nonce ?? 0) + 1,
+ }));
+ }, []);
+
+ const handleMoveMappingHere = useCallback(
+ (columnName: string) => {
+ setDatabaseColumns(prev =>
+ applyMappingMove(
+ prev,
+ columnName,
+ defaultTransformFor(
+ datasource,
+ prev.find(column => column.column_name === columnName),
+ ),
+ ),
+ );
+ // Always explicit from here: the owner picked this column, so the mapping
+ // must not drift back the next time the default datetime column moves.
+ setDatasource(prev => ({ ...prev, partition_mapped_column: columnName }));
+ },
+ [datasource],
+ );
+
+ const handleRemoveMapping = useCallback(() => {
+ // Every column, not just the one that resolved as mapped: with the override
+ // gone the mapping falls back to the default datetime column, so a
+ // transform left anywhere else would come straight back to life -- which is
+ // the one thing "remove" has to rule out. `main_dttm_col` can name a
+ // calculated column, so both lists are cleared.
+ setDatabaseColumns(prev => clearMappingTransforms(prev));
+ setCalculatedColumns(prev => clearMappingTransforms(prev));
+ // The partition column stays designated; only the mapping goes away, which
+ // is the 1g state -- hidden from Explore, nothing mirrored onto it, and the
+ // panel's warning saying so.
+ setDatasource(prev => ({ ...prev, partition_mapped_column: null }));
+ }, []);
+
+ const handleMonotonicChange = useCallback(
+ (columnName: string, isMonotonic: boolean) => {
+ setDatabaseColumns(prev =>
+ prev.map(column =>
+ column.column_name === columnName
+ ? { ...column, partition_transform_is_monotonic: isMonotonic }
+ : column,
+ ),
+ );
+ },
+ [],
+ );
+
+ const handleMainDttmColChange = useCallback(
+ (value?: string) => {
+ // Without an override the mapped column *is* the default datetime column,
+ // so re-pointing it moves the mapping. The value transform stays behind
+ // and is cleared: it was written about the old column, and the mapping
+ // arrives inert rather than mirroring an expression nobody checked
+ // against its new home. Tested on the partition column plus the absent
+ // override rather than on `mappedColumnIsImplicit`, which needs a
+ // datetime column already set and so misses the transition that sets the
+ // first one.
+ if (datasource.partition_column && !datasource.partition_mapped_column) {
Review Comment:
With partition filter mapping disabled, changing the default datetime column away and back still clears the stored transform and monotonicity flag; saving then permanently loses the configuration even though its controls are hidden. Could this clearing branch respect the feature flag, as the backend cleanup does?
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/useDebouncedCommit.ts:
##########
@@ -0,0 +1,85 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { debounce } from 'lodash-es';
+import { Constants } from '@superset-ui/core/components';
+
+/**
+ * Local text state that commits upward on a debounce.
+ *
+ * The dataset editor's commit path is asynchronous and snapshot-based: a value
+ * handed to `onChange` travels Field -> Fieldset -> CollectionTable ->
+ * DatasourceEditor -> DatasourceModal and arrives back on the `value` prop
+ * several renders later, and the callback that commits it was built during an
+ * earlier render. An input driven straight off that prop therefore loses any
+ * keystroke that lands while a commit is in flight -- which is why every other
+ * control in the editor types into local state and commits on a debounce, and
+ * why Fieldset's own comment says the editor assumes exactly that. This is
+ * TextControl's contract (src/explore/components/controls/TextControl), minus
+ * the ControlHeader and the number parsing this field does not want.
+ */
+export function useDebouncedCommit(
+ value: string | null | undefined,
+ commit: (next: string) => void,
+ delay: number = Constants.FAST_DEBOUNCE,
+) {
+ const [localValue, setLocalValue] = useState(value ?? '');
+ const [prevValue, setPrevValue] = useState(value);
+
+ // The commit fires from a timer, so the callback is handed in at call time
+ // rather than captured when the debounce was built -- otherwise it would
+ // close over whichever render happened to create it, and the commit reads
+ // props (the column's monotonic flag) to decide what to write.
+ const debouncedCommit = useRef(
+ debounce(
+ (next: string, commitFn: (value: string) => void) => commitFn(next),
+ delay,
+ ),
+ );
+
+ useEffect(() => () => debouncedCommit.current.cancel(), []);
+
+ const onChange = useCallback(
+ (next: string) => {
+ setLocalValue(next);
+ debouncedCommit.current(next, commit);
+ },
+ [commit],
+ );
+
+ /**
+ * Commit a pending edit now. lodash's `flush` is a no-op when nothing is
+ * pending, so a blur with no edit behind it costs nothing.
+ */
+ const flush = useCallback(() => {
+ debouncedCommit.current.flush();
+ }, []);
+
+ // Re-seed from the prop only when the prop itself changed. Adjusting state
+ // during render is React's documented pattern for this; deriving a display
+ // value without writing it back leaves `localValue` holding superseded text,
+ // so the next render that changes only an unrelated prop -- and so does not
+ // re-enter this branch -- puts the stale value back in the input.
+ if (prevValue !== value) {
Review Comment:
The echo guard still misses clearing the input: it records an empty string, but the section commits it as null, so clearing, pressing Enter, and immediately typing again lets the delayed null echo erase the new characters. Could the guard compare normalized values and cover that nullable round trip in the regression test?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "hughhhh (via GitHub)" <gi...@apache.org>.
hughhhh commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4162116308
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/useDebouncedCommit.ts:
##########
@@ -0,0 +1,85 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { debounce } from 'lodash-es';
+import { Constants } from '@superset-ui/core/components';
+
+/**
+ * Local text state that commits upward on a debounce.
+ *
+ * The dataset editor's commit path is asynchronous and snapshot-based: a value
+ * handed to `onChange` travels Field -> Fieldset -> CollectionTable ->
+ * DatasourceEditor -> DatasourceModal and arrives back on the `value` prop
+ * several renders later, and the callback that commits it was built during an
+ * earlier render. An input driven straight off that prop therefore loses any
+ * keystroke that lands while a commit is in flight -- which is why every other
+ * control in the editor types into local state and commits on a debounce, and
+ * why Fieldset's own comment says the editor assumes exactly that. This is
+ * TextControl's contract (src/explore/components/controls/TextControl), minus
+ * the ControlHeader and the number parsing this field does not want.
+ */
+export function useDebouncedCommit(
+ value: string | null | undefined,
+ commit: (next: string) => void,
+ delay: number = Constants.FAST_DEBOUNCE,
+) {
+ const [localValue, setLocalValue] = useState(value ?? '');
+ const [prevValue, setPrevValue] = useState(value);
+
+ // The commit fires from a timer, so the callback is handed in at call time
Review Comment:
Fixed in `1e132aefc9`. Leftover, as you guessed — the hook never saw a monotonic flag. The claim is gone; the comment now says only why the callback is passed at call time.
##########
superset/daos/dataset.py:
##########
@@ -476,6 +484,48 @@ def _validate_column_date_formats(
"python_date_format is an invalid date/timestamp format."
)
+ @staticmethod
+ def clear_unmapped_partition_transforms(model: SqlaTable) -> None:
+ """
+ Drop the value transform from every column the mapping does not mirror.
+
+ A mapping has exactly one mirrored column, so at most one column may
+ carry a transform. A transform parked on any other column is invisible
+ -- no row but the mapped one renders one -- yet it is still stored, and
+ it goes live the moment the mapped column resolves back to it. Clearing
+ an override is enough to do that: a null `partition_mapped_column` means
+ "follow `main_dttm_col`", so dropping a mapping would otherwise activate
+ whatever the default datetime column happened to be holding, turning a
+ request to remove a mapping into a request to add a different one.
+
+ Enforced here rather than in the editor alone because the editor is only
+ one writer: a PUT, an `override_columns=true` metadata sync and an
+ import all reach the columns directly. The same argument
+ `clear_dangling_partition_mapping` makes about dangling columns.
+
+ Gated on the feature flag, unlike its sibling, because this discards
+ stored configuration rather than repairing a broken reference. With the
+ flag off nothing mirrors, so there is no armed mapping to disarm and
+ clearing would be pure loss.
+ """
+ if not feature_flag_manager.is_feature_enabled(PARTITION_FILTER_MAPPING_FLAG):
+ return
+
+ mapped_column = (
+ (model.partition_mapped_column or model.main_dttm_col)
+ if model.partition_column
+ else None
+ )
+ for column in model.columns:
Review Comment:
Fixed in `1e132aefc9`. Confirmed, and it was the one case the method most needed to catch. `db.session.flush()` + `db.session.expire(model, ["columns"])` now run before the loop, so the collection reflects the FK inserts. Pinned by `test_a_transform_on_a_column_added_in_the_same_request_is_cleared`, which adds a column *with* a transform and points the mapping elsewhere in one request — it fails without the flush.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #43870:
URL: https://github.com/apache/superset/pull/43870#issuecomment-5945364859
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers an incremental AI Review.
- `/review full` - Manually triggers a full AI Review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(explore): indicate when a filter is mirrored onto a partition column [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r3970149881
##########
superset-frontend/packages/superset-ui-chart-controls/src/shared-controls/sharedControls.tsx:
##########
@@ -208,9 +208,56 @@ const time_grain_sqla: SharedControlConfig<'SelectControl'> = {
sortComparator: () => 0, // Disable frontend sorting to preserve backend order
};
+/**
+ * The mapping to hand the time control's partition-pruning indicator, or `null`
+ * when this time range is not mirrored.
+ *
+ * The control renders whatever mapping it is given, so the applicability check
+ * belongs here, where the selected temporal column and the range are both in
+ * scope. Unlike an ad-hoc filter chip the control names no column of its own:
+ * the query path mirrors the time range only when the *chart's* temporal column
+ * is the mapped one (`superset/models/helpers.py`, the `granularity` and
+ * `always_filter_main_dttm` branches), and only when the range resolves to at
+ * least one bound -- `No filter` resolves to neither.
+ */
+function timeRangePartitionMapping({
+ datasource,
+ form_data: formData,
+}: ControlPanelState) {
+ const dataset = datasource as Dataset | null;
+ const mapping = dataset?.partition_filter_mapping;
+ if (
+ !mapping?.active ||
+ !mapping.mirrorable_operators?.includes('TEMPORAL_RANGE')
+ ) {
+ return null;
+ }
+ if (formData?.time_range === NO_TIME_RANGE) {
+ return null;
+ }
+ const granularity = formData?.granularity_sqla;
+ const selectedColumn = isDefined(granularity)
+ ? getColumnLabel(granularity)
+ : undefined;
+ const mirrorsSelectedColumn = selectedColumn === mapping.mapped_column;
+ // `always_filter_main_dttm` adds a second time filter on the main datetime
+ // column even when the chart groups by another one, and that filter mirrors.
+ const mirrorsMainDttm = Boolean(
+ dataset?.always_filter_main_dttm &&
+ dataset.main_dttm_col === mapping.mapped_column,
+ );
+ return mirrorsSelectedColumn || mirrorsMainDttm ? mapping : null;
+}
+
const time_range: SharedControlConfig<'DateFilterControl'> = {
type: 'DateFilterControl',
freeForm: true,
+ // The indicator needs to know whether this filter is mirrored onto a
+ // partition column; the summary is self-contained on the datasource so this
+ // does not have to reach into `columns`.
+ mapStateToProps: state => ({
Review Comment:
Changing the time range is handled by `SET_FIELD_VALUE`, which evaluates this mapper against the pre-action form data; and this control does not opt into render-time recalculation. After switching a mapped range to `No filter` (or the reverse), `partitionMapping` can therefore retain its old value and leave the glyph opposite the generated SQL. Could this opt into recalculation and add a field-update regression case?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4235432575
##########
superset/commands/dataset/refresh.py:
##########
@@ -72,6 +87,24 @@ def run(self) -> Model:
ex.message,
)
+ # `fetch_metadata` writes the columns itself rather than going through
+ # `DatasetDAO.update`, so neither of the mapping's own repairs runs. It
+ # can drop the column `partition_column` names -- leaving a reference
+ # that fails `UpdateDatasetCommand`'s validation on every later edit,
+ # including a description-only PUT, which carries no columns payload and
+ # so cannot reach the branch that forgives a stored-only dangle -- and
+ # it can *set* `main_dttm_col`, which moves the effective mapped column
+ # and can bring a parked transform live.
+ #
+ # No flush needed to read the columns: `fetch_metadata` reassigns the
+ # relationship, so the surviving set is already correct in memory.
+ DatasetDAO.clear_dangling_partition_mapping(
Review Comment:
The dangling-reference repair only runs on this command, but a re-upload into an existing mapped table also replaces its columns through `fetch_metadata()` (`UploadCommand.run`, `superset/commands/database/uploaders/base.py`). If the new file no longer has the partition column, the reference is left pointing at a column that is gone, and a later description-only `PUT /api/v1/dataset/<pk>` then fails the mapping validation, as in the refresh case above. Could the repair live where the columns are replaced (or be called from the upload path too) so every column-sync writer clears it?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2770 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+#: Returned by `ExploreMixin.mirror_probe_request` for a filter no mirror can
+#: stand in for: one the engine compares more coarsely than the value carries, a
+#: value it cannot render as a literal, or an ``IN`` list with a member of
+#: either kind. A sentinel rather than `None`, because `None` is a filter value
+#: in its own right.
+#:
+#: Lives here rather than beside that method so the preview can read it too:
+#: `superset.models.helpers` imports this module, so the sentinel can only cross
+#: the boundary in this direction. Both callers have to recognise the same
+#: object -- a preview that answered "valid" for a request the chart path
+#: declines is the drift this is here to prevent.
+UNMIRRORABLE = object()
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error( # noqa: C901
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ And it must be a *read*. Shape is a separate question from effect: a bare
+ scalar expression can still write, so `SQLStatement.is_mutating` is asked
+ too -- the same question SQL Lab and the chart executor ask before letting
+ SQL run. See the gate itself for what that reaches and what it does not.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ # Also ahead of the parse, and for a stronger reason than cost: every gate
+ # below reasons about the parse tree, and this is the one construct that
+ # makes the parse tree describe a different statement from the one the
+ # engine runs. Checked here as well as in `validate_transform` because this
+ # is the door a row written by an earlier release still comes through.
+ if contains_executable_comment(transform):
+ return str(
+ _(
+ "A partition value transform cannot contain a MySQL "
+ "executable comment, which the database executes and every "
+ "validator reads as a comment."
+ )
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The read-only gate, which nothing above implies. The shape gates ask what
+ # the transform *selects*; this asks what evaluating it *does*, and a bare
+ # scalar expression can still write. `nextval(:value)` on PostgreSQL
+ # advances a sequence: one function call, no clause, no sub-query, and not
+ # in the default `DISALLOWED_SQL_FUNCTIONS` either -- so every gate above
+ # passes it and the probe then runs it. `setval` is the same shape, and
+ # `exp.Execute` and the opaque-`exp.Command` forms arrive the same way.
+ #
+ # The large-object writers (`lo_export`, `lowrite`, `lo_from_bytea`, ...)
+ # are caught here too, and the shipped denylist happens to name them as
+ # well -- but that is config an operator can replace, while this is not.
+ #
+ # `is_mutating` is the same question SQL Lab, `get_virtual_table_metadata`
+ # and the chart executor ask before letting SQL run, so a transform is held
+ # to the bar the rest of Superset already sets rather than to one invented
+ # here. Unconditional rather than gated on `Database.allow_dml`: a transform
+ # is a scalar function of `:value` by definition, so there is no legitimate
+ # mutating one, and the probe runs on a cache schedule nobody chose -- a
+ # write would repeat every time the entry expired.
+ #
+ # It bears saying what this does not reach. A user-defined function whose
+ # body writes is a plain call no parser can tell from `lower(:value)`, and
+ # `is_mutating`'s function-name walk is PostgreSQL-only by design, since the
+ # same names are read-only elsewhere. Neither residual is specific to this
+ # feature -- a dataset editor can already have the engine evaluate an
+ # arbitrary expression through a calculated column or a virtual dataset's
+ # SQL -- and closing them means authorizing the preview against the
+ # database, not parsing harder.
+ if statement.is_mutating():
+ return str(
+ _(
+ "A partition value transform cannot change data. It is "
+ "evaluated against the database to check that it mirrors, so "
+ "it has to be a read."
+ )
+ )
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the probe
+ uninspected -- string elements are escaped by the dialect's own literal
+ processor. `probe_sql_is_evaluable` then re-reads the finished query, which
+ is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def _placeholder_is_bindable(transform: str) -> bool:
+ """
+ Whether SQLAlchemy's ``text()`` can see ``:value`` as a bound parameter.
+
+ `VALUE_PLACEHOLDER_RE` is ``:value\b``, which matches the placeholder in a
+ Postgres cast such as ``:value::bigint``. SQLAlchemy's own bind scan is
+ ``(?<![:\\w$]):([\\w$]+)(?![:\\w$])`` -- note the trailing exclusion -- so a
+ following colon stops it: ``text(":value::bigint")`` reports a parameter
+ named ``valu``, and ``.bindparams(bindparam("value"))`` then raises
+ ``ArgumentError``.
+
+ `_probe` swallows that, so the only symptom was a perfectly valid transform
+ whose mapping silently never pruned, and a preview reporting an engine
+ failure for SQL that was never sent. Every write-side gate passes the
+ transform: it parses, it is a bare expression, and the placeholder *is* in
+ an executable position.
+
+ Answered by attempting the bind itself rather than by pattern-matching
+ ``::`` or reading ``text()``'s private parameter map, so this cannot
+ disagree with what `build_probe_sql` is about to do -- on any dialect, or on
+ a SQLAlchemy whose scan changes.
+ """
+ try:
+ sa.text(transform).bindparams(sa.bindparam("value", value=None))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return False
+ return True
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ bindable = _placeholder_is_bindable(transform)
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ elif bindable:
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ rendered = _compile_literal(clause, dialect)
+ else:
+ # `text()` cannot see the placeholder (see
+ # `_placeholder_is_bindable`), so the value is rendered by the
+ # dialect's own literal processor first and substituted as SQL
+ # text. The same two steps in the other order: binding exists to
+ # get the value through that processor, and `_compile_literal`
+ # inlines the result either way, so this is the same string by a
+ # different route -- not a loosening of the "never interpolate a
+ # raw value" rule. `parse_skeleton` substitutes literally, so a
+ # rendered literal containing a backslash is safe here.
+ rendered = parse_skeleton(
+ transform, _compile_literal(sa.literal(value), dialect)
+ )
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Four things have to hold, and all four are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ # Before the parse, because this gate's whole contract is that what the
+ # parse describes is what the engine will run, and an executable comment is
+ # precisely the text where that stops being true. The transform is already
+ # refused for carrying one; this covers the compiled statement, so no later
+ # change to how values are rendered can reintroduce it behind the gates
+ # below.
+ if contains_executable_comment(sql):
+ return False
+
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if not isinstance(statement, SQLStatement):
+ # A dialect whose statements this gate cannot take apart -- KQL -- gets
+ # no probe rather than an unchecked one. It never had one: the clause
+ # inspection below is implemented for SQL statements only, and the
+ # alternative to declining here is an `AttributeError` that `_probe`
+ # swallows into the same outcome, less legibly.
+ return False
+ if statement.has_subquery():
+ return False
+ if statement.get_clause_names() - {"from"}:
+ return False
+ if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+ """
+ The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+ Parsed rather than string-compared so that the comparison in
+ `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+ not parse answers ``None``, which no statement carrying a FROM can match --
+ the probe then declines, which is the right way for an unreadable engine
+ constant to fail.
+ """
+ if not from_suffix.strip():
+ return None
+ try:
+ return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+ except SupersetParseError:
+ return None
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=values is not None and not any(value is None for value in values),
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ from_suffix = database.db_engine_spec.select_without_from_suffix
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ from_suffix,
+ )
+ if not probe_sql_is_evaluable(
+ sql, database.backend, len(distinct), from_suffix
+ ):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _execution_identity(database: Database) -> str | None:
+ """
+ Who the warehouse will run the probe as, when that can vary by caller.
+
+ `_probe_cache_key` keys on the `Database` record, which is the *connection*
+ -- not the identity it is opened under. Two hooks make that identity a
+ function of the Superset user instead:
+
+ * ``impersonate_user`` on the database, which hands the effective username
+ to `db_engine_spec.impersonate_user`;
+ * ``DB_CONNECTION_MUTATOR``, which receives the effective username and may
+ return an entirely different account's URL.
+
+ Under either one, a cached probe result computed under user A's grants was
+ served to user B, and the preview echoed it back in ``emitted_predicate``.
+ A transform wrapping a read-capable function the denylist does not name --
+ Oracle's ``DBMS_XMLGEN.GETXML`` is the worked example -- then leaks across
+ users who were never allowed the same rows.
+
+ Returns ``None`` when neither hook is configured, which is the common case
+ and deliberately leaves the key as it was: the cache exists to keep a
+ synchronous warehouse round trip off the chart-query path, and keying every
+ deployment on the username would cost every deployment the hit rate to fix
+ the two that need it.
+
+ The *Superset* username rather than the resolved warehouse account, because
+ it is the input both hooks branch on, and reading it needs no URL parse and
+ puts no credential in the key.
+ """
+ if not (database.impersonate_user or app.config["DB_CONNECTION_MUTATOR"]):
+ return None
+ return get_username()
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _mirror_verdict_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str:
+ """
+ `_probe_cache_key` without the values.
+
+ Whether a transform can be evaluated at all is a property of the transform
+ and the connection, not of the filter that happened to be probing it, so
+ one chart's answer settles the question for the next one.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ # Whether a transform *can* be evaluated is a property of the
+ # transform and the connection -- but under impersonation the
+ # connection is per-user, and a function one account may call can
+ # be refused to another. See `_execution_identity`.
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_verdict:{digest}"
+
+
+def record_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ *,
+ mirrors: bool,
+) -> None:
+ """
+ Remember whether this transform produced a mirror, for the UI to read.
+
+ Advisory only. Nothing in the query path consults it: a probe that failed
+ once is retried on the next chart exactly as it is today, because declining
+ to prune for a whole cache timeout over one transient engine blip is the
+ trade `evaluate_transform` deliberately refuses -- see the comment where it
+ declines to cache a failure.
+
+ What this is for is the *claim*. `is_transform_active` parses the transform
+ and no more, so a transform the database rejects -- a misspelled function
+ is the common case -- is "active", and the editor's banner and Explore's
+ pruning glyph promise a speed-up that never happens. A promise is exactly
+ the thing that may be withheld on one bad answer and restored on a good
+ one, which is why this is a separate entry from the probe's own results
+ rather than a relaxation of that rule.
+
+ Written by `_run_probe`, so the preview endpoint -- which shares the
+ evaluator -- settles the question before the owner has even saved.
+ """
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(
+ _mirror_verdict_cache_key(database, catalog, schema, transform),
+ mirrors,
+ timeout=timeout,
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform verdict", exc_info=True)
+
+
+def known_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> bool | None:
+ """
+ The last verdict `record_mirror_verdict` stored, or `None` if there is none.
+
+ `None` is the honest answer on a cold cache and is deliberately not `False`:
+ reporting a working mapping as broken until something probes it would
+ trade one wrong claim for another. The alternative -- probing from the
+ read side -- would put a warehouse round trip on every Explore and
+ dashboard load, and a failing transform is not cached at all, so it would
+ be a round trip every single time.
+ """
+ try:
+ verdict = cache_manager.cache.get(
+ _mirror_verdict_cache_key(database, catalog, schema, transform)
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return verdict if isinstance(verdict, bool) else None
+
+
+def _compile_literal(element: Any, dialect: Dialect | None) -> str:
+ """
+ Compile with inline literals, undoing the paramstyle's percent doubling.
+
+ Both ``TextClause`` and literal compilation run the dialect's
+ ``post_process_text``, which doubles every ``%`` whenever the identifier
+ preparer asks it to -- true for MySQL and Postgres and for every spec
+ inheriting their paramstyle. That doubling exists so a later DBAPI
+ parameter-interpolation pass can undo it, and the probe has no such pass:
+ it executes with no bound parameters at all. So a transform of
+ ``date_format(:value, '%Y%m%d')`` reaches the warehouse asking for the
+ literal string ``%%Y%%m%%d``, the probe returns that instead of a date, and
+ the mirrored predicate drops every row the filter keeps.
+
+ The same normalization ``Database.compile_sqla_query`` applies for the same
+ reason. ``_double_percents`` is private and not guaranteed on a third-party
+ dialect, hence the ``getattr`` default.
+ """
+ compiled = str(
+ element.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
+ )
+ if dialect is not None and getattr(
+ dialect.identifier_preparer, "_double_percents", False
+ ):
+ compiled = compiled.replace("%%", "%")
+ return compiled
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be *asked* to stand in for itself, and the transform
+ cannot carry Jinja or call a non-deterministic function. Tier 2
+ (``blocking=False``) is everything that merely leaves the mapping inactive
+ -- including a self-mapping nobody asked for, where the partition column
+ merely happens to be the default datetime column.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column == partition_column:
+ # Asked for explicitly, so report it as the mistake it is.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+ elif not partition_mapped_column and main_dttm_col == partition_column:
+ # Resolved onto itself only because the default datetime column happens
+ # to be the partition column -- a state metadata sync could produce
+ # without anyone asking for it. The mapping is inert either way, since
+ # `resolve_partition_mapping` bails out on it, so this reports and lets
+ # the write through: blocking here means a dataset already in the state
+ # can never be saved again, not even to change its description, and
+ # there is no field whose edit would clear the error first.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "%(name)s is both the partition column and the default "
+ "datetime column, so the mapping points at itself and "
+ "stays inactive. Set a mapped column override, or change "
+ "the default datetime column.",
+ name=partition_column,
+ ),
+ blocking=False,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def drop_unmapped_value_transforms(
+ columns: list[dict[str, Any]] | None,
+ *,
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ names_by_id: dict[int, str] | None = None,
+) -> list[str]:
+ """
+ Null the value transform on every *incoming* column the mapping cannot mirror.
+
+ The write-side twin of `DatasetDAO.clear_unmapped_partition_transforms`,
+ which answers for the model. A mapping has exactly one mirrored column, so
+ at most one column may carry a transform. One parked on any other column is
+ invisible -- no row but the mapped one renders a transform -- and yet it is
+ stored, and it goes live the moment the mapped column resolves back to it.
+ Clearing an override is enough to do that: a null
+ ``partition_mapped_column`` means "follow ``main_dttm_col``".
+
+ Ungated on the feature flag, unlike its model-level twin, and the difference
+ is what each one discards. That one drops stored configuration, so with the
+ flag off it would be pure loss. This one drops only a value the request in
+ hand is asking to write where the invariant says none may live -- and the
+ flag-off window is precisely when such a value gets parked for later, since
+ the editor hides these fields and the model-level pass declines to run.
+
+ Three writers reach the columns with no effective model-level pass between
+ them, which is why this exists at all: the deprecated
+ ``POST /datasource/save/``, which writes straight through
+ `update_from_object` and so never had one; and a
+ ``PUT /api/v1/dataset/<pk>`` or a dataset import made while the flag is
+ off, where the pass runs on both sides of the write and declines on both.
+
+ Mutates the payload in place, because every caller hands its own request
+ dict straight on to the code that writes it. Returns the names it cleared,
+ so the caller can say so in a log: this is a silent correction to a payload
+ whose author may have meant it.
+
+ A column whose payload mentions neither field is left alone. "Incoming" is
+ the whole scope -- a transform already in storage on a column this request
+ says nothing about is the model-level pass's business, under its own flag.
+
+ The mapped column resolves the way every other reader resolves it,
+ ``partition_mapped_column or main_dttm_col``, and resolves to nothing
+ without a partition column -- in which case no column may hold a transform
+ either.
+
+ :param names_by_id: how to read the name off a payload entry that gives
+ only an ``id``. `DatasetDAO._upsert_columns` identifies an existing
+ column by its primary key and lets ``column_name`` be omitted -- the
+ column keeps the name it has -- so without this an ordinary PUT looked
+ like a payload of nameless columns, none of which matched the mapped
+ one, and every transform in it was dropped. Callers whose writer keys
+ on the name instead (`update_from_object`, the importer) pass nothing.
+ An entry this cannot name is left alone rather than guessed at.
+ """
+ mapped_column = (
+ (partition_mapped_column or main_dttm_col) if partition_column else None
+ )
+ cleared: list[str] = []
+ for column in columns or []:
+ name = column.get("column_name")
+ if name is None and names_by_id is not None:
+ column_id = column.get("id")
+ if column_id is not None:
+ name = names_by_id.get(column_id)
+ if name is None or name == mapped_column:
+ continue
+ if column.get("partition_value_transform") or column.get(
+ "partition_transform_is_monotonic"
+ ):
+ column["partition_value_transform"] = None
+ column["partition_transform_is_monotonic"] = False
+ cleared.append(name)
+ return cleared
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if contains_executable_comment(transform):
+ # Blocking, and checked on raw text next to the Jinja gate because no
+ # parse reports it: sqlglot reads `/*!50000 ... */` as comment data
+ # while MySQL and MariaDB execute it, so every shape gate downstream
+ # inspects a statement the engine will not run. See
+ # `EXECUTABLE_COMMENT_RE`.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform cannot contain a MySQL executable "
+ "comment (/*! ... */ or /*M! ... */). Those are comments "
+ "to every validator and statement text to the database, "
+ "so what would run is not what was checked."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_bare_expression(transform, engine):
+ # Blocking, and deliberately placed in `validate_transform` rather than
+ # only at the probe: one issue here closes the PUT, the importer, the
+ # query-time gate through `is_transform_active`, the Explore indicator's
+ # active verdict and the preview endpoint, all of which already consult
+ # this function.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform must be a single SQL expression. It "
+ "cannot carry a FROM, WHERE, GROUP BY or any other clause, "
+ "and it cannot contain a sub-query."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not contains_value_placeholder(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform must contain the :value placeholder, "
+ "which stands for the filter value being mirrored."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not placeholder_is_executable(transform, engine):
+ # Blocking, and for the same reason the shape gate above is: this is
+ # the function the PUT, the importer, `is_transform_active`, the
+ # Explore indicator and the preview all consult, so one issue here
+ # closes every door at once. A placeholder inside a string literal is
+ # a sub-query the engine will run once a filter value closes the quote;
+ # one inside a comment silently eats the probe's own alias.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The :value placeholder must appear where the engine will "
+ "evaluate it. It cannot sit inside a string literal or a "
+ "comment."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if functions := find_non_deterministic_functions(transform, engine):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform calls %(functions)s, whose result "
+ "depends on when and where it runs. The transform is "
+ "evaluated in a separate session and the result is cached, "
+ "so the emitted predicate would freeze a snapshot of that "
+ "moment.",
+ functions=", ".join(sorted(functions)),
+ ),
+ blocking=True,
+ )
+ ]
+
+ return []
+
+
+@lru_cache(maxsize=LRU_CACHE_MAX_SIZE)
+def is_transform_active(transform: str | None, engine: str) -> bool:
+ """
+ Whether Superset will mirror filters through this transform.
+
+ `validate_transform` with the messages discarded, so the Explore indicator
+ cannot advertise a mapping the save path recorded as inactive. Anything
+ cheaper here would be a second, weaker statement of the same rule, free to
+ drift from the one the save path applies.
+
+ Blocking issues count too. Jinja and non-deterministic transforms are
+ rejected on PUT, but `CreateDatasetCommand` and import do not validate the
+ mapping, so one can still reach the database -- and it would never mirror a
+ filter either.
+
+ Memoized because `partition_filter_mapping_summary` is serialized on every
+ Explore and dashboard load and this parses the transform. The key is
+ everything the answer depends on: `validate_transform` reads no session, no
+ locale and no config beyond `SQL_MAX_PARSE_LENGTH`, which bounds the parser
+ rather than changing a verdict within that bound.
+ """
+ return not validate_transform(transform, engine)
+
+
+def preview_partition_mapping( # pylint: disable=too-many-return-statements
+ datasource: SqlaTable,
+ *,
+ mapped_column: str,
+ value_transform: str | None,
+ sample_values: list[str],
+ operator: FilterOperator = FilterOperator.EQUALS,
+ is_monotonic: bool = False,
+ partition_column: str | None = None,
+) -> dict[str, Any]:
+ """
+ Evaluate a candidate mapping and describe the predicate it would emit.
+
+ Shares the evaluator -- and therefore the probe cache -- with the query
+ path, so preview and runtime cannot drift and a previewed transform warms
+ the chart path for free. The predicate itself comes from
+ `build_mirrored_predicates`, the same builder the query path uses, so
+ operator shapes cannot drift either: what the panel shows is what a chart
+ would emit.
+
+ Validation runs first and the engine second: a half-typed transform is by
+ definition unparseable, so most of what a text input produces costs zero
+ queries.
+
+ Every part of the mapping is taken from the request rather than the stored
+ dataset. The editor previews while the owner is still editing -- a mapping
+ that has to be saved before it can be checked is not a preview.
+ """
+ partition_column = partition_column or datasource.partition_column
+ if not partition_column:
+ return {
+ "valid": False,
+ "reason": "unconfigured",
+ "error": _("No partition column is set."),
+ }
+
+ columns_by_name = {str(column.column_name): column for column in datasource.columns}
+ if mapped_column not in columns_by_name:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _("%(name)s is not a column on this dataset.", name=mapped_column),
+ }
+
+ # The bail-out `resolve_partition_mapping` makes at query time, and that
+ # `partition_filter_mapping_summary` repeats for the Explore indicator.
+ # Without it here, preview reports a valid emitted predicate for a mapping
+ # no chart will ever mirror -- the one answer a preview panel must not give.
+ if has_active_advanced_data_type(columns_by_name[mapped_column]):
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _(
+ "%(name)s has an advanced data type, so its filters are "
+ "translated into their own predicate shape and cannot be "
+ "mirrored onto the partition column.",
+ name=mapped_column,
+ ),
+ }
+
+ engine = datasource.database.backend
+ for issue in validate_partition_mapping(
+ column_names=set(columns_by_name),
+ partition_column=str(partition_column),
+ partition_mapped_column=mapped_column,
+ main_dttm_col=datasource.main_dttm_col,
+ transform=value_transform,
+ engine=engine,
+ ):
+ return {
+ "valid": False,
+ # The parse failure is the one an owner sees constantly, and it is
+ # the only one the mockup gives its own headline to.
+ "reason": (
+ "parse"
+ if issue.field == "partition_value_transform"
+ and not is_parseable(value_transform, engine)
+ else "validation"
+ ),
+ "error": str(issue.message),
+ }
+
+ # The policy every other stored expression goes through. The save path
+ # applies it in `UpdateDatasetCommand._validate_partition_mapping`, but
+ # preview evaluates a candidate transform that has not been saved, so
+ # without this the gate had a door around it. See
+ # `stored_expression_error` for what is being kept out and why.
+ if reason := stored_expression_error(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ cast(str, value_transform),
+ ):
+ return {"valid": False, "reason": "validation", "error": reason}
+
+ mapping = PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=mapped_column,
+ value_transform=cast(str, value_transform),
+ is_monotonic=is_monotonic,
+ equality_is_safe=equality_mirrors_safely(
+ columns_by_name[mapped_column], datasource.database.db_engine_spec
+ ),
+ )
+ sample_input = _render_sample_input(
+ datasource, mapped_column, operator, sample_values
+ )
+
+ if operator not in PREVIEWABLE_OPERATORS:
+ # Checked before `mirrors`, which lets `TEMPORAL_RANGE` through when the
+ # transform is declared monotonic -- and the single sample value would
+ # then reach `handle_comparison_filter`, which has no case for a range
+ # and raises. The request schema rejects it too; this keeps the function
+ # honest for any other caller.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is mirrored as a pair of bounds, which "
+ "a preview of a single value cannot describe.",
+ operator=operator.value,
+ ),
+ }
+
+ if operator in MIRRORABLE_ALWAYS and not mapping.equality_is_safe:
+ # Withdrawn by `equality_mirrors_safely`, which no declaration about
+ # ordering can change -- so naming monotonicity here would send the
+ # owner to a checkbox that leaves the answer as it is.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter on this text column is not mirrored: "
+ "the database may treat strings that differ in case or "
+ "trailing spaces as equal, and the mirrored predicate could "
+ "then drop rows the filter keeps.",
+ operator=operator.value,
+ ),
+ }
+
+ if not mapping.mirrors(operator):
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is only mirrored when the transform "
+ "preserves ordering, which this one is not declared to do.",
+ operator=operator.value,
+ ),
+ }
+
+ return _preview_probe(
+ datasource,
+ mapping,
+ columns_by_name[mapped_column],
+ operator,
+ sample_values,
+ sample_input,
+ )
+
+
+def _preview_probe(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ mapped_col: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+ sample_input: str,
+) -> dict[str, Any]:
+ """
+ The half of a preview that needs the warehouse.
+
+ Split out from `preview_partition_mapping` so that the gates which answer
+ from the stored mapping alone stay readable as the single run of guard
+ clauses they are. Everything here has either run a query or decided not to.
+ """
+ value = datasource.mirror_probe_request(
+ operator,
+ _probe_input(datasource, mapped_col, operator, sample_values),
+ mapped_col,
+ )
+ if value is UNMIRRORABLE:
+ # The same step the chart path applies, so the preview cannot promise a
+ # mirror the query declines. Its own reason: the transform is fine and
+ # the engine evaluates it, the filter just carries more of the value
+ # than the engine compares on this column -- which is the column's type
+ # talking, not a broken expression.
+ return {
+ "valid": False,
+ "reason": "resolution",
+ "sample_input": sample_input,
+ "error": _(
+ "This engine compares less of a %(operator)s value on "
+ "%(column)s than the filter carries, so there is no mirror a "
+ "predicate on the partition column could stand in for. Map a "
+ "column the engine compares in full to mirror this operator.",
+ operator=operator.value,
+ column=mapped_col.column_name,
+ ),
+ }
+ errors: list[str] = []
+ type_errors: list[str] = []
+ predicates = build_mirrored_predicates(
+ datasource,
+ mapping,
+ [(operator, value)],
+ errors=errors,
+ type_errors=type_errors,
+ )
+ if type_errors:
+ # Its own reason, because "the database would not evaluate this" and
+ # "it evaluated and answered with the wrong kind of thing" are
+ # different problems with different fixes, and the owner is the only
+ # one who can tell which transform they meant to write.
+ return {
+ "valid": False,
+ "reason": "type",
+ "sample_input": sample_input,
+ "error": type_errors[0],
+ }
+ if not predicates:
+ return {
+ "valid": False,
+ "reason": "engine",
+ "sample_input": sample_input,
+ "error": (
+ _(
+ "The transform could not be evaluated against the "
+ "database: %(reason)s",
+ reason=errors[0],
+ )
+ if errors
+ else _("The transform could not be evaluated against the database.")
+ ),
+ }
+
+ return {
+ "valid": True,
+ "sample_input": sample_input,
+ "emitted_predicate": _render_predicate(datasource, predicates[0]),
+ }
+
+
+def _probe_input(
+ datasource: SqlaTable,
+ column: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+) -> Any:
+ """
+ The sample values as the query path would bind them.
+
+ The request carries samples as strings, and the probe is keyed on exactly
+ what it is handed, so passing them through raw asks the engine a different
+ question from the one a chart asks. A sample of ``2025`` on a numeric
+ column has to arrive as the integer the chart compares: under a transform
+ of ``typeof(:value)`` the raw string previewed ``'text'`` where the chart
+ emitted ``'integer'``. And because `_probe_cache_key` keys on each value's
+ ``repr``, the two also missed each other's cache entirely -- so the "a
+ previewed transform warms the chart path for free" claim in
+ `preview_partition_mapping`'s docstring did not actually hold.
+
+ Coerced by `filter_values_handler`, the same function the query path uses,
+ rather than by a second implementation of the same rules. Everything the
+ query path then does to the coerced value -- rendering an expression as a
+ literal, widening a bound, declining a comparison the engine resolves too
+ coarsely -- is `ExploreMixin.mirror_probe_request`'s, and the caller hands
+ this result straight to it.
+
+ Ranges are not previewable (see `PREVIEWABLE_OPERATORS`), so the bound
+ conversion `_collect_partition_mirror_range` applies -- a ``datetime`` into
+ the column's stored representation -- has no counterpart here.
+
+ An array column is the exception to `filter_values_handler`: its predicate
+ is built from the raw value, parsed into elements and rendered as the
+ engine's own array literal, so the chart path probes that literal
+ (`ExploreMixin._array_mirror_probe_value`) and this does too. Passing the
+ handled text instead previewed ``length('[1, 2]')`` for a filter whose
+ query probes ``length(array(1, 2))``.
+
+ Answers with a value, or `None` where an engine spec claims array columns
+ without an array literal -- which `mirror_probe_request` then declines, as
+ the chart path declines it. Otherwise `UNMIRRORABLE` is
+ `mirror_probe_request`'s to return, and the caller hands this straight to it.
+ """
+ is_list = operator == FilterOperator.IN
+ column_spec = datasource.db_engine_spec.get_column_spec(native_type=column.type)
+ if (
+ column_spec
+ and column_spec.generic_type == utils.GenericDataType.MULTI_VALUE
+ and operator in MIRRORABLE_ALWAYS
+ ):
+ # `=` and `IN` are the previewable operators the array branch builds a
+ # literal for; a bound on an array column binds the handled value on
+ # the chart path too, so it falls through to the same here.
+ return datasource._array_mirror_probe_value( # noqa: SLF001
+ sample_values if is_list else sample_values[0],
+ operator,
+ datasource.db_engine_spec.get_array_element_type(column.type),
+ datasource.db_engine_spec,
+ )
+ handled = datasource.filter_values_handler(
+ # `list[str]` is not a `list[FilterValue]` to mypy, invariantly, even
+ # though every `str` is a `FilterValue`.
+ values=cast(FilterValues, sample_values if is_list else sample_values[0]),
+ operator=operator,
+ target_generic_type=(
+ column_spec.generic_type if column_spec else utils.GenericDataType.STRING
+ ),
+ target_native_type=column.type,
+ is_list_target=is_list,
+ db_engine_spec=datasource.db_engine_spec,
+ db_extra=datasource.db_extra,
+ )
+ # No `ColumnElement` conversion here: an epoch-milliseconds sample comes back
+ # as engine SQL rather than a value, and `mirror_probe_request` renders it --
+ # the same step, on the same values, as for a chart filter.
+ return handled
+
+
+def _render_sample_input(
+ datasource: SqlaTable,
+ mapped_column: str,
+ operator: FilterOperator,
+ values: list[str],
+) -> str:
+ """
+ The filter being previewed, written the way an owner would read it.
+
+ Display-only -- it is never executed -- but it is still read as SQL, so the
+ column is quoted and the values are rendered by the dialect rather than
+ concatenated raw. A column named ``order date`` would otherwise come out as
+ two bare words.
+ """
+ quoted = datasource.quote_identifier(mapped_column)
+ if operator == FilterOperator.IN:
+ rendered = ", ".join(
+ _render_literal(datasource.database, value) for value in values
+ )
+ return f"{quoted} IN ({rendered})"
+ return (
+ f"{quoted} {operator.value} {_render_literal(datasource.database, values[0])}"
+ )
+
+
+def _render_predicate(datasource: SqlaTable, predicate: ColumnElement[Any]) -> str:
+ """
+ Compile a mirrored predicate to the text a reader would see in View query.
+
+ Every value in it is a probed constant by this point, so ``literal_binds``
+ renders the same literals the chart query carries.
+ """
+ return _compile_literal(predicate, _dialect_for(datasource.database)).replace(
+ "\n", " "
+ )
+
+
+def _render_literal(database: Database, value: Any) -> str:
+ """
+ Render a value the way it appears in the generated SQL.
+
+ Compiled by the dialect rather than formatted by hand. `str()` would render
+ a NULL as the Python repr `None` and leave a date unquoted, neither of which
+ is SQL, and hand-rolled quote-doubling would only ever have been right for
+ strings.
+ """
+ return _compile_literal(sa.literal(value), _dialect_for(database))
+
+
+def build_mirrored_predicates(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ requests: list[tuple[FilterOperator, Any]],
+ *,
+ errors: list[str] | None = None,
+ type_errors: list[str] | None = None,
+) -> list[ColumnElement[Any]]:
+ """
+ Turn collected ``(operator, value)`` mirror requests into predicates.
+
+ ``requests`` is expected to be deduplicated by the caller. Every value is
+ resolved in a single probe round trip -- one per chart query at most -- then
+ emitted as a literal constant, so "View query" shows the reader an ordinary
+ ``WHERE`` clause rather than an inline expression.
+
+ A strict bound is emitted non-strictly; see `mirror_operator`. That happens
+ here, at the one point where a ``FilterOperator`` becomes SQL, rather than
+ at the collection sites in `ExploreMixin`: the preview endpoint calls this
+ directly, so this is what keeps the predicate the editor shows an owner and
+ the predicate the chart carries from disagreeing.
+
+ :param errors: optional sink; see `evaluate_transform`.
+ :param type_errors: optional sink for a probe result the partition column
+ cannot hold -- see `probed_value_type_error`. Separate from ``errors``
+ because the two say different things to an owner: that one is "the
+ database would not evaluate this", and this one is "it evaluated, and
+ answered with the wrong kind of thing".
+ """
+ if not requests:
+ return []
+
+ partition_column = next(
+ (
+ column
+ for column in datasource.columns
+ if column.column_name == mapping.partition_column
+ ),
+ None,
+ )
+ if partition_column is None:
+ return []
+
+ # Flatten every value that needs probing into one list, remembering how many
+ # each request consumed so the results can be handed back out.
+ flat: list[Any] = []
+ spans: list[tuple[FilterOperator, int, int]] = []
+ for operator, value in requests:
+ values = list(value) if operator == FilterOperator.IN else [value]
+ spans.append((operator, len(flat), len(values)))
+ flat.extend(values)
+
+ evaluated = evaluate_transform(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ mapping.value_transform,
+ flat,
+ errors=errors,
+ )
+ if evaluated is None:
+ return []
+
+ if not _bounds_are_ordered(evaluated, spans):
+ return []
+
+ # Declining here is the last chance to decline at all: once these
+ # predicates are in the statement, a value the partition column cannot
+ # hold fails the whole chart rather than its pruning.
+ if reason := probed_value_type_error(partition_column, evaluated):
+ logger.warning(
+ "Partition transform returned a value the partition column cannot "
+ "hold; queries will not prune: %s",
+ reason,
+ )
+ if type_errors is not None:
+ type_errors.append(reason)
+ # Deliberately *not* recorded as a mirror verdict. The transform
+ # evaluated perfectly; what failed is the comparison against this
+ # dataset's partition column -- and `_mirror_verdict_cache_key` is
+ # keyed on database, catalog, schema and transform, with no partition
+ # column in it. Recorded, this dataset-specific outcome answered for
+ # every other dataset sharing the transform: `CAST(:value AS text)`
+ # mirroring happily onto a text key in dataset A was reported
+ # `evaluable: false` -- and its pruning indicator hidden -- because
+ # someone previewed the same transform against a numeric key in
+ # dataset B. A probe cache hit on A never rewrites the verdict, so it
+ # stayed wrong until the entry expired.
+ return []
+
+ sqla_col = datasource.convert_tbl_column_to_sqla_col(partition_column)
+ predicates = _predicates_from_probe(
+ sqla_col, datasource.db_engine_spec, evaluated, spans
+ )
+ if not predicates:
+ return []
+
+ # A comparison against a NULL partition value is NULL, so a row parked in a
+ # NULL partition is dropped by the mirror even when the real filter matches
+ # it -- Hive and Impala's default partition, or a transform that returns
+ # NULL for an input it cannot convert. The mirror only has to be no
+ # narrower than the filter it stands in for, so admitting NULL partitions
+ # keeps those rows. Engines still prune; they read one extra partition.
+ return [sa.or_(sa.and_(*predicates), sqla_col.is_(None))]
+
+
+def _predicates_from_probe(
+ sqla_col: ColumnElement[Any],
+ db_engine_spec: type[BaseEngineSpec],
+ evaluated: list[Any],
+ spans: list[tuple[FilterOperator, int, int]],
+) -> list[ColumnElement[Any]]:
+ """
+ One predicate on the partition column per surviving mirror request.
+
+ A request whose probe answered `None` for any of its values is skipped
+ rather than emitted: `col = NULL` is `NULL`, so it would drop every row the
+ filter keeps. A strict bound is emitted non-strictly; see `mirror_operator`.
+ """
+ predicates: list[ColumnElement[Any]] = []
+ for operator, start, length in spans:
+ chunk = evaluated[start : start + length]
+ if any(value is None for value in chunk):
+ continue
+ if operator == FilterOperator.IN:
+ # The probe answers per value, so a transform over a mixed-number
+ # filter can answer with a mixed-number partition key -- and
+ # `in_` infers the bind type from the first element it is handed.
+ # Without this, probe results of `[33, 29.02]` emit
+ # `IN (33, 29)` and prune away the partition holding `29.02`.
+ predicates.append(sqla_col.in_(normalize_mixed_numbers(chunk)))
+ else:
+ predicates.append(
+ db_engine_spec.handle_comparison_filter(
+ sqla_col, mirror_operator(operator), chunk[0]
+ )
+ )
+ return predicates
+
+
+#: Operators whose value is the lower end of a range, and whose upper-end twins.
+#:
+#: Shared with `ExploreMixin._mirror_probe_input`, which rounds a bound *outward*
+#: where the engine resolves it more coarsely than the filter carries -- backward
+#: for a lower bound, forward for an upper one. Which end an operator names is
+#: the only thing separating the two directions in either caller, so the two have
+#: to agree on it rather than each classify for itself.
+LOWER_BOUND_OPERATORS = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+}
+UPPER_BOUND_OPERATORS = {
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+#: What Python type a probe result may have, per generic type of the partition
+#: column it is about to be compared against.
+#:
+#: Only the types a mismatch can actually break a query with are listed. An
+#: unresolvable column type is absent because there is nothing to check
+#: against, and ``MULTI_VALUE`` because this module does not mirror onto an
+#: array partition key at all.
+#: ``numbers.Number`` rather than ``(int, float)``: Postgres answers
+#: ``extract(epoch from ...)`` with a `Decimal`, which is the single commonest
+#: transform this feature has, and an engine is free to answer with any number
+#: type its driver prefers. What the check is for is a *string* where a number
+#: belongs, and every numeric type is equally not that.
+_PROBE_RESULT_TYPES: dict[utils.GenericDataType, tuple[type, ...]] = {
+ utils.GenericDataType.NUMERIC: (numbers.Number,),
+ utils.GenericDataType.BOOLEAN: (bool,),
+ # A day key such as ``to_char(:value, 'YYYYMMDD')`` is legitimately text,
+ # so ``str`` is admitted -- but only for text an engine reads as an
+ # instant. `_reads_as_temporal` is the second half of this entry.
+ utils.GenericDataType.TEMPORAL: (datetime, date, str),
+ # Text, and not a number rendered as one. Not every engine accepts a number
+ # in a text comparison: Postgres refuses ``character varying = integer``,
+ # Trino ``varchar = bigint`` and BigQuery ``STRING = INT64``, all of which
+ # fail the whole chart once the predicate is in the statement. SQLite is
+ # worse -- it raises nothing and compares across storage classes as never
+ # equal, so the mirror drops every row rather than losing pruning, which is
+ # the one outcome this feature may not have. An owner whose partition key
+ # really is text writes the cast into the transform.
+ utils.GenericDataType.STRING: (str,),
+}
+
+
+#: Day/second keys a temporal column accepts as text, beyond ISO 8601.
+#: ``YYYYMMDD`` is the commonest bucketing key this feature exists for, and
+#: Postgres, Trino and BigQuery all read it as a date.
+_TEMPORAL_KEY_FORMATS = ("%Y%m%d", "%Y%m%d%H%M%S", "%Y-%m-%d %H:%M:%S")
Review Comment:
BigQuery only coerces a string literal to `DATE` when it is in the canonical `YYYY-MM-DD` form, so `YYYYMMDD` is not read as a date there (the comment above says it is). A transform such as `format_date('%Y%m%d', :value)` against a `DATE` partition column passes `_reads_as_temporal`, previews as valid, and then emits `partition_col = '20260115'`, which BigQuery rejects once the predicate is in the statement -- so the chart errors rather than just losing pruning. Could the day-key formats be admitted per engine (for example through an engine-spec hook that defaults to the ISO forms), so an engine that cannot read `YYYYMMDD` declines instead of failing the query?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4275997668
##########
superset/commands/dataset/importers/v0.py:
##########
@@ -291,7 +306,91 @@ def run(self) -> None:
.one()
)
dataset["database_id"] = database.id
- SqlaTable.import_from_dict(dataset, sync=self.sync)
+ table = SqlaTable.import_from_dict(dataset, sync=self.sync)
+ if table is not None:
+ imported.append(table)
+
+ self._repair_partition_mappings(imported)
Review Comment:
A legacy overwrite can switch on a stored transform that nothing in the bundle wrote: `clear_unmapped_partition_transforms` only runs here, after `import_from_dict` has already applied the new references. The v1 importer runs it on the stored dataset before the import as well, because an omitted field keeps its stored value.
Concretely, with the flag on, a dataset maps `a -> p` and has a parked `:value + 100` on numeric column `b`. A v0 overwrite that sets `partition_mapped_column: b` and omits the columns then makes `b` the effective column, so this cleanup keeps its transform. A chart filter `b = 5` gets `p = 105` and drops the row `(a=1, b=5, p=1)`.
Could v0 disarm the old mapping's unmapped transforms before the import, the way v1 does?
##########
superset/commands/dataset/importers/v0.py:
##########
@@ -291,7 +306,91 @@ def run(self) -> None:
.one()
)
dataset["database_id"] = database.id
- SqlaTable.import_from_dict(dataset, sync=self.sync)
+ table = SqlaTable.import_from_dict(dataset, sync=self.sync)
+ if table is not None:
+ imported.append(table)
+
+ self._repair_partition_mappings(imported)
+
+ @classmethod
+ def _default_omitted_monotonic_declarations(cls, config: Any) -> None:
+ """
+ Materialize `partition_transform_is_monotonic` wherever a transform is
+ set, anywhere in a v0 config.
+
+ The v1 importer does this on its own raw config, and for the same
+ reason: an overwrite keeps whatever the bundle omits, including a
+ ``True`` left behind by the transform this bundle is replacing. A
+ non-monotonic transform declared monotonic enables range mirrors that
+ exclude rows the filter keeps -- ``abs(:value)`` inheriting a stored
+ ``True`` turns ``n >= -1`` into ``p >= 1`` and misses ``n = 0``.
+
+ Walked rather than addressed directly because a v0 bundle comes in two
+ shapes: a CLI export nests datasets under ``databases[].tables[]``,
+ while a UI export is a bare list of datasets. Only columns that supply
+ a transform are touched, so a re-import that says nothing about a
+ column stays idempotent.
+ """
+ if isinstance(config, list):
+ for entry in config:
+ cls._default_omitted_monotonic_declarations(entry)
+ return
+ if not isinstance(config, dict):
+ return
+ _default_omitted_monotonic_declarations(config.get("columns") or [])
+ for key in (DATABASES_KEY, "tables"):
+ for child in config.get(key) or []:
+ cls._default_omitted_monotonic_declarations(child)
+
+ @staticmethod
+ def _repair_partition_mappings(datasets: list[SqlaTable]) -> None:
+ """
+ Keep the partition filter mapping honest across a v0 import.
+
+ The mapping's columns ride in `SqlaTable.export_fields`, so this path
+ carries them -- but it calls `SqlaTable.import_from_dict` directly and
+ goes through neither `DatasetDAO.update` nor the v1 importer, so
+ neither of the mapping's repairs ran. An older bundle imported with
+ ``--sync columns`` that omits the partition column deletes it and keeps
+ `partition_column` naming it: pruning silently stops, and every later
+ edit of that dataset fails the partition-column-not-found validation,
+ including a description-only PUT, which carries no columns payload and
+ so cannot reach the branch that forgives a stored-only dangle.
+
+ The same pair, in the same order, as `RefreshDatasetCommand` and the
+ v1 importer. Run after the import rather than around it because
+ ``import_from_dict`` is what discovers which datasets are involved.
+ """
+ if not datasets:
+ return
+ # Deferred import: `daos.dataset` pulls in `views.base`, which
+ # circularly imports back into the commands package at app init.
+ from superset.daos.dataset import DatasetDAO # noqa: PLC0415
+
+ db.session.flush()
+ for dataset in datasets:
+ DatasetDAO.clear_dangling_partition_mapping(
+ dataset, {column.column_name for column in dataset.columns}
+ )
+ # The other reference a bundle can leave unsaveable, cleared the way
+ # the v1 importer clears it: an *explicit* self-mapping is blocking
+ # in `UpdateDatasetCommand`, so a bundle setting both references to
+ # the same existing column imported happily and then failed every
+ # later edit, including a description-only PUT. Dropping only the
+ # override leaves the mapping following `main_dttm_col`, which is
+ # the state a bundle omitting the field would have produced.
+ if (
+ dataset.partition_mapped_column
+ and dataset.partition_mapped_column == dataset.partition_column
+ ):
+ logger.warning(
+ "Clearing the partition mapped column on dataset %s during "
+ "import: it names the partition column itself, which no "
+ "later save would accept",
+ dataset.table_name,
+ )
+ dataset.partition_mapped_column = None
+ DatasetDAO.clear_unmapped_partition_transforms(dataset)
Review Comment:
This cleanup keeps any transform on the effective mapped column, but v0 never drops one that the save path would reject, which v1 does through `drop_unusable_partition_transforms`. Importing a legacy bundle with `partition_mapped_column: n` and `n.partition_value_transform: "random() + :value"` succeeds and stores the expression. Every later save then fails validation: a description-only `PUT /api/v1/dataset/<id>` returns 422 on the stored transform, and the mapping never mirrors anything.
Could v0 run the same transform sanitization as v1 on both bundle shapes (CLI `databases[].tables[]` and the UI list)?
##########
superset/models/helpers.py:
##########
@@ -4340,36 +4444,730 @@ def dttm_sql_literal(self, dttm: datetime, col: "TableColumn") -> str:
return f"""'{dttm.strftime("%Y-%m-%d %H:%M:%S.%f")}'"""
- def get_time_filter( # pylint: disable=too-many-arguments # noqa: C901
+ def _mirror_probe_value(self, dttm: datetime, col: Optional["TableColumn"]) -> Any:
+ """
+ ``dttm`` in the mapped column's own stored representation.
+
+ The predicate this mirror stands in for compares the column against
+ `dttm_sql_literal(dttm, col)`, so the transform has to be probed with
+ the same value. On a column stored as an epoch integer, ``T`` is a
+ function of an integer: probing it with a `datetime` either returns
+ something unrelated to the partition keys or raises, and a raise costs
+ the dataset its pruning silently.
+
+ Only the ``python_date_format`` branches of `dttm_sql_literal` are
+ reproduced, because only those produce a *value*. `convert_dttm` yields
+ engine-specific SQL text, which cannot be bound as a parameter; its own
+ divergence from the probe is handled by widening the bounds instead
+ (`_engine_literal_resolution`).
+
+ In `dttm_sql_literal`'s own order, though: it asks ``convert_dttm``
+ first and reaches the format only when the engine answers nothing. A
+ column can carry both -- a TIMESTAMP with a ``%Y%m%d``
+ ``python_date_format``, or an entry in
+ ``python_date_format_by_column_name`` -- and applying the format
+ unconditionally probed a value the real predicate never compares.
+ ``event_time >= '2026-01-01 00:00:00'`` mirrored as
+ ``partition_col >= '20260101'``, and a January 15 row keyed
+ ``2026-01-15`` sorts below that string, so the chart lost a row the
+ filter keeps.
+
+ Where the engine does answer, the `datetime` is returned unchanged and
+ the widening path takes over -- which is exactly what already happens
+ for every temporal column that carries no format at all.
+ """
+ if col is None:
+ return dttm
+
+ if col.type and self.db_engine_spec.convert_dttm(
+ col.type, dttm, db_extra=self.db_extra
+ ):
+ # The format is unreachable in `dttm_sql_literal` for this column,
+ # so reproducing it here would describe a different bound.
+ return dttm
+
+ tf = col.python_date_format
+ if not tf and self.db_extra:
+ tf = self.db_extra.get("python_date_format_by_column_name", {}).get(
+ col.column_name
+ )
+ if not tf:
+ return dttm
+
+ if tf in EPOCH_FORMATS:
+ dttm_tz_aware = dttm
+ if dttm_tz_aware.tzinfo is None:
+ dttm_tz_aware = dttm_tz_aware.replace(tzinfo=timezone.utc)
+ return int(dttm_tz_aware.timestamp()) * EPOCH_FORMATS[tf]
+ return dttm.strftime(tf)
+
+ def _engine_literal_resolution(
+ self, dttm: datetime, col: Optional["TableColumn"]
+ ) -> LiteralResolution:
+ """
+ How much of ``dttm`` survives into this engine's literal for ``col``.
+
+ The real predicate compares `dttm_sql_literal(dttm, col)`, so whatever
+ that literal throws away is a bound the engine never sees. A mirror
+ derived from the full precision then describes a *narrower* range than
+ the predicate it stands in for -- and narrower means it drops rows the
+ filter keeps.
+
+ Two things get thrown away in practice:
+
+ - the sub-second part. SQLite renders a timestamp with
+ ``timespec="seconds"``.
+ - the time of day entirely. Every engine spec with a ``types.Date``
+ branch renders ``dttm.date().isoformat()``, so Presto, Trino,
+ BigQuery and some two dozen others answer `DATE '2026-01-01'` for a
+ bound of 10:00 -- and `T(DATE '2026-01-01')` is below the mirror's
+ own lower bound, so the whole first day is dropped.
+
+ Detected rather than enumerated per engine, because the branch depends
+ on the column's type as well as the spec: instants differing only in the
+ part under test render as the same text exactly when the engine has
+ thrown that part away.
+
+ The day test uses two fixed times of day rather than ``dttm`` and one
+ alternative, so a bound that happens to sit on the hour the alternative
+ uses cannot read as "no time at all". Neither probe sits at midnight on
+ purpose: SQLite renders a DATE column at exactly midnight as a bare
+ date, so a midnight probe would differ from its alternative for a
+ reason that has nothing to do with resolution.
+
+ Likewise both sub-second probes carry a non-zero remainder. Comparing
+ against ``dttm`` truncated to the second looks like the obvious test and
+ is wrong for the same formatting-boundary reason.
+
+ A non-temporal column has no answer here, and asking anyway gets a wrong
+ one. SQLite's ``convert_dttm`` renders for ``types.String`` as well as
+ for the date types, so a ``VARCHAR`` mapped column reads as
+ second-resolution -- and a filter value that happens to *look* like an
+ instant then has its bound rounded as though the engine had truncated
+ it. On a VARCHAR ``code`` mapped onto a VARCHAR ``p`` by ``:value``,
+ ``code < '2026-07-06T10:08:11.500000'`` was mirrored as
+ ``p <= '2026-07-06 10:08:12.000000'``; a space sorts before ``T``, so a
+ row holding ``2026-07-06T09:00:00`` fell outside the mirror while
+ matching the filter.
+
+ The guard lives here rather than in each caller so this and
+ `_column_literal_resolution` cannot disagree about which column is
+ coarse -- which is the same reason that helper delegates to this one.
+
+ "Temporal" is the column's generic type, not just its ``is_dttm`` flag.
+ `get_time_filter` renders a bound through ``convert_dttm`` for any
+ ``DATE`` column, flagged or not, so a ``DATE`` column left unflagged
+ still compares a bare day -- and skipping the resolution check there
+ would hand the probe 10:00 for a bound the engine reads as midnight.
+ """
+ if col is None or not col.type or col.type_generic != GenericDataType.TEMPORAL:
+ return LiteralResolution.FULL
+
+ def render(moment: datetime) -> Optional[str]:
+ return self.db_engine_spec.convert_dttm(
+ col.type, moment, db_extra=self.db_extra
+ )
+
+ try:
+ early = render(dttm.replace(hour=1, minute=2, second=3, microsecond=444444))
+ late = render(
+ dttm.replace(hour=22, minute=33, second=44, microsecond=555555)
+ )
+ if early is not None and early == late:
+ return LiteralResolution.DAY
+
+ # Flooring to the second is a no-op on a bound that has no
+ # sub-second part, so there is nothing to detect.
+ if not dttm.microsecond:
+ return LiteralResolution.FULL
+
+ first = render(dttm.replace(microsecond=111111))
+ second = render(dttm.replace(microsecond=222222))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return LiteralResolution.FULL
+
+ if first is not None and first == second:
+ return LiteralResolution.SECOND
+ return LiteralResolution.FULL
+
+ def _round_bounds_outward(
self,
- time_col: "TableColumn",
+ start_dttm: Optional[datetime],
+ end_dttm: Optional[datetime],
+ col: Optional["TableColumn"],
+ ) -> tuple[Optional[datetime], Optional[datetime]]:
+ """
+ The bounds widened to whatever the engine's literal actually resolves to.
+
+ Rounding outward is never narrower than the predicate being mirrored,
+ which is the only property the mirror has to hold.
+ """
+ resolutions = {
+ self._engine_literal_resolution(bound, col)
+ for bound in (start_dttm, end_dttm)
+ if bound is not None
+ }
+
+ if LiteralResolution.DAY in resolutions:
+ # The engine compares a bare date, so the real predicate's lower
+ # bound is the start of that day and its upper bound admits the
+ # whole of the day before. Anything finer excludes rows it keeps.
+ if start_dttm is not None:
+ start_dttm = start_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ )
+ if end_dttm is not None and end_dttm != end_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ ):
+ end_dttm = end_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ ) + timedelta(days=1)
+ elif LiteralResolution.SECOND in resolutions:
+ if start_dttm is not None:
+ start_dttm = start_dttm.replace(microsecond=0)
+ if end_dttm is not None and end_dttm.microsecond:
+ end_dttm = end_dttm.replace(microsecond=0) + timedelta(seconds=1)
+
+ return start_dttm, end_dttm
+
+ def _literal_is_coarser_than(
+ self, dttm: datetime, col: Optional["TableColumn"]
+ ) -> bool:
+ """
+ Whether the engine's literal for ``dttm`` throws away part of it.
+
+ Unlike a range, an equality cannot be widened outward, so the only safe
+ answer when the engine compares less than the full value is to decline
+ the mirror.
+ """
+ resolution = self._engine_literal_resolution(dttm, col)
+ if resolution is LiteralResolution.DAY:
+ return dttm != dttm.replace(hour=0, minute=0, second=0, microsecond=0)
+ if resolution is LiteralResolution.SECOND:
+ return bool(dttm.microsecond)
+ return False
+
+ def _column_literal_resolution(
+ self, col: Optional["TableColumn"]
+ ) -> LiteralResolution:
+ """
+ How much of *any* value this engine compares on ``col``.
+
+ `_engine_literal_resolution` answers about a particular instant, which
+ is what a mirror derived from one needs. Two callers have no instant to
+ ask about -- the summary the Explore glyph reads, and a filter value
+ `_instant_from_filter_value` cannot read as an instant at all -- and
+ both need the column's own answer. Through one helper so that the glyph
+ and the query path cannot disagree about which column is coarse, which
+ is the same reason `mirrorable_operators` is computed once.
+
+ A non-temporal column has no answer, and asking anyway gets a wrong one:
+ SQLite's ``convert_dttm`` renders for ``types.String`` as well as for the
+ date types, so a reference instant makes a ``VARCHAR`` mapped column look
+ second-resolution -- and ``country = 'US'``, the text half of this
+ feature, reads as a value the engine compares coarsely.
+
+ That guard is `_engine_literal_resolution`'s, not this function's. It
+ used to be here, on the belief that the per-instant callers never met
+ the case because they arrive only with a value that parsed as an
+ instant -- which is untrue of a text column holding ISO-shaped text,
+ where the value parses and the column is still not temporal.
+ """
+ return self._engine_literal_resolution(_RESOLUTION_REFERENCE_INSTANT, col)
+
+ def _round_bound_outward(
+ self,
+ instant: datetime,
+ col: Optional["TableColumn"],
+ *,
+ is_upper: bool,
+ ) -> datetime:
+ """
+ One bound widened to whatever the engine resolves ``col`` to.
+
+ `_round_bounds_outward` answers for a since/until pair, because a time
+ range is the shape it was written for. A single comparison is one end of
+ such a pair with the other end absent, and the widening is per-end
+ already -- a lower bound moves back, an upper bound forward.
+
+ Narrowing the return type is the other half of the point: a bound handed
+ in non-`None` comes back non-`None`, and saying so here saves every
+ caller from re-establishing it.
+ """
+ start_dttm, end_dttm = self._round_bounds_outward(
+ None if is_upper else instant,
+ instant if is_upper else None,
+ col,
+ )
+ rounded = end_dttm if is_upper else start_dttm
+ return rounded if rounded is not None else instant
+
+ def _in_column_number_type(self, value: Any, col: Optional["TableColumn"]) -> Any:
+ """
+ A numeric ``value`` in the number type the mapped column stores.
+
+ The engine compares a number against the column in the column's own
+ domain, so ``n = '1.0'`` on an integer ``n`` matches the row holding
+ ``1``. `filter_values_handler` hands over ``1.0``, though, and a
+ transform whose output depends on the representation --
+ ``CAST(:value AS TEXT)`` answers ``'1.0'`` where the row's key is
+ ``'1'`` -- then mirrors to a partition value no matching row holds.
+ Probing at the value the column would hold keeps ``T(col) = T(v)``.
+
+ Integer columns only. A non-integral value on an integer column is
+ returned unchanged -- it matches no row, so its mirror cannot drop one.
+
+ Nothing is converted for an approximate or exact decimal column, even
+ though ``1`` and ``1.0`` are the same number to a ``REAL``. What the
+ transform sees is the *literal*, and how an engine renders one is not
+ something the engine spec exposes: on PostgreSQL ``CAST(1.0 AS TEXT)``
+ is ``'1.0'`` while the ``REAL`` column holding that value renders as
+ ``'1'``, so coercing the value to ``float`` mirrored onto a partition
+ key no matching row holds -- the same failure this helper exists to
+ stop, in the other direction. A ``DECIMAL`` column says it louder,
+ since its text also depends on a scale the spec does not carry. For
+ both, the rendering stays the owner's assumption, like
+ ``p = T(mapped_col)`` itself.
+ """
+ if (
+ col is None
+ or not col.type
+ or isinstance(value, bool)
+ or not isinstance(value, (int, float, Decimal))
+ ):
+ return value
+ try:
+ column_spec = self.db_engine_spec.get_column_spec(
+ col.type, db_extra=self.db_extra
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return value
+ if column_spec is None:
+ return value
+ sqla_type = column_spec.sqla_type
+ type_class = sqla_type if isinstance(sqla_type, type) else type(sqla_type)
+ if issubclass(type_class, sa.Integer):
+ if isinstance(value, int):
+ return value
+ try:
+ return int(value) if value == int(value) else value
+ except (OverflowError, ValueError):
+ # Infinity and NaN have no integer, and match no integer row.
+ return value
+ return value
+
+ def _mirror_probe_input(
+ self,
+ operator: utils.FilterOperator,
+ value: Any,
+ col: Optional["TableColumn"],
+ ) -> Any:
+ """
+ ``value`` in the representation the mirror may probe the transform at.
+
+ A simple filter on a temporal column carries a *string*.
+ `filter_values_handler` rewrites only an all-digit value, which it reads
+ as epoch milliseconds, so ``'2026-07-06 10:08:11'`` reaches here exactly
+ as the chart author typed it and is bound as text. The engine compares
+ that text against the column under its own cast, and on a ``DATE``
+ column the cast drops the time of day: the filter keeps the whole of
+ 2026-07-06 while a mirror probed at 10:08:11 keeps one instant of it,
+ which is narrower than the predicate it stands in for.
+
+ So the text is read back into the instant it denotes -- the only way
+ `_engine_literal_resolution`, which answers about a `datetime`, reaches
+ a filter value at all -- and where the engine compares less of that
+ instant than the filter carries, what to do about it is a property of
+ the *operator*:
+
+ * a bound rounds outward, through the helper the range collector uses.
+ Reading one extra bucket at the edge is the trade this feature makes
+ everywhere else too -- see `mirror_operator` -- and the original
+ predicate is still in the query to exclude the rows that bucket adds.
+ * an equality, or one member of an ``IN`` list, has nowhere to widen to.
+ These entries are ``AND``-ed onto the query, so "or the day either
+ side" is not something this sink can express, and the request is
+ declined with `_UNMIRRORABLE`. The query is then correct and unpruned,
+ which is the one failure mode this feature is allowed.
+
+ An instant carrying a UTC offset is declined for every operator, a
+ bound included. Rounding one outward would first have to place it in the
+ frame the partition column was written in, and guessing that frame is
+ how a mirror ends up a whole offset narrower than the filter -- see the
+ load-bearing assumption in
+ `superset.connectors.sqla.partition_mapping`.
+
+ A *string* `_instant_from_filter_value` cannot read at all is declined on
+ the same terms, and for the same reason one more step back: there is no
+ instant to round. ``'07/06/2026 10:08:11'`` is not ISO 8601, so the
+ parser leaves it alone -- and Postgres casts that same text to a DATE and
+ keeps the whole of July 6 while the probe, handed the string verbatim,
+ evaluates the transform at 10:08:11 and asks for a partition key no row
+ holds. That is exactly the narrowing the ISO-only parser was written to
+ prevent, reached through a value it declines to read, so the decline has
+ to travel with it. Which costs a non-ISO *date* its pruning too, because
+ telling July 6 from June 7 is the guess that started this.
+
+ Only a string. `_as_probe_input` has already run, so the engine SQL
+ `filter_values_handler` returns for an epoch-millisecond bound arrives
+ here as a `RawProbeValue` rather than text -- and that literal was
+ rendered by the engine at the engine's own resolution, so it is the one
+ thing on this path with nothing left to resolve.
+
+ Where the engine compares the whole instant, a string is returned
+ exactly as it arrived -- down to the type the probe binds and the cache
+ key it lands on, because every query that was already correct has to
+ stay byte-for-byte correct. A `datetime` is still converted, which it
+ has always needed: on a column stored as an epoch integer the transform
+ is a function of an integer, and a `datetime` is not the value the real
+ predicate compares.
+ """
+ value = self._in_column_number_type(value, col)
+ parsed = _instant_from_filter_value(value)
+ if parsed is None:
+ if (
+ isinstance(value, str)
+ and self._column_literal_resolution(col) is not LiteralResolution.FULL
+ ):
+ return _UNMIRRORABLE
+ return value
+
+ # Ahead of the full-resolution return: a transform such as
+ # `CAST(:value AS TIMESTAMP)` drops the offset, so even an engine that
+ # compares the whole instant would probe it in the wrong frame. Its own
+ # reason, because mapping a column the engine compares in full -- the
+ # advice the resolution decline carries -- does not help here.
+ if parsed.tzinfo is not None:
+ return _UNMIRRORABLE_OFFSET
+
+ if self._engine_literal_resolution(parsed, col) is LiteralResolution.FULL:
+ return (
+ self._mirror_probe_value(parsed, col)
+ if isinstance(value, datetime)
+ else value
+ )
+
+ if operator in LOWER_BOUND_OPERATORS:
+ instant = self._round_bound_outward(parsed, col, is_upper=False)
+ elif operator in UPPER_BOUND_OPERATORS:
+ instant = self._round_bound_outward(parsed, col, is_upper=True)
+ elif self._literal_is_coarser_than(parsed, col):
+ return _UNMIRRORABLE
+ else:
+ instant = parsed
+
+ if instant == parsed and not isinstance(value, datetime):
+ return value
+ return self._mirror_probe_value(instant, col)
+
+ def _collect_partition_mirror_range(
+ self,
+ mapping: Optional["PartitionMapping"],
+ sink: list[tuple[utils.FilterOperator, Any]],
+ column_name: str,
start_dttm: Optional[sa.DateTime],
end_dttm: Optional[sa.DateTime],
- time_grain: Optional[str] = None,
- label: Optional[str] = "__time",
- template_processor: Optional[BaseTemplateProcessor] = None,
- ) -> Optional[ColumnElement]:
- col = (
- time_col.get_timestamp_expression(
- time_grain=time_grain,
- label=label,
- template_processor=template_processor,
+ widen_bounds_by: Optional[relativedelta] = None,
+ ) -> None:
+ """
+ Record a time range for mirroring onto the partition column.
+
+ The bounds are adjusted first, by the same helper `get_time_filter` uses:
+ the mirrored predicate has to describe the same instants as the
+ timestamp predicate it stands in for, or the pruning is wrong by exactly
+ the dataset's timezone offset -- silently.
+
+ Either bound may be `None` for an open-ended range, in which case only
+ the bound that exists is mirrored.
+
+ Both bounds are recorded with the operators the real predicate uses,
+ `>=` and `<`. Relaxing the strict one is `mirror_operator`'s job, at the
+ single point where an operator becomes SQL -- which is also the point
+ the preview endpoint goes through.
+
+ `widen_bounds_by` is one grain bucket width, passed when the filter this
+ stands in for compares a *truncated* column. The real predicate then
+ keeps rows the raw bounds exclude, and widening both ends by one bucket
+ is the smallest range guaranteed to contain all of them -- see the "Time
+ grains" section of `superset.connectors.sqla.partition_mapping`.
+
+ A widened range can also be wide enough to fail `_bounds_are_ordered`
+ against a tighter filter on the same column. That fails open -- no
+ mirroring, no pruning, no dropped rows.
+ """
+ if mapping is None or column_name != mapping.mapped_column:
+ return
+ if not mapping.mirrors(utils.FilterOperator.TEMPORAL_RANGE):
+ return
+
+ # Resolve the column so the offset adjustment sees the same type
+ # `get_time_filter` does -- an offset the column's type cannot represent
+ # is dropped, and the mirrored bounds have to agree with the originals.
+ mapped_col = next(
+ (col for col in self.columns if col.column_name == column_name), None
+ )
+ start_dttm, end_dttm = self.adjust_time_bounds(start_dttm, end_dttm, mapped_col)
+
+ # Adjust first, then widen. `adjust_time_bounds` moves the naive UI
+ # bounds into the frame the column is *stored* in, and the grain
+ # truncation in the real predicate happens in that same frame, so the
+ # bucket width has to be added there too. The two commute for the
+ # hour-offset branch but not for the `ZoneInfo` one, where widening
+ # across a DST boundary first lands an hour out.
+ if widen_bounds_by is not None:
+ if start_dttm is not None:
+ start_dttm -= widen_bounds_by
+ if end_dttm is not None:
+ end_dttm += widen_bounds_by
+
+ # Then round outward, to whatever the engine's literal resolves to.
+ start_dttm, end_dttm = self._round_bounds_outward(
+ start_dttm, end_dttm, mapped_col
+ )
+
+ # Converted last. The widening and rounding above are `datetime`
+ # arithmetic, and the stored representation may be an integer.
+ if start_dttm is not None:
+ sink.append(
+ (
+ utils.FilterOperator.GREATER_THAN_OR_EQUALS,
+ self._mirror_probe_value(start_dttm, mapped_col),
+ )
)
- if time_grain
- else self.convert_tbl_column_to_sqla_col(
- time_col, label=label, template_processor=template_processor
+ if end_dttm is not None:
+ sink.append(
+ (
+ utils.FilterOperator.LESS_THAN,
+ self._mirror_probe_value(end_dttm, mapped_col),
+ )
)
+
+ def _array_mirror_probe_value(
+ self,
+ value: Any,
+ operator: utils.FilterOperator,
+ element_type: Optional[utils.GenericDataType],
+ db_engine_spec: builtins.type["BaseEngineSpec"],
+ ) -> Any:
+ """
+ The array literal the real predicate compares, ready to probe with.
+
+ On an array column the predicate is not built from `eq` at all: the
+ branch below reads the raw `val`, parses the pasted literal into
+ elements, coerces them to the array's element type and asks the engine
+ spec for its own array syntax. Mirroring `eq` would probe the transform
+ at a value the query never compares, so this reproduces that chain
+ instead -- the mirror then probes exactly what the predicate holds.
+
+ The result is SQL text rather than a value, because an array literal is
+ an expression; `RawProbeValue` carries it and `build_probe_sql`
+ substitutes rather than binds. Returns `None` when the engine spec
+ claims multi-value columns without implementing a literal for them, or
+ when an element has no literal the dialect can render -- a nested array
+ such as ``[[1, 2]]`` -- which costs the query its pruning and nothing
+ else.
+ """
+
+ def literal(entry: Any) -> Any:
+ return raw_probe_value(
+ self.database,
+ db_engine_spec.array_literal(
+ coerce_array_values(parse_array_literal(entry), element_type)
+ ),
+ )
+
+ try:
+ if operator in {utils.FilterOperator.IN, utils.FilterOperator.NOT_IN}:
+ candidates = (
+ list(value) if isinstance(value, (list, tuple)) else [value]
+ )
+ return tuple(literal(candidate) for candidate in candidates)
+ return literal(value)
+ except (NotImplementedError, sa.exc.CompileError):
+ return None
+
+ def _as_probe_input(self, value: Any) -> Any:
+ """
+ ``value`` in a form `build_probe_sql` can put into the probe.
+
+ `filter_values_handler` returns engine SQL rather than a value for an
+ epoch-millisecond bound on a temporal column -- what drill-to-detail and
+ cross-filters send -- and SQL cannot be the value of a bind parameter.
+ Carrying it as text lets the probe substitute it instead, exactly as the
+ preview path's own coercion does and as an array literal needs.
+
+ Text rather than the expression itself also matters for caching: the
+ probe cache keys on `repr` of each value, and a `ColumnClause`'s default
+ `repr` carries its memory address, so every request would miss.
+
+ Returns `_UNRENDERABLE` when the engine cannot render the literal, which
+ costs the query its pruning and nothing else -- the same thing the probe
+ itself does on failure.
+ """
+
+ def rendered(entry: Any) -> Any:
+ if isinstance(entry, ColumnElement):
+ return raw_probe_value(self.database, entry)
+ return entry
+
+ try:
+ if isinstance(value, (list, tuple)):
+ return type(value)(rendered(item) for item in value)
+ return rendered(value)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ logger.warning(
+ "Could not render a filter value for the partition mirror; "
+ "queries will not prune",
+ exc_info=True,
+ )
+ return _UNRENDERABLE
+
+ def _collect_partition_mirror_filter(
+ self,
+ mapping: Optional["PartitionMapping"],
+ sink: list[tuple[utils.FilterOperator, Any]],
+ column_name: str,
+ operator: utils.FilterOperator,
+ value: Any,
+ ) -> None:
+ """
+ Record a structured filter for mirroring onto the partition column.
+
+ Only operators the mapping declares safe are recorded; see the operator
+ matrix in `superset.connectors.sqla.partition_mapping`.
+
+ The value itself is resolved by `mirror_probe_request`, which the preview
+ endpoint calls too so that the two cannot answer differently.
+ """
+ if mapping is None or column_name != mapping.mapped_column:
+ return
+ if not mapping.mirrors(operator):
+ return
+
+ mapped_col = next(
+ (col for col in self.columns if col.column_name == column_name), None
)
+ probe_value = self.mirror_probe_request(operator, value, mapped_col)
+ if is_unmirrorable(probe_value):
+ return
+ sink.append((operator, probe_value))
+
+ def mirror_probe_request(
+ self,
+ operator: utils.FilterOperator,
+ value: Any,
+ col: Optional["TableColumn"],
+ ) -> Any:
+ """
+ ``value`` as the mirror may probe the transform at, or an `Unmirrorable`.
+
+ The whole of what has to happen to a filter value before it can be
+ probed, in one place because two callers need it: the chart query path,
+ and the dataset editor's preview endpoint. The preview used to coerce the
+ value and then probe it directly, so it reported a mirror for a request
+ the chart path declines -- an owner was shown a valid predicate on a
+ `DATE` mapped column whose equality filters never mirror at all.
+
+ Routing per *value* rather than per Python type is what makes a bound
+ widen and an equality decline whichever shape the value arrived in -- a
+ `datetime` from drill-to-detail, or the raw string a simple filter binds.
+ """
+ # First, and ahead of anything that reads the value as an instant: a
+ # value `filter_values_handler` already turned into engine SQL is
+ # carried as text from here on, and the probe has to receive exactly
+ # that literal -- it is what the real predicate compares, so there is
+ # nothing left to resolve about it. Idempotent, so a caller that has
+ # already rendered its own values may still come through here.
+ value = self._as_probe_input(value)
+ if value is _UNRENDERABLE:
+ return UNMIRRORABLE
+
+ if operator == utils.FilterOperator.IN:
+ if not isinstance(value, (list, tuple)) or not value:
+ return UNMIRRORABLE
+ if any(item is None for item in value):
Review Comment:
This guard declines a whole `IN` list when one member is `None`, but nothing in the mirroring tests drives it: the NULL tests cover a NULL partition value, not a NULL member of the filter's own list. If it regressed to dropping the `None` and mirroring the rest, `country IN ['US', None]` with `coalesce(lower(:value), 'unknown')` would emit `region_key IN ('us') OR region_key IS NULL` and exclude a row with `country IS NULL, region_key = 'unknown'` that the original keeps.
Could `get_sqla_query` get a test with that filter on the existing mapped-table fixture, asserting the probe is not called and no `region_key` predicate is emitted?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4254203475
##########
docs/static/resources/openapi.json:
##########
@@ -4253,6 +4411,7 @@
"type": "object"
},
"DashboardRestApi.get_list": {
+ "additionalProperties": false,
Review Comment:
This regeneration adds `"additionalProperties": false` to ~380 schemas and turns nullable `allOf` into `anyOf`; CI's `superset update-api-docs` emits neither, so `check-openapi-spec-drift` and `test_dashboard_list_uses_generated_response_schema` fail on all 4 DB legs. No suggestion: generated file.
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,3041 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: The opening and closing delimiters of each kind of Jinja block. The probe
+#: would render these in a different context at a different time from the chart
+#: query, so a transform holding one is rejected at save time.
+JINJA_BLOCK_DELIMITERS = (("{{", "}}"), ("{%", "%}"), ("{#", "#}"))
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: A PostgreSQL Unicode-escaped identifier, ``U&"..."``.
+#:
+#: The second construct that breaks the premise above, and in the same way:
+#: ``U&"\\0071uery_to_xml"(...)`` parses as an anonymous function whose name is
+#: the *literal* ``\\0071uery_to_xml``, so the function denylist is matching a
+#: name the engine never sees -- PostgreSQL decodes the escape and runs
+#: ``query_to_xml``, handing a dataset owner rows from outside their RLS scope
+#: through the preview's ``emitted_predicate``.
+#:
+#: Normalizing the escapes and re-checking would be the other repair, and is
+#: worse: it means reimplementing one engine's identifier decoding well enough
+#: to be a security boundary. Refusing the construct is exact, and costs
+#: nothing real -- a transform is a scalar function of ``:value``, and there is
+#: no reason to name a function or column through an escape sequence.
+#:
+#: Refused on every engine, like the executable comment, so a transform stored
+#: on SQLite cannot detonate when the dataset is re-pointed at PostgreSQL. The
+#: ``&`` may be separated from the ``U`` by nothing at all, but whitespace or a
+#: comment between the prefix and the string is not accepted by PostgreSQL
+#: either, so the strict form is the whole surface.
+#:
+#: Matched in raw text, so the prefix is refused inside a string literal too.
+#: That is the same trade the executable comment makes and has the same
+#: justification: a gate whose contract is to fire *before* the parse cannot
+#: ask the parse whether the text was quoted. ``concat(:value, 'u&"x"')`` is
+#: refused, which costs an owner nothing anyone writes.
+UNICODE_ESCAPED_IDENTIFIER_RE = re.compile(r'\bU&"', re.IGNORECASE)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+class Unmirrorable:
+ """
+ A filter no mirror can stand in for, and why.
+
+ Returned by `ExploreMixin.mirror_probe_request` for a value the engine
+ compares more coarsely than the filter carries, one it cannot render as a
+ literal, one in a time frame the transform would discard, or an ``IN`` list
+ with a member of any of those kinds. An object rather than `None`, because
+ `None` is a filter value in its own right.
+
+ The reason rides along because the preview has to explain the decline to
+ the owner, and the two declines want different advice: "the engine compares
+ less of this value than you typed, so map a column it compares in full" is
+ sound guidance for a `DATE` column and actively misleading for an
+ offset-bearing bound on a `TIMESTAMP` one, which already is such a column.
+ Carried rather than re-derived so the preview's explanation cannot come
+ apart from the chart path's decision.
+
+ Lives here rather than beside that method so the preview can read it too:
+ `superset.models.helpers` imports this module, so these can only cross the
+ boundary in this direction. Both callers recognise the same instances -- a
+ preview that answered "valid" for a request the chart path declines is the
+ drift this is here to prevent.
+ """
+
+ __slots__ = ("reason",)
+
+ def __init__(self, reason: str) -> None:
+ self.reason = reason
+
+ def __repr__(self) -> str:
+ return f"<Unmirrorable {self.reason}>"
+
+
+#: The ordinary decline: whatever the mirror cannot be built from, with the
+#: engine's own comparison resolution as the reason an owner can act on.
+UNMIRRORABLE = Unmirrorable("resolution")
+
+#: A value carrying a UTC offset, declined whatever the column's resolution.
+#: A transform such as ``CAST(:value AS TIMESTAMP)`` drops the offset, so even
+#: an engine that compares the whole instant would be probed in the wrong
+#: frame -- which is not something mapping a different column fixes.
+UNMIRRORABLE_OFFSET = Unmirrorable("offset")
+
+
+def is_unmirrorable(value: Any) -> bool:
+ """Whether `mirror_probe_request` declined this request."""
+ return isinstance(value, Unmirrorable)
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+#: Declared types whose comparison ignores trailing blanks.
+#:
+#: The fixed-width character types, which the SQL standard has compare as
+#: though both sides were padded to the same length -- so ``'US'`` and
+#: ``'US '`` are equal in a ``CHARACTER(3)``, while ``lower()`` of the two is
+#: not. Spelled out rather than matched by prefix because the variable-width
+#: names start with the same letters: ``VARCHAR`` and ``CHARACTER VARYING``
+#: compare the blanks and must not land here.
+PADDED_CHARACTER_TYPES = frozenset(
+ {
+ "CHAR",
+ "NCHAR",
+ # PostgreSQL's own name for ``CHARACTER``, which is what reflection
+ # reports for a ``CHAR(n)`` column there.
+ "BPCHAR",
+ "CHARACTER",
+ "NATIONAL CHAR",
+ "NATIONAL CHARACTER",
+ }
+)
+
+
+def _is_padded_character_type(column: TableColumn) -> bool:
+ """
+ Whether ``column``'s declared type compares without its trailing blanks.
+
+ Read off the declared type rather than the engine spec's resolved one: the
+ specs map ``CHAR`` and ``VARCHAR`` onto the same `sqlalchemy.String`, so
+ the distinction this needs is gone by then. The length suffix is dropped
+ and the name matched against `PADDED_CHARACTER_TYPES`, so an unfamiliar
+ spelling answers ``False`` and the engine-level flag decides as before --
+ this gate adds a decline rather than lifting one. A column with no
+ declared type has nothing to read, and answers the same way.
+ """
+ if not isinstance(column.type, str):
+ return False
+ native = re.sub(r"\s+", " ", column.type.strip().upper())
+ return native.split("(")[0].strip() in PADDED_CHARACTER_TYPES
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ Padding is asked about per column, because it is a property of the *type*
+ rather than of the engine. ``binary_string_comparison`` speaks for an
+ engine's default text comparison, and on PostgreSQL -- which declares it
+ -- a ``CHAR(2)`` still matches a filter for ``'US '`` against a stored
+ ``'US'``, because the standard says a padded character type compares
+ without its trailing blanks. The mirror ``region_key = lower('US ')`` then
+ excludes the row. So a fixed-width character type declines whatever the
+ engine says, and an engine that ignores trailing blanks on its *variable*
+ types says so by not declaring the flag at all (see `RedshiftEngineSpec`).
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ # Ahead of the generic-type question, which a padded type can lose: the
+ # specs map ``CHARACTER`` onto no generic type at all on some engines, and
+ # a fixed-width character type is a string whether or not Superset can say
+ # so from the name.
+ if _is_padded_character_type(column):
+ return False
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_unicode_escaped_identifier(transform: str | None) -> bool:
+ """Whether the transform names something through a ``U&"..."`` escape.
+
+ See `UNICODE_ESCAPED_IDENTIFIER_RE`. Answered on raw text for the same
+ reason as the comment above: the parse reports a name the engine does not
+ use, which is exactly what makes the denylist blind to it.
+ """
+ return (
+ bool(transform)
+ and UNICODE_ESCAPED_IDENTIFIER_RE.search(transform or "") is not None
+ )
+
+
+#: Sequence pseudo-columns, which advance a sequence when they are *read*.
+#:
+#: ``orders_seq.NEXTVAL`` parses as a qualified column reference, not a
+#: function call, so neither `SQLStatement.is_mutating` -- which walks function
+#: names -- nor the function denylist can see it. The probe would then run
+#: ``SELECT orders_seq.NEXTVAL + 1 FROM DUAL`` and advance the sequence, again
+#: on every cache expiry, for a dataset editor holding neither SQL Lab nor a
+#: DML grant. Reading one is a write however the parser classifies it.
+#:
+#: The function spelling (``nextval('s')`` on PostgreSQL) is a different shape
+#: and is caught as a function; this is only about the suffix form.
+SEQUENCE_PSEUDO_COLUMNS = frozenset({"nextval", "currval"})
+
+
+def references_sequence_pseudo_column(statement: SQLStatement) -> bool:
+ """Whether the statement reads a sequence pseudo-column.
+
+ See `SEQUENCE_PSEUDO_COLUMNS`. Answered on the parse rather than on raw
+ text, because the name has to be in column position for this to be the
+ construct: a column or alias merely *called* ``nextval`` is not it.
+ """
+ return bool(statement.get_column_names() & SEQUENCE_PSEUDO_COLUMNS)
Review Comment:
The function spellings still pass: MySQL/MariaDB `NEXTVAL(s)`/`SETVAL(s, 1)`, DuckDB `nextval('s')` and MSSQL `NEXT VALUE FOR s` all get `None` from `stored_expression_error`, because `is_mutating` walks function names only on PostgreSQL.
```suggestion
return bool(
statement.get_column_names() & SEQUENCE_PSEUDO_COLUMNS
or statement.get_disallowed_functions({"nextval", "setval", "next_value_for"})
)
```
##########
superset/config.py:
##########
@@ -2569,6 +2601,29 @@ def engine_context_manager( # pylint: disable=unused-argument
"getMacro",
"getSetting",
},
+ # Oracle functions that run a query handed to them as text. Same blind spot
+ # as PostgreSQL's XML and full-text families above: the statement they
+ # execute is a string, so the expression has no FROM clause and no
+ # sub-query of its own for a table-reference gate to see, and the rows come
+ # back without the dataset grants or row-level security the caller is
+ # subject to.
+ #
+ # Named bare rather than package-qualified: `DBMS_XMLGEN.GETXML(...)`
+ # parses as an anonymous function called `GETXML`, so the package prefix
+ # never reaches the matcher. `getclobval` and `extract` are deliberately
+ # absent -- they read an XMLType the caller already has rather than
+ # building one from a query.
+ "oracle": {
+ "getxml",
+ "getxmltype",
+ "newcontext",
+ "newcontextfromhierarchy",
+ # Reads a table by path string, e.g.
+ # ``DBURITYPE('/HR/EMPLOYEES/ROW[ID=1]/SALARY').getclob()``, which is
+ # the same blind spot as the above with no function argument to
+ # inspect -- and ``PUBLIC`` holds execute on it by default.
+ "dburitype",
Review Comment:
`URIFACTORY.GETURI('/oradb/HR/EMPLOYEES/ROW[ID=1]/SALARY').getclob()` builds the same DBURIType through the factory and passes the gate, as do the sibling types `XDBURITYPE` and `HTTPURITYPE`.
```suggestion
"dburitype",
# The same reader through its factory, and its sibling URI types.
"geturi",
"xdburitype",
"httpuritype",
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4251048976
##########
superset/daos/dataset.py:
##########
@@ -476,10 +606,104 @@ def _validate_column_date_formats(
"python_date_format is an invalid date/timestamp format."
)
+ @staticmethod
+ def clear_unmapped_partition_transforms(model: SqlaTable) -> None:
+ """
+ Drop the value transform from every column the mapping does not mirror.
+
+ A mapping has exactly one mirrored column, so at most one column may
+ carry a transform. A transform parked on any other column is invisible
+ -- no row but the mapped one renders one -- yet it is still stored, and
+ it goes live the moment the mapped column resolves back to it. Clearing
+ an override is enough to do that: a null `partition_mapped_column` means
+ "follow `main_dttm_col`", so dropping a mapping would otherwise activate
+ whatever the default datetime column happened to be holding, turning a
+ request to remove a mapping into a request to add a different one.
+
+ Enforced here rather than in the editor alone because the editor is only
+ one writer: a PUT, an `override_columns=true` metadata sync and an
+ import all reach the columns directly. The same argument
+ `clear_dangling_partition_mapping` makes about dangling columns.
+
+ `DatasetDAO.update` calls this twice, before and after it applies the
+ request, and the reason is here rather than only at the call site: this
+ reads the mapping as it stands, so a single call can only enforce the
+ invariant against one of the two resolutions a mapping change has.
+
+ Gated on the feature flag, unlike its sibling, because this discards
+ stored configuration rather than repairing a broken reference. With the
+ flag off nothing mirrors, so there is no armed mapping to disarm and
+ clearing would be pure loss.
+ """
+ if not feature_flag_manager.is_feature_enabled(PARTITION_FILTER_MAPPING_FLAG):
+ return
+
+ mapped_column = (
+ (model.partition_mapped_column or model.main_dttm_col)
+ if model.partition_column
+ else None
+ )
+ # `_upsert_columns` and `_override_columns` insert a new column with
+ # `db.session.add(TableColumn(..., table_id=model.id))` rather than
+ # appending to this relationship, and `BaseDAO.update` does not flush --
+ # so a column created *and* given a transform in the same request was
+ # invisible here and kept it. That is exactly the stray transform this
+ # method exists to clear, waiting for the mapping to resolve back to it.
+ db.session.flush()
+ db.session.expire(model, ["columns"])
+ for column in model.columns:
+ if column.column_name == mapped_column:
+ continue
+ if (
+ column.partition_value_transform
+ or column.partition_transform_is_monotonic
+ ):
+ column.partition_value_transform = None
+ column.partition_transform_is_monotonic = False
+
+ @staticmethod
+ def clear_dangling_partition_mapping(
Review Comment:
The dangling-reference repair only runs from `DatasetDAO.update`. `DeleteDatasetColumnCommand` (`DELETE /api/v1/dataset/<pk>/column/<column_id>`) removes a column through `DatasetColumnDAO.delete` without calling it. With the flag on, deleting the designated partition column that way leaves `partition_column` pointing at a column that no longer exists, and the next description-only PUT (no `columns` payload) validates against the model's remaining columns and is rejected. Should the column-delete path clear the mapping as well?
##########
superset/dashboards/schemas.py:
##########
@@ -379,6 +379,9 @@ class DashboardDatasetSchema(Schema):
granularity_sqla = fields.List(fields.List(fields.Str()))
normalize_columns = fields.Bool()
always_filter_main_dttm = fields.Bool()
+ partition_column = fields.Str()
Review Comment:
`partition_column` and `partition_mapped_column` are declared as non-nullable strings, but `SqlaTable.data` always includes them and both are `None` on any dataset without a mapping (and `partition_mapped_column` is `None` whenever the mapping follows `main_dttm_col`). The generated `DashboardDatasetSchema` in `openapi.json` then rejects an ordinary successful response under strict client validation. Could both fields be `allow_none=True` with the spec regenerated?
##########
superset/dashboards/schemas.py:
##########
@@ -379,6 +379,9 @@ class DashboardDatasetSchema(Schema):
granularity_sqla = fields.List(fields.List(fields.Str()))
normalize_columns = fields.Bool()
always_filter_main_dttm = fields.Bool()
+ partition_column = fields.Str()
+ partition_mapped_column = fields.Str()
+ partition_filter_mapping = fields.Dict(allow_none=True)
Review Comment:
`DASHBOARD_DATASET_INACCESSIBLE_FIELDS` strips columns, SQL, `main_dttm_col` and similar from a dataset the caller cannot access, but `partition_filter_mapping` is not in that list. `GET /api/v1/dashboard/<id>/datasets` therefore still returns the mapped and partition column names and the raw transform (`evaluated_transform`) to a Gamma user with dashboard access but no grant on that dataset. Should the three new fields be added to the redaction list?
##########
tests/unit_tests/connectors/sqla/partition_mapping_test.py:
##########
@@ -0,0 +1,2674 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Unit tests for ``superset.connectors.sqla.partition_mapping``."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from decimal import Decimal
+from importlib import import_module
+from typing import Any, cast
+from unittest.mock import MagicMock, patch, PropertyMock
+
+import pandas as pd
+import pytest
+from dateutil.relativedelta import relativedelta
+from flask import Flask
+from sqlalchemy.dialects import mysql, postgresql
+
+from superset.config import DISALLOWED_SQL_FUNCTIONS
+from superset.connectors.sqla.models import SqlaTable, TableColumn
+from superset.connectors.sqla.partition_mapping import (
+ _mirror_verdict_cache_key,
+ _placeholder_is_bindable,
+ _probe_cache_key,
+ _reads_as_temporal,
+ _render_literal,
+ build_mirrored_predicates,
+ build_probe_sql,
+ contains_executable_comment,
+ contains_jinja,
+ contains_value_placeholder,
+ drop_unmapped_value_transforms,
+ equality_mirrors_safely,
+ evaluate_transform,
+ find_non_deterministic_functions,
+ grain_bucket_width,
+ GRAIN_BUCKET_WIDTHS,
+ is_bare_expression,
+ is_parseable,
+ is_transform_active,
+ is_unfinished,
+ known_mirror_verdict,
+ MappingValidationIssue,
+ mirror_operator,
+ MIRRORABLE_ALWAYS,
+ MIRRORABLE_IF_MONOTONIC,
+ mirrorable_operators,
+ parse_error_detail,
+ placeholder_is_executable,
+ probe_sql_is_evaluable,
+ probed_value_type_error,
+ RawProbeValue,
+ resolve_partition_mapping,
+ stored_expression_error,
+ validate_partition_mapping,
+ validate_transform,
+)
+from superset.constants import TimeGrain
+from superset.db_engine_specs.base import BaseEngineSpec
+from superset.db_engine_specs.oracle import OracleEngineSpec
+from superset.db_engine_specs.postgres import PostgresEngineSpec
+from superset.models.core import Database
+from superset.sql.parse import SQLStatement
+from superset.utils.core import FilterOperator, GenericDataType, override_user
+
+
+@pytest.fixture(autouse=True)
+def real_probe_cache(app: Flask) -> Any:
+ """
+ The test app runs a null cache, which would make every cache assertion here
+ vacuously pass. Swap in a real in-memory one for the duration.
+ """
+ from flask_caching import Cache
+
+ from superset.extensions import cache_manager
+
+ cache = Cache(config={"CACHE_TYPE": "SimpleCache", "CACHE_DEFAULT_TIMEOUT": 300})
+ cache.init_app(app)
+ original = cache_manager._cache # noqa: SLF001
+ cache_manager._cache = cache # noqa: SLF001
+ yield
+ cache_manager._cache = original # noqa: SLF001
+
+
+@pytest.fixture(autouse=True)
+def enable_partition_filter_mapping(app: Flask) -> Any:
+ """The feature ships off; every test here exercises it on."""
+ original = app.config["DEFAULT_FEATURE_FLAGS"].get("PARTITION_FILTER_MAPPING")
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = True
+ yield
+ if original is None:
+ del app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"]
+ else:
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = original
+
+
+def _table(**kwargs: Any) -> SqlaTable:
+ database = Database(database_name="test_db", sqlalchemy_uri="sqlite://")
+ defaults: dict[str, Any] = {
+ "table_name": "web_events",
+ "database": database,
+ "main_dttm_col": "event_time",
+ "columns": [
+ TableColumn(column_name="event_time", is_dttm=True, type="TIMESTAMP"),
+ TableColumn(
+ column_name="dt_epoch",
+ type="BIGINT",
+ partition_value_transform=None,
+ ),
+ TableColumn(column_name="country", type="VARCHAR"),
+ TableColumn(column_name="region_key", type="VARCHAR"),
+ ],
+ }
+ defaults.update(kwargs)
+ return SqlaTable(**defaults)
+
+
+def _mapped_table(
+ *,
+ partition_column: str = "dt_epoch",
+ mapped_column: str = "event_time",
+ transform: str | None = "unix_timestamp(:value)",
+ monotonic: bool = True,
+ partition_mapped_column: str | None = None,
+ main_dttm_col: str | None = "event_time",
+) -> SqlaTable:
+ table = _table(main_dttm_col=main_dttm_col)
+ table.partition_column = partition_column
+ table.partition_mapped_column = partition_mapped_column
+ for column in table.columns:
+ if column.column_name == mapped_column:
+ column.partition_value_transform = transform
+ column.partition_transform_is_monotonic = monotonic
+ return table
+
+
+# ---------------------------------------------------------------------------
+# §2 — operator safety matrix
+# ---------------------------------------------------------------------------
+
+
+def test_equality_and_in_are_always_mirrorable() -> None:
+ """``=`` and ``IN`` are safe for any function ``T``."""
+ assert MIRRORABLE_ALWAYS == {FilterOperator.EQUALS, FilterOperator.IN}
+
+
+def test_range_operators_require_a_monotonic_transform() -> None:
+ assert MIRRORABLE_IF_MONOTONIC == {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+ }
+
+
+def test_mirrorable_operators_excludes_ranges_when_not_monotonic() -> None:
+ assert mirrorable_operators(is_monotonic=False) == MIRRORABLE_ALWAYS
+
+
+def test_mirrorable_operators_includes_ranges_when_monotonic() -> None:
+ assert mirrorable_operators(is_monotonic=True) == (
+ MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+ )
+
+
+@pytest.mark.parametrize(
+ "operator",
+ [
+ FilterOperator.NOT_EQUALS,
+ FilterOperator.NOT_IN,
+ FilterOperator.LIKE,
+ FilterOperator.ILIKE,
+ FilterOperator.NOT_LIKE,
+ FilterOperator.NOT_ILIKE,
+ FilterOperator.IS_NULL,
+ FilterOperator.IS_NOT_NULL,
+ FilterOperator.IS_TRUE,
+ FilterOperator.IS_FALSE,
+ ],
+)
+def test_negations_and_pattern_matches_are_never_mirrorable(
+ operator: FilterOperator,
+) -> None:
+ """
+ ``T`` is not injective, so ``col != v`` does **not** imply ``T(col) != T(v)``:
+ mirroring it would drop rows the original filter keeps.
+ """
+ assert operator not in mirrorable_operators(is_monotonic=True)
+
+
+def test_equality_is_dropped_when_the_engine_does_not_compare_byte_exactly() -> None:
+ """
+ "Safe for any function ``T``" reasons about value equality: ``T`` is a
+ function, so ``col = v`` gives ``T(col) = T(v)``. The engine reasons about
+ *SQL* equality, and the two part company under a case-insensitive
+ collation -- a stored ``'us'`` satisfies a filter for ``'US'`` while the
+ mirror ``hex('US')`` excludes the row, and the chart loses it silently.
+ """
+ assert mirrorable_operators(is_monotonic=False, equality_is_safe=False) == set()
+
+
+def test_ranges_survive_an_unsafe_equality() -> None:
+ """
+ Range mirroring already rests on the owner declaring ``T``
+ order-preserving with respect to the column's own order -- an assertion
+ about the very comparison semantics this gate checks for. Equality has no
+ such declaration behind it, which is why only equality is withdrawn.
+ """
+ assert (
+ mirrorable_operators(is_monotonic=True, equality_is_safe=False)
+ == MIRRORABLE_IF_MONOTONIC
+ )
+
+
+@pytest.mark.parametrize(
+ "operator,expected",
+ [
+ (FilterOperator.GREATER_THAN, FilterOperator.GREATER_THAN_OR_EQUALS),
+ (FilterOperator.LESS_THAN, FilterOperator.LESS_THAN_OR_EQUALS),
+ (
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ ),
+ (FilterOperator.LESS_THAN_OR_EQUALS, FilterOperator.LESS_THAN_OR_EQUALS),
+ (FilterOperator.EQUALS, FilterOperator.EQUALS),
+ (FilterOperator.IN, FilterOperator.IN),
+ ],
+)
+def test_a_strict_bound_mirrors_non_strictly(
+ operator: FilterOperator, expected: FilterOperator
+) -> None:
+ """
+ Order-preserving means non-decreasing, not injective, so ``col < v``
+ implies only ``T(col) <= T(v)``. A day-key transform maps a whole day onto
+ one value and a strict mirror drops the boundary bucket. The non-strict
+ cases are already safe and pass through, which is what makes applying this
+ twice harmless.
+ """
+ assert mirror_operator(operator) == expected
+
+
+def test_relaxing_a_bound_stays_inside_the_mirrorable_set() -> None:
+ """
+ The substitution is about strictness, not about which filters mirror. The
+ Explore indicator reads `mirrorable_operators`, so leaving that set alone is
+ what keeps the glyph from promising pruning the SQL does not do -- and it is
+ also what guarantees `handle_comparison_filter` is never handed an operator
+ it has no case for.
+ """
+ assert {
+ mirror_operator(operator) for operator in MIRRORABLE_IF_MONOTONIC
+ } <= MIRRORABLE_IF_MONOTONIC
+
+
+def _column(type_: str) -> TableColumn:
+ database = Database(database_name="t", sqlalchemy_uri="sqlite://")
+ table = SqlaTable(table_name="t", database=database)
+ return TableColumn(column_name="c", type=type_, table=table)
+
+
+@pytest.mark.parametrize(
+ "type_, binary, expected",
+ [
+ ("VARCHAR", True, True),
+ ("VARCHAR", False, False),
+ # Numeric and temporal comparison is exact everywhere.
+ ("BIGINT", False, True),
+ ("TIMESTAMP", False, True),
+ ("DOUBLE", False, True),
+ ],
+)
+def test_equality_mirrors_safely_only_guards_string_columns(
+ app: Flask, type_: str, binary: bool, expected: bool
+) -> None:
+ class _Spec(BaseEngineSpec):
+ binary_string_comparison = binary
+
+ with app.app_context():
+ assert equality_mirrors_safely(_column(type_), _Spec) is expected
+
+
+@pytest.mark.parametrize(
+ "type_, expected",
+ [
+ # The padded types: `'US'` and `'US '` are equal in the column, and
+ # `lower()` of the two is not.
+ ("CHAR(2)", False),
+ ("CHAR", False),
+ ("CHARACTER(2)", False),
+ ("NCHAR(2)", False),
+ # What PostgreSQL reflection reports for a `CHAR(n)` column.
+ ("BPCHAR", False),
+ ("bpchar(2)", False),
+ ("NATIONAL CHARACTER(2)", False),
+ # The variable-width types start with the same letters and must not be
+ # caught by it.
+ ("VARCHAR(2)", True),
+ ("NVARCHAR(2)", True),
+ ("CHARACTER VARYING(2)", True),
+ ("TEXT", True),
+ ],
+)
+def test_a_padded_character_column_declines_equality_on_a_byte_exact_engine(
+ app: Flask, type_: str, expected: bool
+) -> None:
+ """
+ `binary_string_comparison` speaks for the engine's default comparison,
+ which PostgreSQL declares -- and a `CHAR(2)` there still matches a filter
+ for `'US '` against a stored `'US'`, so the mirror `lower('US ')` excludes
+ the row. Padding is a property of the type, so it is asked per column.
+ """
+
+ class _Spec(BaseEngineSpec):
+ binary_string_comparison = True
+
+ with app.app_context():
+ assert equality_mirrors_safely(_column(type_), _Spec) is expected
+
+
+def test_redshift_does_not_opt_in_to_byte_exact_comparison() -> None:
+ """
+ Redshift ignores trailing blanks for `VARCHAR` as well as `CHAR`, so the
+ `True` it inherits from `PostgresBaseEngineSpec` would be wrong.
+ """
+ from superset.db_engine_specs.redshift import RedshiftEngineSpec
+
+ assert RedshiftEngineSpec.binary_string_comparison is False
+
+
+def test_equality_mirrors_safely_fails_closed_on_an_unresolvable_type(
+ app: Flask,
+) -> None:
+ """
+ The gate exists to stop a silent wrong answer, so a column whose type it
+ cannot read is treated as the risky case rather than waved through.
+ """
+ column = MagicMock()
+ type(column).type_generic = PropertyMock(side_effect=ValueError("no type"))
+
+ with app.app_context():
+ assert equality_mirrors_safely(column, BaseEngineSpec) is False
+
+
+def test_no_mapped_column_leaves_the_matrix_alone(app: Flask) -> None:
+ """Nothing to reason about, and the resolver bails out on it anyway."""
+ with app.app_context():
+ assert equality_mirrors_safely(None, BaseEngineSpec) is True
+
+
+@pytest.mark.parametrize(
+ "module, spec_name",
+ [
+ ("presto", "PrestoEngineSpec"),
+ ("hive", "HiveEngineSpec"),
+ ("trino", "TrinoEngineSpec"),
+ ("impala", "ImpalaEngineSpec"),
+ ("postgres", "PostgresEngineSpec"),
+ ("bigquery", "BigQueryEngineSpec"),
+ ("sqlite", "SqliteEngineSpec"),
+ ],
+)
+def test_the_byte_exact_engines_opt_in(module: str, spec_name: str) -> None:
+ """
+ The engines this feature targets compare text byte-exactly, so the gate
+ must not cost them the second canonical mapping (`lower(:value)` onto a
+ lowercased key).
+ """
+ spec = getattr(import_module(f"superset.db_engine_specs.{module}"), spec_name)
+ assert spec.binary_string_comparison is True
+
+
+@pytest.mark.parametrize("module, spec_name", [("mysql", "MySQLEngineSpec")])
+def test_a_case_insensitive_engine_does_not_opt_in(module: str, spec_name: str) -> None:
+ """
+ MySQL's default collation is `utf8mb4_0900_ai_ci`, which is exactly the
+ case the reviewer raised.
+ """
+ spec = getattr(import_module(f"superset.db_engine_specs.{module}"), spec_name)
+ assert spec.binary_string_comparison is False
+
+
+def test_the_base_spec_does_not_opt_in() -> None:
+ """A spec that has not said so does not mirror string equality."""
+ assert BaseEngineSpec.binary_string_comparison is False
+
+
+# ---------------------------------------------------------------------------
+# Time grain bucket widths
+# ---------------------------------------------------------------------------
+
+
+@pytest.mark.parametrize("grain", list(TimeGrain))
+def test_every_builtin_grain_has_a_known_bucket_width(
+ app: Flask, grain: TimeGrain
+) -> None:
+ """
+ The widening is only sound for a grain whose bucket width we know, so a
+ grain added upstream without a width here would silently stop mirroring.
+ This is the test that notices.
+ """
+ with app.app_context():
+ assert grain_bucket_width(grain.value, "sqlite") is not None
+
+
+def test_a_calendar_grain_widens_by_a_calendar_month(app: Flask) -> None:
+ """A month is not thirty days, and the month it lands in decides its width."""
+ with app.app_context():
+ width = grain_bucket_width(TimeGrain.MONTH.value, "sqlite")
+
+ assert width is not None
+ assert datetime(2026, 1, 31) + width == datetime(2026, 2, 28)
+ assert datetime(2026, 2, 1) + width == datetime(2026, 3, 1)
+
+
+def test_a_fractional_grain_has_a_width(app: Flask) -> None:
+ """
+ ``PT0.5H`` and ``P0.25Y`` are why the widths are written out rather than
+ parsed -- and the anchored week grains are intervals ``parse_duration``
+ rejects outright.
+ """
+ with app.app_context():
+ assert grain_bucket_width(TimeGrain.HALF_HOUR.value, "sqlite") == relativedelta(
+ minutes=30
+ )
+ assert grain_bucket_width(
+ TimeGrain.WEEK_ENDING_SATURDAY.value, "sqlite"
+ ) == relativedelta(days=7)
+
+
+def test_an_unknown_grain_has_no_known_width(app: Flask) -> None:
+ with app.app_context():
+ assert grain_bucket_width("P13X", "sqlite") is None
+ assert grain_bucket_width(None, "sqlite") is None
+
+
+def test_an_addon_grain_has_no_known_width(app: Flask) -> None:
+ """An operator-declared grain carries whatever duration string they typed."""
+ with app.app_context():
+ app.config["TIME_GRAIN_ADDONS"] = {"PT2S": "2 second"}
+ try:
+ assert grain_bucket_width("PT2S", "sqlite") is None
+ finally:
+ app.config["TIME_GRAIN_ADDONS"] = {}
+
+
+def test_a_builtin_grain_an_operator_redefined_has_no_known_width(
+ app: Flask,
+) -> None:
+ """
+ ``TIME_GRAIN_ADDON_EXPRESSIONS`` replaces a built-in grain's SQL for one
+ engine, so its duration no longer bounds the displacement *there* -- but it
+ still does on every other engine.
+ """
+ with app.app_context():
+ app.config["TIME_GRAIN_ADDON_EXPRESSIONS"] = {
+ "sqlite": {"P1D": "DATETIME({col}, 'start of year')"}
+ }
+ try:
+ assert grain_bucket_width(TimeGrain.DAY.value, "sqlite") is None
+ assert grain_bucket_width(TimeGrain.DAY.value, "hive") is not None
+ finally:
+ app.config["TIME_GRAIN_ADDON_EXPRESSIONS"] = {}
+
+
+def test_the_width_table_is_keyed_on_grain_durations(app: Flask) -> None:
+ """Keys are the ISO duration a filter carries, not the enum member name."""
+ assert GRAIN_BUCKET_WIDTHS[TimeGrain.DAY] == relativedelta(days=1)
+ assert set(GRAIN_BUCKET_WIDTHS) == {grain.value for grain in TimeGrain}
+
+
+# ---------------------------------------------------------------------------
+# §4.1 — resolving the effective mapping, and the defensive bail-outs
+# ---------------------------------------------------------------------------
+
+
+def test_resolve_returns_the_mapping_when_everything_lines_up(app: Flask) -> None:
+ with app.app_context():
+ mapping = resolve_partition_mapping(_mapped_table())
+
+ assert mapping is not None
+ assert mapping.partition_column == "dt_epoch"
+ assert mapping.mapped_column == "event_time"
+ assert mapping.value_transform == "unix_timestamp(:value)"
+ assert mapping.is_monotonic is True
+
+
+def test_effective_mapped_column_follows_main_dttm_col(app: Flask) -> None:
+ """No explicit override: the mapping follows the default datetime column."""
+ with app.app_context():
+ mapping = resolve_partition_mapping(_mapped_table())
+
+ assert mapping is not None
+ assert mapping.mapped_column == "event_time"
+
+
+def test_explicit_override_wins_over_main_dttm_col(app: Flask) -> None:
+ table = _mapped_table(
+ mapped_column="country",
+ transform="lower(:value)",
+ monotonic=False,
+ partition_mapped_column="country",
+ )
+ table.partition_column = "region_key"
+
+ with app.app_context():
+ mapping = resolve_partition_mapping(table)
+
+ assert mapping is not None
+ assert mapping.mapped_column == "country"
+ assert mapping.partition_column == "region_key"
+ assert mapping.is_monotonic is False
+
+
+def test_resolve_returns_none_when_the_feature_flag_is_off(app: Flask) -> None:
+ table = _mapped_table()
+ with app.app_context():
+ with patch(
+ "superset.connectors.sqla.partition_mapping.feature_flag_manager."
+ "is_feature_enabled",
+ return_value=False,
+ ):
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_without_a_partition_column(app: Flask) -> None:
+ table = _mapped_table()
+ table.partition_column = None
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_partition_column_no_longer_exists(
+ app: Flask,
+) -> None:
+ """A column sync can drop the physical partition column out from under us."""
+ table = _mapped_table()
+ table.partition_column = "dt_epoch_gone"
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_the_mapped_column_no_longer_exists(
+ app: Flask,
+) -> None:
+ table = _mapped_table(main_dttm_col="vanished")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_on_self_mapping(app: Flask) -> None:
+ """
+ ``partition_column == effective mapped column`` mirrors a column onto itself.
+ Save-time validation rejects it, but rows predating that validation exist.
+ """
+ table = _mapped_table(
+ partition_column="event_time",
+ mapped_column="event_time",
+ )
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+@pytest.mark.parametrize("transform", [None, "", " "])
+def test_resolve_returns_none_without_a_transform(
+ app: Flask, transform: str | None
+) -> None:
+ table = _mapped_table(transform=transform)
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_the_transform_lacks_the_placeholder(
+ app: Flask,
+) -> None:
+ table = _mapped_table(transform="unix_timestamp(event_time)")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_for_a_non_deterministic_transform(app: Flask) -> None:
+ """
+ The query-time gate is `is_transform_active`, the same one the Explore
+ indicator reads. Anything narrower would let a transform that reached
+ storage without passing `UpdateDatasetCommand` -- through import, or a
+ hand-written bundle -- mirror a filter with a value frozen at probe time,
+ while the editor reported the mapping as inactive and nothing on screen
+ said otherwise.
+ """
+ table = _mapped_table(transform="unix_timestamp(:value) + rand()")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_for_a_multi_expression_transform(app: Flask) -> None:
+ """A select list is not an expression; the probe cannot align its columns."""
+ table = _mapped_table(transform="lower(:value), 'x'")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_for_an_unparseable_transform(app: Flask) -> None:
+ table = _mapped_table(transform="unix_timestamp(:value")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_the_mapped_column_has_an_advanced_data_type(
+ app: Flask,
+) -> None:
+ """
+ ``translate_filter`` builds its own predicate shape from *translated* values,
+ so the ``(operator, value)`` pair the operator matrix reasons about does not
+ exist. Mirroring anyway would silently apply the wrong values (§4.1).
+ """
+ table = _mapped_table()
+ for column in table.columns:
+ if column.column_name == "event_time":
+ column.advanced_data_type = "port"
+
+ with app.app_context():
+ with patch.dict(app.config["ADVANCED_DATA_TYPES"], {"port": MagicMock()}):
+ with patch(
+ "superset.connectors.sqla.partition_mapping.feature_flag_manager."
+ "is_feature_enabled",
+ side_effect=lambda flag: (
+ flag in {"PARTITION_FILTER_MAPPING", "ENABLE_ADVANCED_DATA_TYPES"}
+ ),
+ ):
+ assert resolve_partition_mapping(table) is None
+
+
+def test_advanced_data_type_does_not_block_when_the_flag_is_off(app: Flask) -> None:
+ """An inert ``advanced_data_type`` is not a reason to skip mirroring."""
+ table = _mapped_table()
+ for column in table.columns:
+ if column.column_name == "event_time":
+ column.advanced_data_type = "port"
+
+ with app.app_context():
+ with patch(
+ "superset.connectors.sqla.partition_mapping.feature_flag_manager."
+ "is_feature_enabled",
+ side_effect=lambda flag: flag == "PARTITION_FILTER_MAPPING",
+ ):
+ assert resolve_partition_mapping(table) is not None
+
+
+# ---------------------------------------------------------------------------
+# §5 — transform inspection helpers
+# ---------------------------------------------------------------------------
+
+
+@pytest.mark.parametrize(
+ "transform,expected",
+ [
+ ("unix_timestamp(:value)", True),
+ ("lower(:value)", True),
+ ("CAST(:value AS BIGINT)", True),
+ ("unix_timestamp(event_time)", False),
+ (":values", False),
+ ("", False),
+ (None, False),
+ ],
+)
+def test_contains_value_placeholder(transform: str | None, expected: bool) -> None:
+ assert contains_value_placeholder(transform) is expected
+
+
+@pytest.mark.parametrize(
+ "transform,expected",
+ [
+ ("unix_timestamp(:value)", False),
+ ("{{ current_username() }}", True),
+ ("lower({% if x %}:value{% endif %})", True),
+ ("lower(:value) -- {# comment #}", True),
+ ],
+)
+def test_contains_jinja(transform: str, expected: bool) -> None:
+ assert contains_jinja(transform) is expected
+
+
+@pytest.mark.parametrize(
+ ("transform", "expected"),
+ [
+ ("lower(:value)", False),
+ ("lower(:value) /* an ordinary comment */", False),
+ ("lower(:value) -- a line comment", False),
+ (":value /*!50000 + 1 */", True),
+ (":value /*M!50000 + 1 */", True),
+ (":value /*! + 1 */", True),
+ ("", False),
+ (None, False),
+ ],
+)
+def test_contains_executable_comment(transform: str | None, expected: bool) -> None:
+ assert contains_executable_comment(transform) is expected
+
+
+@pytest.mark.parametrize(
+ "transform",
+ [
+ "unix_timestamp(:value)",
+ "lower(:value)",
+ "CAST(:value AS BIGINT)",
+ "date_format(:value, 'yyyyMMdd')",
+ ],
+)
+def test_pure_transforms_report_no_non_deterministic_functions(
+ transform: str,
+) -> None:
+ assert find_non_deterministic_functions(transform, "hive") == set()
+
+
+@pytest.mark.parametrize(
+ "transform,expected_name",
+ [
+ ("date_diff(:value, now())", "NOW"),
+ ("CAST(:value AS BIGINT) + rand()", "RAND"),
+ ("CAST(:value AS DATE) - current_date", "CURRENT_DATE"),
+ ],
+)
+def test_non_deterministic_functions_are_reported(
+ transform: str, expected_name: str
+) -> None:
+ """
+ The probe runs at a different moment and in a different session from the
+ chart query, and its result is cached, so anything time- or
+ randomness-dependent freezes a snapshot of probe time into the predicate.
+ """
+ assert expected_name in find_non_deterministic_functions(transform, "hive")
+
+
+def test_niladic_unix_timestamp_is_rejected_but_the_unary_form_is_not() -> None:
+ """
+ On Hive/Impala ``unix_timestamp()`` means "now" while ``unix_timestamp(x)``
+ -- the canonical temporal transform -- is pure. The distinction is the whole
+ reason this check inspects arity rather than just the name.
+ """
+ assert find_non_deterministic_functions("unix_timestamp(:value)", "hive") == set()
+ assert find_non_deterministic_functions(
+ "unix_timestamp(:value) - unix_timestamp()", "hive"
+ )
+
+
+# ---------------------------------------------------------------------------
+# §4.2 — probe evaluation
+# ---------------------------------------------------------------------------
+
+
+def _user(username: str) -> Any:
+ """A stand-in for `override_user`, which only needs `.username` here."""
+ user = MagicMock()
+ user.username = username
+ user.is_anonymous = False
+ return user
+
+
+def _database_returning(values: list[Any]) -> Database:
+ """A real ``Database`` (so the dialect is real) with only ``get_df`` stubbed."""
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ return_value=pd.DataFrame(
+ [values], columns=[f"v{i}" for i in range(len(values))]
+ )
+ )
+ return database
+
+
+def _database_returning_frame(frame: pd.DataFrame) -> Database:
+ """
+ ``_database_returning`` for a probe result whose column dtypes matter.
+
+ The flat-list sibling builds its frame from one Python list, so pandas
+ infers a single dtype and the row-versus-cell distinction cannot be seen.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ return_value=frame
+ )
+ return database
+
+
+def _probe(database: Database) -> MagicMock:
+ """
+ The stubbed ``get_df``, typed for call assertions.
+
+ ``Database.get_df`` is a real method, so mypy reads its declared signature
+ rather than the mock that replaced it and rejects ``.call_args`` and
+ friends.
+ """
+ return cast(MagicMock, database.get_df)
+
+
+def test_evaluate_transform_returns_one_value_per_input(app: Flask) -> None:
+ database = _database_returning([1767225600, 1769904000])
+
+ with app.app_context():
+ result = evaluate_transform(
+ database,
+ None,
+ "default",
+ "unix_timestamp(:value)",
+ ["2026-01-01 00:00:00", "2026-02-01 00:00:00"],
+ )
+
+ assert result == [1767225600, 1769904000]
+ _probe(database).assert_called_once()
+
+
+def test_evaluate_transform_binds_values_rather_than_interpolating(
+ app: Flask,
+) -> None:
+ """
+ Filter values are attacker-controlled (a Gamma user picks them), so they must
+ be bound and escaped, never pasted into the probe SQL.
+ """
+ database = _database_returning(["o''brien"])
+
+ with app.app_context():
+ evaluate_transform(database, None, None, "lower(:value)", ["O'Brien"])
+
+ sql = _probe(database).call_args.kwargs["sql"]
+ assert "O'Brien" not in sql
+ assert "O''Brien" in sql
+
+
+@pytest.mark.parametrize(
+ ("transform", "expected"),
+ [
+ ("lower(:value)", True),
+ ("CAST(:value AS BIGINT)", True),
+ ("date_format(:value, '%Y%m%d')", True),
+ # The cast shorthand: a trailing colon stops SQLAlchemy's bind scan.
+ (":value::bigint", False),
+ ("(:value::date)::text", False),
+ ],
+)
+def test_a_postgres_cast_shorthand_is_not_bindable(
+ transform: str, expected: bool
+) -> None:
+ """
+ `VALUE_PLACEHOLDER_RE` is `:value\b`, which matches inside `:value::bigint`.
+ SQLAlchemy's own scan ends with `(?![:\\w$])`, so the following colon stops
+ it: `text(":value::bigint")` reports a parameter named `valu`, and asking it
+ to bind `value` raises.
+
+ Pinned because the two regexes disagreeing is the whole bug: every
+ write-side gate accepted the transform and the probe then died on an
+ `ArgumentError` that `_probe` swallows.
+ """
+ assert _placeholder_is_bindable(transform) is expected
+
+
+def test_a_cast_shorthand_transform_still_probes(app: Flask) -> None:
+ """
+ The transform is valid SQL, passes every gate, and used to prune nothing:
+ `build_probe_sql` raised, `_probe` swallowed it, and the only symptom was a
+ mapping that silently never mirrored -- with the preview reporting an engine
+ failure for SQL that was never sent.
+ """
+ database = _database_returning([20260115])
+
+ with app.app_context():
+ result = evaluate_transform(
+ database, None, None, ":value::bigint", ["20260115"]
+ )
+
+ assert result == [20260115]
+ assert _probe(database).call_count == 1
+ assert "::bigint" in _probe(database).call_args.kwargs["sql"]
+
+
+def test_a_cast_shorthand_value_is_still_escaped_by_the_dialect(
+ app: Flask,
+) -> None:
+ """
+ The fallback substitutes where the bind path binds, so it has to earn the
+ same guarantee its sibling above pins: the value is rendered by the
+ dialect's literal processor, not pasted in.
+
+ Binding was only ever the vehicle for reaching that processor --
+ `_compile_literal` inlines the result either way -- so this renders first
+ and substitutes second. Same string, different order.
+ """
+ database = _database_returning(["x"])
+
+ with app.app_context():
+ evaluate_transform(database, None, None, ":value::text", ["O'Brien"])
+
+ sql = _probe(database).call_args.kwargs["sql"]
+ assert "O'Brien" not in sql
+ assert "O''Brien" in sql
+
+
+def test_evaluate_transform_dedupes_repeated_values(app: Flask) -> None:
+ """Three inputs, two distinct: the probe evaluates the transform twice."""
+ database = _database_returning(["us", "us"])
+
+ with app.app_context():
+ result = evaluate_transform(
+ database, None, None, "lower(:value)", ["US", "US", "us"]
+ )
+
+ assert result == ["us", "us", "us"]
+ sql = _probe(database).call_args.kwargs["sql"]
+ assert sql.count("lower") == 2
+
+
+def test_evaluate_transform_fails_open_on_a_short_result_row(app: Flask) -> None:
+ """A row narrower than the probe asked for means the results cannot be
+ aligned back to their inputs; pruning is skipped rather than guessed at."""
+ database = _database_returning(["us"])
+
+ with app.app_context():
+ assert (
+ evaluate_transform(database, None, None, "lower(:value)", ["US", "CA"])
+ is None
+ )
+
+
+def test_evaluate_transform_fails_open_on_a_wide_result_row(app: Flask) -> None:
+ """
+ Too many columns is the dangerous direction. A transform whose select list
+ holds two expressions returns 2N columns for N inputs, and reading the first
+ N interleaves the expressions instead of taking one per value -- a predicate
+ built from the wrong values rather than one that is merely short. A frame of
+ `('us', 'x', 'ca', 'x')` read as the first two columns would have yielded
+ `('us', 'x')` and dropped every CA row.
+
+ The transform is a perfectly ordinary `lower(:value)` and the width comes
+ from the stubbed frame, which is the only way to reach the guard: a
+ transform that really does carry two expressions -- `lower(:value), 'x'` --
+ is refused by `stored_expression_error` for not being a single expression,
+ so `get_df` is never called and `None` comes back for an unrelated reason.
+ Asserting the probe *ran* is what separates the two, and it is what makes
+ relaxing the guard from `!=` to `<` fail here rather than pass: four columns
+ for two inputs is not fewer than two.
+ """
+ database = _database_returning(["us", "x", "ca", "x"])
+
+ with app.app_context():
+ assert (
+ evaluate_transform(database, None, None, "lower(:value)", ["US", "CA"])
+ is None
+ )
+
+ assert _probe(database).call_count == 1
+
+
+def test_the_probe_select_carries_the_engine_s_from_clause(app: Flask) -> None:
+ """
+ A `SELECT` with no `FROM` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from. Without this every probe on those engines
+ raises, which `evaluate_transform` swallows -- so the only symptom is a
+ correctly configured mapping that silently never prunes.
+ """
+ assert build_probe_sql("lower(:value)", ["US"]) == "SELECT lower('US') AS v0"
+ assert build_probe_sql("lower(:value)", ["US"], None, " FROM DUAL").endswith(
+ " FROM DUAL"
+ )
+ assert OracleEngineSpec.select_without_from_suffix == " FROM DUAL"
+ assert BaseEngineSpec.select_without_from_suffix == ""
+
+
+@pytest.mark.parametrize("dialect", [mysql.dialect(), postgresql.dialect()])
+def test_the_probe_select_does_not_double_percent_signs(dialect: Any) -> None:
+ """
+ `TextClause` compilation runs the dialect's `post_process_text`, which
+ doubles every `%` on any paramstyle whose DBAPI later interpolates
+ parameters -- MySQL and Postgres, and every spec inheriting from them. The
+ probe has no such interpolation pass: it executes with no bound parameters
+ at all. Left doubled, `date_format(:value, '%Y%m%d')` asks the warehouse
+ for the literal string `%%Y%%m%%d`, so the probe returns that instead of a
+ date and the mirrored predicate drops every row the filter keeps.
+ """
+ sql = build_probe_sql("date_format(:value, '%Y%m%d')", ["2026-01-15"], dialect)
+
+ assert "'%Y%m%d'" in sql
+ assert "%%" not in sql
+
+
+def test_the_probe_select_is_unchanged_on_a_dialect_that_does_not_double() -> None:
+ """
+ Pins the no-dialect path, which is also the blind spot: the default dialect
+ does not double percent signs, so no assertion made through it can see the
+ bug the two cases above cover.
+ """
+ assert (
+ build_probe_sql("date_format(:value, '%Y%m%d')", ["2026-01-15"])
+ == "SELECT date_format('2026-01-15', '%Y%m%d') AS v0"
+ )
+
+
+def test_a_raw_probe_value_is_substituted_literally() -> None:
+ r"""
+ `RawProbeValue.sql` is rendered from a filter value, so it reaches
+ `parse_skeleton` as the *replacement* for `:value`. Read as a replacement
+ template, a backslash in it is an escape: `array('a\nb')` -- which is how a
+ dialect renders the two characters `\` and `n` -- would become a real
+ newline, so the engine is asked about a different array than the predicate
+ compares and the mirror can exclude rows the filter keeps.
+ """
+ sql = build_probe_sql("toYYYYMM(:value)", [RawProbeValue(r"array('a\nb')")])
+
+ assert sql == r"SELECT toYYYYMM(array('a\nb')) AS v0"
+
+
+def test_a_raw_probe_value_does_not_re_inject_the_placeholder() -> None:
+ r"""
+ `\g<0>` in a replacement template expands to the whole match, which would
+ put `:value` back into the probe -- an unbound parameter the engine refuses.
+ """
+ sql = build_probe_sql("toYYYYMM(:value)", [RawProbeValue(r"'a\g<0>b'")])
+
+ assert sql == r"SELECT toYYYYMM('a\g<0>b') AS v0"
+ assert ":value" not in sql
+
+
+def test_a_raw_probe_value_with_a_group_reference_does_not_raise() -> None:
+ r"""
+ `\1` is an invalid group reference for this pattern, so as a replacement
+ template it raised `re.PatternError` rather than probing anything.
+ """
+ sql = build_probe_sql("toYYYYMM(:value)", [RawProbeValue(r"'a\1b'")])
+
+ assert sql == r"SELECT toYYYYMM('a\1b') AS v0"
+
+
+def test_a_probed_literal_keeps_its_percent_sign(app: Flask) -> None:
+ """
+ The preview panel renders probed values through the same dialect, so a
+ value that merely contains a `%` would be shown doubled.
+ """
+ database = Database(database_name="pct_db", sqlalchemy_uri="postgresql://h/d")
+
+ with app.app_context():
+ assert _render_literal(database, "100%") == "'100%'"
+
+
+def test_the_probe_reads_each_cell_without_row_wide_dtype_coercion(
+ app: Flask,
+) -> None:
+ """
+ A row is a Series, so it carries one dtype across every probe column: a row
+ mixing an exact int64 with a float unifies to float64 and an integer
+ partition key above 2^53 comes back rounded. The mirror then asks for a key
+ the warehouse does not hold, and the row the filter matched is dropped.
+ """
+ database = _database_returning_frame(
+ pd.DataFrame({"v0": [9007199254740993], "v1": [1.5]})
+ )
+
+ with app.app_context():
+ probed = evaluate_transform(
+ database, None, None, "CAST(:value AS NUMERIC)", ["9007199254740993", "1.5"]
+ )
+
+ assert probed == [9007199254740993, 1.5]
+
+
+def test_evaluate_transform_pins_catalog_and_schema(app: Flask) -> None:
+ """
+ The probe runs in a different session from the chart query; pinning the
+ catalog and schema keeps session settings as close as the pool allows.
+ """
+ database = _database_returning([1])
+
+ with app.app_context():
+ evaluate_transform(database, "prod", "analytics", "lower(:value)", ["x"])
+
+ kwargs = _probe(database).call_args.kwargs
+ assert kwargs["catalog"] == "prod"
+ assert kwargs["schema"] == "analytics"
+
+
+def test_evaluate_transform_fails_open_when_the_probe_raises(app: Flask) -> None:
+ """A wedged engine must not break the chart — it just stops pruning."""
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ side_effect=RuntimeError("connection reset")
+ )
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, "lower(:value)", ["x"]) is None
+
+
+def test_evaluate_transform_fails_open_on_an_empty_result(app: Flask) -> None:
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ return_value=pd.DataFrame()
+ )
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, "lower(:value)", ["x"]) is None
+
+
+def test_evaluate_transform_returns_none_for_no_values(app: Flask) -> None:
+ database = _database_returning([])
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, "lower(:value)", []) is None
+
+ _probe(database).assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "transform",
+ [
+ "(SELECT password FROM ab_user LIMIT 1) || :value",
+ "lower(:value) UNION ALL SELECT password FROM ab_user",
+ "lower(:value); DROP TABLE ab_user",
+ "password || :value FROM ab_user",
+ "lower(:value) FROM ab_user WHERE 1 = 1",
+ ],
+ ids=[
+ "subquery",
+ "set-operation",
+ "multi-statement",
+ "bare-from",
+ "from-and-where",
+ ],
+)
+def test_a_transform_that_is_not_a_storable_expression_never_runs(
+ app: Flask, transform: str
+) -> None:
+ """
+ The probe is where a transform stops being text and becomes SQL.
+
+ `build_probe_sql` binds `:value` and splices the rest in verbatim, so a
+ transform that was never a single harmless expression is arbitrary SQL
+ against the dataset's database -- read back out of the emitted predicate
+ by anyone who can open "View query". The write-side gates refuse these,
+ but they can only speak for rows written after they existed, so the last
+ word belongs here.
+ """
+ database = _database_returning(["irrelevant"])
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, transform, ["us"]) is None
+
+ _probe(database).assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "transform, unfinished",
+ [
+ ("unix_timestamp(:value", True),
+ ("unix_timestamp(:value))", True),
+ ("unix_timestamp(:value) +", True),
+ ("unix_timestamp(:value)", False),
+ ("unix_timestamp(:value); DROP TABLE ab_user", False),
+ ("unix_timestamp(:value) UNION ALL SELECT password FROM ab_user", False),
+ ("password || :value FROM ab_user", False),
+ ],
+)
+def test_is_unfinished_separates_not_sql_yet_from_the_wrong_sql(
+ transform: str, unfinished: bool
+) -> None:
+ """
+ The two deserve opposite treatment -- a half-typed transform is stored and
+ parked inactive, the wrong SQL is refused -- and neither `is_parseable` nor
+ parsing as a single statement tells them apart, because the multi-statement
+ form fails both exactly as unfinished text does. Parsing as a script does.
+ """
+ assert is_unfinished(transform, "hive") is unfinished
+
+
+def test_a_transform_smuggling_its_own_from_clause_is_refused(app: Flask) -> None:
+ """
+ The hole this gate was added for.
+
+ `is_parseable` counts only the projection, so `password || :value FROM
+ ab_user` reads as a single select expression and passed every write-side
+ gate -- including with `ALLOW_ADHOC_SUBQUERY` off, since a top-level FROM
+ is not a sub-query. `build_probe_sql` then emitted `SELECT password || 'us'
+ AS v0 FROM ab_user`, where its own alias is read as a table alias on the
+ FROM clause the transform brought with it: valid SQL, one row, and the
+ secret handed back through the predicate the preview panel renders.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ transform = "password || :value FROM ab_user"
+
+ assert is_parseable(transform, "sqlite") is True
+ assert is_bare_expression(transform, "sqlite") is False
+
+ with app.app_context():
+ reason = stored_expression_error(database, None, None, transform)
+ assert reason is not None
+
+ blocking = _blocking(validate_transform(transform, "sqlite"))
+ assert len(blocking) == 1
+ assert "single SQL expression" in str(blocking[0].message)
+ assert is_transform_active(transform, "sqlite") is False
+
+
+def test_a_subquery_transform_is_refused_even_with_adhoc_subquery_enabled(
+ app: Flask,
+) -> None:
+ """
+ `validate_adhoc_subquery` admits a sub-query under `ALLOW_ADHOC_SUBQUERY`
+ and returns RLS-rewritten SQL -- which this path has no way to propagate,
+ because `build_probe_sql` splices the original transform text. So the probe
+ ran a sub-query with no row-level-security predicates at all and reported
+ the hidden row in `emitted_predicate`. A transform is a scalar function of
+ `:value`, so refusing the sub-query outright is both correct and what makes
+ the missing RLS rewrite moot.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ transform = "(SELECT secret FROM vault LIMIT 1) || :value"
+
+ with app.app_context():
+ app.config["DEFAULT_FEATURE_FLAGS"]["ALLOW_ADHOC_SUBQUERY"] = True
+ try:
+ reason = stored_expression_error(database, None, None, transform)
+ finally:
+ del app.config["DEFAULT_FEATURE_FLAGS"]["ALLOW_ADHOC_SUBQUERY"]
+
+ assert reason is not None
+ assert "sub-query" in reason
+
+
+@pytest.mark.parametrize(
+ "comment",
+ ["/*!50000 + (SELECT secret FROM vault LIMIT 1) */", "/*M!50000 + 1 */"],
+)
+def test_an_executable_comment_is_refused_by_every_gate(
+ app: Flask, comment: str
+) -> None:
+ """
+ The one construct that made the shape gates describe a statement the engine
+ would not run.
+
+ sqlglot reads a MySQL executable comment as comment data: the pinned parse
+ below reports no sub-query and no clause, so `stored_expression_error` and
+ `probe_sql_is_evaluable` both passed it, while MySQL and MariaDB execute
+ what is inside. An owner with dataset write and no SQL Lab could put one in
+ a transform, call the preview and read a table back out of
+ `emitted_predicate`, with no RLS on the hidden query.
+
+ Refused on every engine, not only the two that honour it -- hence SQLite
+ here. There is no legitimate transform carrying one, and a per-engine gate
+ would store on Postgres what detonates after the dataset is re-pointed.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ transform = f"(:value {comment})"
+
+ # The premise: no parse-tree gate can see it.
+ statement = SQLStatement(f"SELECT (1 {comment}) AS v0", "mysql")
+ assert statement.has_subquery() is False
+ assert statement.get_clause_names() == set()
+
+ with app.app_context():
+ assert stored_expression_error(database, None, None, transform) is not None
+
+ blocking = [
+ issue for issue in validate_transform(transform, "mysql") if issue.blocking
+ ]
+ assert len(blocking) == 1
+ assert "executable comment" in str(blocking[0].message)
+
+
+def test_an_executable_comment_stops_the_probe_before_the_engine(app: Flask) -> None:
+ """
+ The gate above is the save path. This is the row an earlier release stored:
+ `_probe` consults `stored_expression_error` on every call, so a transform
+ already in the metadata database never reaches `get_df`.
+ """
+ database = _database_returning(["x"])
+ transform = "(:value /*!50000 + (SELECT secret FROM vault LIMIT 1) */)"
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, transform, ["US"]) is None
+
+ assert _probe(database).call_count == 0
+
+
+def test_a_plain_comment_is_still_allowed_through_the_shape_gates(
+ app: Flask,
+) -> None:
+ """
+ Only the executable form is refused. An ordinary comment is inert on every
+ engine, so rejecting it would cost an owner a transform that works -- and
+ the placeholder gate already covers the case that matters, a `:value` the
+ comment swallows.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+
+ with app.app_context():
+ assert (
+ stored_expression_error(database, None, None, "lower(:value) /* ok */")
+ is None
+ )
+
+
+def test_a_transform_calling_a_disallowed_function_is_refused(app: Flask) -> None:
+ """
+ The probe executes the transform, so the operator's function denylist has
+ to apply to it for the same reason it applies in SQL Lab.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ transform = "version() || :value"
+
+ with app.app_context():
+ original = app.config["DISALLOWED_SQL_FUNCTIONS"]
+ try:
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = {"sqlite": {"version"}}
+ reason = stored_expression_error(database, None, None, transform)
+ assert reason is not None
+ assert "version" in reason
+
+ # Named, rather than echoing the operator's whole denylist back.
+ assert "current_user" not in reason
+
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = {}
+ assert stored_expression_error(database, None, None, transform) is None
+ finally:
+ # Restored: `app.config` is shared, and leaving it emptied silently
+ # disabled this gate for every test that ran afterwards.
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = original
+
+
+@pytest.mark.parametrize(
+ "function",
+ [
+ "database_to_xml",
+ "database_to_xmlschema",
+ "database_to_xml_and_xmlschema",
+ "schema_to_xml",
+ "schema_to_xmlschema",
+ "schema_to_xml_and_xmlschema",
+ "table_to_xml",
+ "table_to_xmlschema",
+ "table_to_xml_and_xmlschema",
+ "query_to_xml",
+ "query_to_xmlschema",
+ "query_to_xml_and_xmlschema",
+ ],
+)
+def test_the_whole_postgres_xml_family_is_denied_by_default(function: str) -> None:
+ """
+ These read tables with no FROM clause and no sub-query, so every gate that
+ reasons about table references is blind to them -- the denylist is the only
+ thing that can refuse them, and it has to name each shape. `schema_to_xml`
+ and three siblings were missing, so a bare scalar call cleared
+ `stored_expression_error` entirely and returned connection-user-readable
+ schema contents through preview.
+
+ Asserted against the shipped default rather than through the gate, because
+ the gap was an incomplete enumeration rather than broken wiring -- and
+ because `app.config` is ambient here, which the behavioural test below
+ handles by setting the denylist itself.
+ """
+ assert function in DISALLOWED_SQL_FUNCTIONS["postgresql"]
+
+
+def test_a_denied_read_capable_function_is_refused_despite_having_no_from(
+ app: Flask,
+) -> None:
+ """
+ The wiring half: a bare scalar call passes the length, single-statement,
+ bare-expression, sub-query and placeholder gates, so the denylist is what
+ has to stop it.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="postgresql://u@h/d")
+ transform = "schema_to_xml('public', true, false, '') || :value"
+
+ with app.app_context():
+ original = app.config["DISALLOWED_SQL_FUNCTIONS"]
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = {"postgresql": {"schema_to_xml"}}
+ try:
+ reason = stored_expression_error(database, None, None, transform)
+ finally:
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = original
+
+ assert reason is not None
+ assert "schema_to_xml" in reason
+
+
+@pytest.mark.parametrize("function", ["ts_rewrite", "ts_stat"])
+def test_the_postgres_full_text_query_functions_are_denied_by_default(
+ function: str,
+) -> None:
+ """
+ `ts_stat('select ...')` and `ts_rewrite(q, 'select ...')` run their *text*
+ argument as a query. The query is a string, so these have the same blind
+ spot the XML family above does: no FROM clause and no sub-query for a
+ table-reference gate to reason about, which leaves the denylist as the only
+ thing that can refuse them.
+ """
+ assert function in DISALLOWED_SQL_FUNCTIONS["postgresql"]
+
+
+@pytest.mark.parametrize(
+ "function", ["getxml", "getxmltype", "newcontext", "newcontextfromhierarchy"]
+)
+def test_the_oracle_query_running_xml_functions_are_denied_by_default(
+ function: str,
+) -> None:
+ """
+ `DBMS_XMLGEN.GETXML('select secret from vault')` runs its text argument as
+ a query -- the same blind spot as the PostgreSQL families above, on the
+ engine both reviewers named. Listed bare because the package prefix never
+ reaches the matcher: sqlglot parses the call as an anonymous function named
+ `GETXML`, and `get_disallowed_functions` compares against that name.
+ """
+ assert function in DISALLOWED_SQL_FUNCTIONS["oracle"]
+
+
+def test_a_package_qualified_denied_function_is_refused(app: Flask) -> None:
+ """
+ The wiring half for the bare-name listing above: the denylist entry has to
+ match a call written with its package prefix, which is the only way anyone
+ writes these.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="oracle://u@h/d")
+ transform = "DBMS_XMLGEN.GETXML('select secret from vault') || :value"
+
+ with app.app_context():
+ reason = stored_expression_error(database, None, None, transform)
+
+ assert reason is not None
+ assert "getxml" in reason
+
+
+def test_a_denied_query_running_text_function_is_refused(app: Flask) -> None:
+ """
+ The wiring half, and the only thing that proves the *name* matching works
+ for these two: neither is a function sqlglot models, so each reaches
+ `get_disallowed_functions` through its ANONYMOUS branch rather than as a
+ typed node. A denylist entry that only matched modelled functions would
+ pass the enumeration test above and still let these through.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="postgresql://u@h/d")
+ transform = "ts_stat('select 1') || :value"
+
+ with app.app_context():
+ original = app.config["DISALLOWED_SQL_FUNCTIONS"]
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = {"postgresql": {"ts_stat"}}
+ try:
+ reason = stored_expression_error(database, None, None, transform)
+ finally:
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = original
+
+ assert reason is not None
+ assert "ts_stat" in reason
+
+
+def test_the_function_denylist_is_keyed_on_the_engine_spec_name(app: Flask) -> None:
+ """
+ Every other denylist gate in the codebase keys on the engine spec's own
+ name, which is also the name the config documentation tells an operator to
+ write, so this one does too -- a spec covering several SQLAlchemy backends
+ through `engine_aliases` reports the one canonical name under which its
+ entry exists.
+
+ Tested through an *aliased* engine, which is the only way to tell the two
+ names apart. On `sqlite://` the backend and the spec name are both
+ `"sqlite"`, so the assertion held whichever one the gate read, and the test
+ did not check what its name promises. `postgres://` is
+ `PostgresEngineSpec.engine_aliases`, so the URL's backend is `postgres`
+ while the spec -- and the config key an operator writes -- is `postgresql`.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="postgres://u@h/d")
+
+ with app.app_context():
+ # The premise, asserted rather than assumed: if this alias ever goes
+ # away, the test below stops discriminating and should say so here.
+ assert database.backend == "postgres"
+ assert database.db_engine_spec.engine == "postgresql"
+
+ # Denied only under the spec's name. Keyed on `database.backend` the
+ # gate would find no entry and let the call through.
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = {"postgresql": {"version"}}
Review Comment:
`app` is module-scoped, and this test (like the one at :1517) overwrites `app.config["DISALLOWED_SQL_FUNCTIONS"]` without restoring it. Run before `test_a_package_qualified_denied_function_is_refused` (for example with `-k`, random ordering or xdist), that test sees `{"postgresql": {"version"}}`, has no Oracle entry, and fails its refusal assertion even though the shipped defaults are correct. Could these use `monkeypatch.setitem` or the try/finally restore the neighbouring tests use?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2929 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+class Unmirrorable:
+ """
+ A filter no mirror can stand in for, and why.
+
+ Returned by `ExploreMixin.mirror_probe_request` for a value the engine
+ compares more coarsely than the filter carries, one it cannot render as a
+ literal, one in a time frame the transform would discard, or an ``IN`` list
+ with a member of any of those kinds. An object rather than `None`, because
+ `None` is a filter value in its own right.
+
+ The reason rides along because the preview has to explain the decline to
+ the owner, and the two declines want different advice: "the engine compares
+ less of this value than you typed, so map a column it compares in full" is
+ sound guidance for a `DATE` column and actively misleading for an
+ offset-bearing bound on a `TIMESTAMP` one, which already is such a column.
+ Carried rather than re-derived so the preview's explanation cannot come
+ apart from the chart path's decision.
+
+ Lives here rather than beside that method so the preview can read it too:
+ `superset.models.helpers` imports this module, so these can only cross the
+ boundary in this direction. Both callers recognise the same instances -- a
+ preview that answered "valid" for a request the chart path declines is the
+ drift this is here to prevent.
+ """
+
+ __slots__ = ("reason",)
+
+ def __init__(self, reason: str) -> None:
+ self.reason = reason
+
+ def __repr__(self) -> str:
+ return f"<Unmirrorable {self.reason}>"
+
+
+#: The ordinary decline: whatever the mirror cannot be built from, with the
+#: engine's own comparison resolution as the reason an owner can act on.
+UNMIRRORABLE = Unmirrorable("resolution")
+
+#: A value carrying a UTC offset, declined whatever the column's resolution.
+#: A transform such as ``CAST(:value AS TIMESTAMP)`` drops the offset, so even
+#: an engine that compares the whole instant would be probed in the wrong
+#: frame -- which is not something mapping a different column fixes.
+UNMIRRORABLE_OFFSET = Unmirrorable("offset")
+
+
+def is_unmirrorable(value: Any) -> bool:
+ """Whether `mirror_probe_request` declined this request."""
+ return isinstance(value, Unmirrorable)
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+#: Declared types whose comparison ignores trailing blanks.
+#:
+#: The fixed-width character types, which the SQL standard has compare as
+#: though both sides were padded to the same length -- so ``'US'`` and
+#: ``'US '`` are equal in a ``CHARACTER(3)``, while ``lower()`` of the two is
+#: not. Spelled out rather than matched by prefix because the variable-width
+#: names start with the same letters: ``VARCHAR`` and ``CHARACTER VARYING``
+#: compare the blanks and must not land here.
+PADDED_CHARACTER_TYPES = frozenset(
+ {
+ "CHAR",
+ "NCHAR",
+ # PostgreSQL's own name for ``CHARACTER``, which is what reflection
+ # reports for a ``CHAR(n)`` column there.
+ "BPCHAR",
+ "CHARACTER",
+ "NATIONAL CHAR",
+ "NATIONAL CHARACTER",
+ }
+)
+
+
+def _is_padded_character_type(column: TableColumn) -> bool:
+ """
+ Whether ``column``'s declared type compares without its trailing blanks.
+
+ Read off the declared type rather than the engine spec's resolved one: the
+ specs map ``CHAR`` and ``VARCHAR`` onto the same `sqlalchemy.String`, so
+ the distinction this needs is gone by then. The length suffix is dropped
+ and the name matched against `PADDED_CHARACTER_TYPES`, so an unfamiliar
+ spelling answers ``False`` and the engine-level flag decides as before --
+ this gate adds a decline rather than lifting one. A column with no
+ declared type has nothing to read, and answers the same way.
+ """
+ if not isinstance(column.type, str):
+ return False
+ native = re.sub(r"\s+", " ", column.type.strip().upper())
+ return native.split("(")[0].strip() in PADDED_CHARACTER_TYPES
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ Padding is asked about per column, because it is a property of the *type*
+ rather than of the engine. ``binary_string_comparison`` speaks for an
+ engine's default text comparison, and on PostgreSQL -- which declares it
+ -- a ``CHAR(2)`` still matches a filter for ``'US '`` against a stored
+ ``'US'``, because the standard says a padded character type compares
+ without its trailing blanks. The mirror ``region_key = lower('US ')`` then
+ excludes the row. So a fixed-width character type declines whatever the
+ engine says, and an engine that ignores trailing blanks on its *variable*
+ types says so by not declaring the flag at all (see `RedshiftEngineSpec`).
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ # Ahead of the generic-type question, which a padded type can lose: the
+ # specs map ``CHARACTER`` onto no generic type at all on some engines, and
+ # a fixed-width character type is a string whether or not Superset can say
+ # so from the name.
+ if _is_padded_character_type(column):
+ return False
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error( # noqa: C901
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ And it must be a *read*. Shape is a separate question from effect: a bare
+ scalar expression can still write, so `SQLStatement.is_mutating` is asked
+ too -- the same question SQL Lab and the chart executor ask before letting
+ SQL run. See the gate itself for what that reaches and what it does not.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ # Also ahead of the parse, and for a stronger reason than cost: every gate
+ # below reasons about the parse tree, and this is the one construct that
+ # makes the parse tree describe a different statement from the one the
+ # engine runs. Checked here as well as in `validate_transform` because this
+ # is the door a row written by an earlier release still comes through.
+ if contains_executable_comment(transform):
+ return str(
+ _(
+ "A partition value transform cannot contain a MySQL "
+ "executable comment, which the database executes and every "
+ "validator reads as a comment."
+ )
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The read-only gate, which nothing above implies. The shape gates ask what
+ # the transform *selects*; this asks what evaluating it *does*, and a bare
+ # scalar expression can still write. `nextval(:value)` on PostgreSQL
+ # advances a sequence: one function call, no clause, no sub-query, and not
+ # in the default `DISALLOWED_SQL_FUNCTIONS` either -- so every gate above
+ # passes it and the probe then runs it. `setval` is the same shape, and
+ # `exp.Execute` and the opaque-`exp.Command` forms arrive the same way.
+ #
+ # The large-object writers (`lo_export`, `lowrite`, `lo_from_bytea`, ...)
+ # are caught here too, and the shipped denylist happens to name them as
+ # well -- but that is config an operator can replace, while this is not.
+ #
+ # `is_mutating` is the same question SQL Lab, `get_virtual_table_metadata`
+ # and the chart executor ask before letting SQL run, so a transform is held
+ # to the bar the rest of Superset already sets rather than to one invented
+ # here. Unconditional rather than gated on `Database.allow_dml`: a transform
+ # is a scalar function of `:value` by definition, so there is no legitimate
+ # mutating one, and the probe runs on a cache schedule nobody chose -- a
+ # write would repeat every time the entry expired.
+ #
+ # It bears saying what this does not reach. A user-defined function whose
+ # body writes is a plain call no parser can tell from `lower(:value)`, and
+ # `is_mutating`'s function-name walk is PostgreSQL-only by design, since the
+ # same names are read-only elsewhere. Neither residual is specific to this
+ # feature -- a dataset editor can already have the engine evaluate an
+ # arbitrary expression through a calculated column or a virtual dataset's
+ # SQL -- and closing them means authorizing the preview against the
+ # database, not parsing harder.
+ if statement.is_mutating():
Review Comment:
`is_mutating()` only recognises function calls, and the comment above promises that no mutating transform gets through. On Oracle, `orders_seq.NEXTVAL + :value` parses as a column reference, so it passes every gate; with a numeric mapped column, a numeric partition column and sample `1` the preview probe runs `SELECT orders_seq.NEXTVAL + 1 FROM DUAL` and advances the sequence, again on every cache expiry, for a dataset editor with no SQL Lab or DML grant. Could pseudo-columns such as `NEXTVAL` be refused here or added to the denylist for Oracle?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4175105710
##########
superset/models/helpers.py:
##########
@@ -5602,6 +5831,11 @@ def get_sqla_query( # pylint: disable=too-many-arguments,too-many-locals,too-ma
# col_obj is None and sqla_col is None - column not found!
# Silently skip - this can happen for removed columns or invalid filters
pass
+ if partition_mapping is not None:
+ where_clause_and += self._build_partition_mirror_predicates(
Review Comment:
These outer-window partition predicates also enter the series-limit subquery through `where_clause_and`, but relative time comparisons rank series using different `inner_from_dttm`/`inner_to_dttm` bounds. A January 2025 comparison can therefore rank January 2026 timestamps while requiring January 2025 partition keys, producing an empty ranking and dropping the comparison series; could each query window build its own mirrors?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,1314 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` always -- ``T`` is a function
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import re
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLStatement
+from superset.utils import json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: Every entry point enforces it -- the typed column field, the import schema
+#: and the preview request -- because `is_transform_active` parses the stored
+#: value on each Explore load, and an unbounded string would make that parse
+#: the expensive part of rendering a chart.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+def mirrorable_operators(is_monotonic: bool) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ """
+ if is_monotonic:
+ return MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+ return set(MIRRORABLE_ALWAYS)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(self.is_monotonic)
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+ """
+ return VALUE_PLACEHOLDER_RE.sub(_PARSE_STANDIN, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(transform: str, engine: str) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
Review Comment:
A transform such as `secret || :value FROM vault` passes the single-expression and subquery checks even with `ALLOW_ADHOC_SUBQUERY` disabled, then executes as `SELECT secret || 'us' FROM vault AS v0`, exposing another table's contents through the preview. Could this require an expression-only AST with no FROM or other statement clauses before running the probe?
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/DatasourceEditor.tsx:
##########
@@ -1250,6 +1356,124 @@ function DatasourceEditor({
[],
);
+ // Which column's row expand to open, for the "map a different column" links.
+ // Consumed by the Columns tab, which scrolls the row into view and expands it.
+ //
+ // Carries a nonce because the request is an event, not a state: clicking the
+ // same link twice -- after collapsing the row by hand in between -- asks for
+ // the same column name, and a bare string would make the second
+ // `setColumnToReveal` a no-op. React would bail out of the render, nothing
+ // downstream would see a change, and the row would stay shut.
+ const [columnToReveal, setColumnToReveal] = useState<{
+ name: string;
+ nonce: number;
+ } | null>(null);
+
+ const handlePartitionColumnChange = useCallback(
+ (columnName: string | null) => {
+ setDatasource(prev => ({
+ ...prev,
+ partition_column: columnName,
+ partition_mapped_column: nextMappedColumnOverride(
+ prev.partition_mapped_column,
+ columnName,
+ ),
+ }));
+ if (columnName) {
+ setDatabaseColumns(prev =>
+ applyPartitionColumnDefaults(prev, columnName),
Review Comment:
These partition defaults and the edited transform live in `databaseColumns`, but `syncMetadata` merges source metadata with the older local `datasource.columns`. Configuring the mapping and then syncing unchanged source columns before saving restores the old transform, monotonicity and picker flags, so the save loses those edits; could sync merge against the current column state?
##########
superset/commands/dataset/importers/v1/utils.py:
##########
@@ -267,6 +272,72 @@ def _get_template_params(dataset: SqlaTable) -> dict[str, Any]:
return params if isinstance(params, dict) else {}
+def drop_unusable_partition_transforms(config: dict[str, Any]) -> None:
+ """
+ Drop a partition value transform the save path would have rejected.
+
+ Import is the one door into this field that does not go through
+ `UpdateDatasetCommand`, so a bundle can carry a transform holding Jinja or
+ calling a non-deterministic function -- one that will never mirror a filter,
+ and that the editor can only report as broken after the fact. Dropping it on
+ the way in leaves the column with no transform, a state an owner can see and
+ fix, rather than a stored expression that looks configured and is not.
+
+ Deliberately sanitizes rather than raises. A bundle is imported as a whole,
+ and failing someone's entire dataset over one unusable expression is a worse
+ trade than importing the dataset without it. This is the same bargain
+ `DatasetDAO.clear_dangling_partition_mapping` already strikes for a mapping
+ whose column went away.
+
+ Two kinds of check, and only one of them answers to the feature flag. The
+ usability checks ask whether a transform will ever mirror a filter, which
+ is a question about a live feature; with the flag off nothing mirrors, so
+ rewriting the bundle would discard configuration for no gain. The
+ structural check asks whether the expression is one this product stores at
+ all, and that answer does not change with a flag -- an import written while
+ the flag was off would otherwise sit in the metadata DB fully armed,
+ waiting for an operator to turn the flag on.
+ """
+ columns = config.get("columns")
+ if not columns:
+ return
+ if not any(column.get("partition_value_transform") for column in columns):
+ return
+
+ database = db.session.query(Database).filter_by(id=config["database_id"]).first()
+ if database is None:
+ return
+
+ check_usability = is_feature_enabled(PARTITION_FILTER_MAPPING)
+ catalog = config.get("catalog")
+ schema = config.get("schema")
+
+ for column in columns:
+ transform = column.get("partition_value_transform")
+ if not transform:
+ continue
+
+ reasons: list[str] = []
+ if reason := stored_expression_error(database, catalog, schema, transform):
Review Comment:
PUT deliberately saves an unfinished transform such as `unix_timestamp(:value` as inactive, but exporting and importing that unchanged dataset hits this parse rejection and silently replaces the transform with null, even with the feature disabled. Could import preserve the same non-blocking inactive state instead of discarding configuration that PUT accepts?
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/useDebouncedCommit.ts:
##########
@@ -0,0 +1,100 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { debounce } from 'lodash-es';
+import { Constants } from '@superset-ui/core/components';
+
+/**
+ * Local text state that commits upward on a debounce.
+ *
+ * The dataset editor's commit path is asynchronous and snapshot-based: a value
+ * handed to `onChange` travels Field -> Fieldset -> CollectionTable ->
+ * DatasourceEditor -> DatasourceModal and arrives back on the `value` prop
+ * several renders later, and the callback that commits it was built during an
+ * earlier render. An input driven straight off that prop therefore loses any
+ * keystroke that lands while a commit is in flight -- which is why every other
+ * control in the editor types into local state and commits on a debounce, and
+ * why Fieldset's own comment says the editor assumes exactly that. This is
+ * TextControl's contract (src/explore/components/controls/TextControl), minus
+ * the ControlHeader and the number parsing this field does not want.
+ */
+export function useDebouncedCommit(
+ value: string | null | undefined,
+ commit: (next: string) => void,
+ delay: number = Constants.FAST_DEBOUNCE,
+) {
+ const [localValue, setLocalValue] = useState(value ?? '');
+ const [prevValue, setPrevValue] = useState(value);
+ // What was last handed to `commit`. A commit's own echo arrives as a prop
+ // change like any other, and the re-seed below cannot tell the two apart --
+ // so a commit landing while typing continues (a blur or Enter flushes
+ // immediately) used to reset the input to the committed text and drop every
+ // keystroke since. State rather than a ref because the re-seed reads it
+ // during render, which is exactly what a ref is not for.
+ const [lastCommitted, setLastCommitted] = useState<string | undefined>(
+ undefined,
+ );
+
+ // The commit fires from a timer, so the callback is handed in at call time
+ // rather than captured when the debounce was built -- otherwise it would
+ // close over whichever render happened to create it, and fire a stale
+ // callback that writes to a superseded owner.
+ const debouncedCommit = useRef(
+ debounce((next: string, commitFn: (value: string) => void) => {
+ setLastCommitted(next);
+ commitFn(next);
+ }, delay),
+ );
+
+ useEffect(() => () => debouncedCommit.current.cancel(), []);
+
+ const onChange = useCallback(
+ (next: string) => {
+ setLocalValue(next);
+ debouncedCommit.current(next, commit);
Review Comment:
This queues the commit callback from the input event, whose `CollectionTable.onFieldsetChange` still captures the whole column collection. With two rows expanded, a description edit committing before a queued transform edit can be reverted when that transform commits through the older collection snapshot; could the delayed commit merge into the latest collection, with both rows' edits covered together?
##########
superset/daos/dataset.py:
##########
@@ -476,10 +546,98 @@ def _validate_column_date_formats(
"python_date_format is an invalid date/timestamp format."
)
+ @staticmethod
+ def clear_unmapped_partition_transforms(model: SqlaTable) -> None:
+ """
+ Drop the value transform from every column the mapping does not mirror.
+
+ A mapping has exactly one mirrored column, so at most one column may
+ carry a transform. A transform parked on any other column is invisible
+ -- no row but the mapped one renders one -- yet it is still stored, and
+ it goes live the moment the mapped column resolves back to it. Clearing
+ an override is enough to do that: a null `partition_mapped_column` means
+ "follow `main_dttm_col`", so dropping a mapping would otherwise activate
+ whatever the default datetime column happened to be holding, turning a
+ request to remove a mapping into a request to add a different one.
+
+ Enforced here rather than in the editor alone because the editor is only
+ one writer: a PUT, an `override_columns=true` metadata sync and an
+ import all reach the columns directly. The same argument
+ `clear_dangling_partition_mapping` makes about dangling columns.
+
+ `DatasetDAO.update` calls this twice, before and after it applies the
+ request, and the reason is here rather than only at the call site: this
+ reads the mapping as it stands, so a single call can only enforce the
+ invariant against one of the two resolutions a mapping change has.
+
+ Gated on the feature flag, unlike its sibling, because this discards
+ stored configuration rather than repairing a broken reference. With the
+ flag off nothing mirrors, so there is no armed mapping to disarm and
+ clearing would be pure loss.
+ """
+ if not feature_flag_manager.is_feature_enabled(PARTITION_FILTER_MAPPING_FLAG):
+ return
+
+ mapped_column = (
+ (model.partition_mapped_column or model.main_dttm_col)
+ if model.partition_column
+ else None
+ )
+ # `_upsert_columns` and `_override_columns` insert a new column with
+ # `db.session.add(TableColumn(..., table_id=model.id))` rather than
+ # appending to this relationship, and `BaseDAO.update` does not flush --
+ # so a column created *and* given a transform in the same request was
+ # invisible here and kept it. That is exactly the stray transform this
+ # method exists to clear, waiting for the mapping to resolve back to it.
+ db.session.flush()
+ db.session.expire(model, ["columns"])
+ for column in model.columns:
+ if column.column_name == mapped_column:
+ continue
+ if (
+ column.partition_value_transform
+ or column.partition_transform_is_monotonic
+ ):
+ column.partition_value_transform = None
+ column.partition_transform_is_monotonic = False
+
+ @staticmethod
+ def clear_dangling_partition_mapping(
+ model: SqlaTable, surviving_column_names: set[str]
+ ) -> None:
+ """
+ Drop parts of the partition filter mapping whose columns no longer exist.
+
+ A metadata sync can remove the partition column at the source, which
+ would otherwise leave the dataset pointing at a column that isn't there.
+ The query layer bails out defensively on a dangling mapping, so this is
+ about the dataset's stored state being honest rather than about
+ correctness of the SQL.
+
+ Called from `update_columns` for both write paths: the editor clears the
+ mapping client-side too, but `override_columns=true` (an API-driven
+ metadata sync) bypasses the editor entirely, and the upsert path drops
+ every column the payload omits, so either one can take the mapped
+ column out from under the mapping.
+ """
+ if (
Review Comment:
When one PUT renames the partition column from `old_part` to `new_part` and updates `partition_column`, this child-update cleanup still sees the old reference and clears the surviving `partition_mapped_column='country'`. Scalar updates restore only the partition column, and the subsequent cleanup deletes country's transform, silently switching the mapping to the main datetime column; could cleanup use the final requested references instead?
##########
superset/models/helpers.py:
##########
@@ -4290,36 +4297,153 @@ def dttm_sql_literal(self, dttm: datetime, col: "TableColumn") -> str:
return f"""'{dttm.strftime("%Y-%m-%d %H:%M:%S.%f")}'"""
- def get_time_filter( # pylint: disable=too-many-arguments # noqa: C901
+ def _collect_partition_mirror_range(
self,
- time_col: "TableColumn",
+ mapping: Optional["PartitionMapping"],
+ sink: list[tuple[utils.FilterOperator, Any]],
+ column_name: str,
start_dttm: Optional[sa.DateTime],
end_dttm: Optional[sa.DateTime],
- time_grain: Optional[str] = None,
- label: Optional[str] = "__time",
- template_processor: Optional[BaseTemplateProcessor] = None,
- ) -> Optional[ColumnElement]:
- col = (
- time_col.get_timestamp_expression(
- time_grain=time_grain,
- label=label,
- template_processor=template_processor,
- )
- if time_grain
- else self.convert_tbl_column_to_sqla_col(
- time_col, label=label, template_processor=template_processor
- )
+ widen_bounds_by: Optional[relativedelta] = None,
+ ) -> None:
+ """
+ Record a time range for mirroring onto the partition column.
+
+ The bounds are adjusted first, by the same helper `get_time_filter` uses:
+ the mirrored predicate has to describe the same instants as the
+ timestamp predicate it stands in for, or the pruning is wrong by exactly
+ the dataset's timezone offset -- silently.
+
+ Either bound may be `None` for an open-ended range, in which case only
+ the bound that exists is mirrored.
+
+ `widen_bounds_by` is one grain bucket width, passed when the filter this
+ stands in for compares a *truncated* column. The real predicate then
+ keeps rows the raw bounds exclude, and widening both ends by one bucket
+ is the smallest range guaranteed to contain all of them -- see the "Time
+ grains" section of `superset.connectors.sqla.partition_mapping`. Note
+ the widened upper bound is `<=` rather than `<`: `ts < until + width`
+ only gives `T(ts) <= T(until + width)` for a transform that is monotonic
+ but not strictly so, such as `unix_timestamp` on a sub-second column.
+
+ A widened range can also be wide enough to fail `_bounds_are_ordered`
+ against a tighter filter on the same column. That fails open -- no
+ mirroring, no pruning, no dropped rows.
+ """
+ if mapping is None or column_name != mapping.mapped_column:
+ return
+ if not mapping.mirrors(utils.FilterOperator.TEMPORAL_RANGE):
+ return
+
+ # Resolve the column so the offset adjustment sees the same type
+ # `get_time_filter` does -- an offset the column's type cannot represent
+ # is dropped, and the mirrored bounds have to agree with the originals.
+ mapped_col = next(
+ (col for col in self.columns if col.column_name == column_name), None
)
+ start_dttm, end_dttm = self.adjust_time_bounds(start_dttm, end_dttm, mapped_col)
+
+ # Adjust first, then widen. `adjust_time_bounds` moves the naive UI
+ # bounds into the frame the column is *stored* in, and the grain
+ # truncation in the real predicate happens in that same frame, so the
+ # bucket width has to be added there too. The two commute for the
+ # hour-offset branch but not for the `ZoneInfo` one, where widening
+ # across a DST boundary first lands an hour out.
+ upper_operator = utils.FilterOperator.LESS_THAN
+ if widen_bounds_by is not None:
+ if start_dttm is not None:
+ start_dttm -= widen_bounds_by
+ if end_dttm is not None:
+ end_dttm += widen_bounds_by
+ upper_operator = utils.FilterOperator.LESS_THAN_OR_EQUALS
+
+ if start_dttm is not None:
+ sink.append((utils.FilterOperator.GREATER_THAN_OR_EQUALS, start_dttm))
Review Comment:
The probe uses this Python datetime, while the original filter renders it through `dttm_sql_literal` and the engine's `convert_dttm`, so the bounds can differ: SQLite truncates a `.500000` lower bound to whole seconds, but a `julianday(:value)` mirror keeps `.500000` and drops a matching `.250000` row. Could mirroring transform the same typed temporal literal used by the original predicate?
##########
superset/datasets/api.py:
##########
@@ -323,6 +401,8 @@ class DatasetRestApi(SoftDeleteApiMixin, BaseSupersetModelRestApi):
]
show_columns = show_select_columns + [
"columns.type_generic",
+ # Engine-supplied pre-fill for the editor's value transform input.
+ "partition_value_transform_default",
Review Comment:
Saving the dataset from Explore reloads this GET response and replaces the Explore datasource with it, but the response omits `partition_filter_mapping`. The pruning indicators consequently disappear after an unrelated save even though queries still mirror filters; could this expose the same mapping summary as `SqlaTable.data` and cover that save/reload boundary?
##########
superset/commands/dataset/create.py:
##########
@@ -248,5 +253,52 @@ def validate(self) -> None: # noqa: C901
# so a ``viewers`` key would be dropped by the DAO's ``setattr`` loop.
populate_subjects(self._properties, exceptions, include_viewers=False)
+ self._validate_partition_mapping(exceptions)
+
if exceptions:
raise DatasetInvalidError(exceptions=exceptions)
+
+ def _validate_partition_mapping(self, exceptions: list[ValidationError]) -> None:
+ """
+ Reject a partition mapping that cannot work, at create time too.
+
+ `UpdateDatasetCommand` has validated this since the mapping landed, but
+ create did not, so the same mapping accepted on POST and rejected on PUT
+ was reachable -- and once stored it is only reported as broken by the
+ editor, which an API-only caller never opens.
+
+ What create can check is narrower than what update can. The dataset's
+ columns are synced by `fetch_metadata` *after* this runs, so "is that a
+ real column?" has no answer yet; both submitted names are therefore
+ passed as known so the existence checks pass trivially and the checks
+ that do not need a column list still run. There is no column payload on
+ POST either, so no transform can arrive here to validate.
+ """
+ if not is_feature_enabled(PARTITION_FILTER_MAPPING):
+ return
+
+ partition_column = self._properties.get("partition_column")
+ database = self._properties.get("database")
+ if not partition_column or not database:
+ # No database means the caller already has a
+ # `DatabaseNotFoundValidationError`; there is no engine to validate
+ # a mapping against and no value in a second error about it.
+ return
+
+ partition_mapped_column = self._properties.get("partition_mapped_column")
+ for issue in validate_partition_mapping(
+ column_names={
+ name
+ for name in (partition_column, partition_mapped_column)
+ if name is not None
+ },
+ partition_column=partition_column,
+ partition_mapped_column=partition_mapped_column,
+ main_dttm_col=None,
Review Comment:
Passing `main_dttm_col=None` lets POST accept `partition_column='event_time'` without an override when metadata subsequently selects that same column as the default datetime column. The resulting self-mapping then makes even a description-only PUT fail validation; could create validate the effective mapping after metadata supplies the default?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,1314 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` always -- ``T`` is a function
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import re
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLStatement
+from superset.utils import json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: Every entry point enforces it -- the typed column field, the import schema
+#: and the preview request -- because `is_transform_active` parses the stored
+#: value on each Explore load, and an unbounded string would make that parse
+#: the expensive part of rendering a chart.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+def mirrorable_operators(is_monotonic: bool) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ """
+ if is_monotonic:
+ return MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+ return set(MIRRORABLE_ALWAYS)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(self.is_monotonic)
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+ """
+ return VALUE_PLACEHOLDER_RE.sub(_PARSE_STANDIN, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(transform: str, engine: str) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def stored_expression_error(
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ The same subquery, function-denylist and RLS policy every other stored
+ expression goes through, applied to a value transform. It matters more
+ here than the name suggests: `build_probe_sql` binds only `:value` and
+ splices the rest of the transform in as SQL text, which the engine then
+ executes, so an ungated transform is arbitrary SQL. A dataset editor
+ without SQL Lab could store `(SELECT secret FROM protected_table LIMIT 1)
+ || :value` and read the answer back out of the emitted predicate.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+ """
+ selections = []
+ for index, value in enumerate(values):
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ compiled = clause.compile(
+ dialect=dialect,
+ compile_kwargs={"literal_binds": True},
+ )
+ selections.append(f"{compiled} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ database.db_engine_spec.select_without_from_suffix,
+ )
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ row = frame.iloc[0]
Review Comment:
Reading the probe through `frame.iloc[0]` coerces mixed numeric columns to a common float dtype. On SQLite, `CAST(:value AS NUMERIC)` for an IN filter containing `'9007199254740993'` and `'1.5'` changes the first exact result to `9007199254740992.0`, so the mirror drops a matching row; could each probe cell be read without row-wide dtype coercion?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(explore): indicate when a filter is mirrored onto a partition column [superset]
Posted by "netlify[bot] (via GitHub)" <gi...@apache.org>.
netlify[bot] commented on PR #43870:
URL: https://github.com/apache/superset/pull/43870#issuecomment-5541518713
### <span aria-hidden="true">✅</span> Deploy Preview for *superset-docs-preview* ready!
| Name | Link |
|:-:|------------------------|
|<span aria-hidden="true">🔨</span> Latest commit | 949b0afdd82fdd0bac25469ed2c2fbec56757fdb |
|<span aria-hidden="true">🔍</span> Latest deploy log | https://app.netlify.com/projects/superset-docs-preview/deploys/6a9ace32a8253a00082f3d15 |
|<span aria-hidden="true">😎</span> Deploy Preview | [https://deploy-preview-43870--superset-docs-preview.netlify.app](https://deploy-preview-43870--superset-docs-preview.netlify.app) |
|<span aria-hidden="true">📱</span> Preview on mobile | <details><summary> Toggle QR Code... </summary><br /><br /><br /><br />_Use your smartphone camera to open QR code link._</details> |
|<span aria-hidden="true">🤖</span> Make changes | [Run an agent on this branch](https://app.netlify.com/projects/superset-docs-preview/agent-runs#DYpbCoAgEADvst9JpijWDTrG5iOFfCAFRXT3dr6GYV5oveZ2wgIwwNax2Egerz0SYwuZaebvdtTuWSouWTxrp9V5as_qaNY4o_VSoBFKIufciCDdpOD7AQ) |
---
<!-- [superset-docs-preview Preview](https://deploy-preview-43870--superset-docs-preview.netlify.app) -->
_To edit notification comments on pull requests, go to your [Netlify project configuration](https://app.netlify.com/projects/superset-docs-preview/configuration/notifications#deploy-notifications)._
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(explore): indicate when a filter is mirrored onto a partition column [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #43870:
URL: https://github.com/apache/superset/pull/43870#issuecomment-5541487939
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "eschutho (via GitHub)" <gi...@apache.org>.
eschutho commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4235123713
##########
superset/models/helpers.py:
##########
@@ -4334,36 +4432,715 @@ def dttm_sql_literal(self, dttm: datetime, col: "TableColumn") -> str:
return f"""'{dttm.strftime("%Y-%m-%d %H:%M:%S.%f")}'"""
- def get_time_filter( # pylint: disable=too-many-arguments # noqa: C901
+ def _mirror_probe_value(self, dttm: datetime, col: Optional["TableColumn"]) -> Any:
+ """
+ ``dttm`` in the mapped column's own stored representation.
+
+ The predicate this mirror stands in for compares the column against
+ `dttm_sql_literal(dttm, col)`, so the transform has to be probed with
+ the same value. On a column stored as an epoch integer, ``T`` is a
+ function of an integer: probing it with a `datetime` either returns
+ something unrelated to the partition keys or raises, and a raise costs
+ the dataset its pruning silently.
+
+ Only the ``python_date_format`` branches of `dttm_sql_literal` are
+ reproduced, because only those produce a *value*. `convert_dttm` yields
+ engine-specific SQL text, which cannot be bound as a parameter; its own
+ divergence from the probe is handled by widening the bounds instead
+ (`_engine_literal_resolution`).
+
+ In `dttm_sql_literal`'s own order, though: it asks ``convert_dttm``
+ first and reaches the format only when the engine answers nothing. A
+ column can carry both -- a TIMESTAMP with a ``%Y%m%d``
+ ``python_date_format``, or an entry in
+ ``python_date_format_by_column_name`` -- and applying the format
+ unconditionally probed a value the real predicate never compares.
+ ``event_time >= '2026-01-01 00:00:00'`` mirrored as
+ ``partition_col >= '20260101'``, and a January 15 row keyed
+ ``2026-01-15`` sorts below that string, so the chart lost a row the
+ filter keeps.
+
+ Where the engine does answer, the `datetime` is returned unchanged and
+ the widening path takes over -- which is exactly what already happens
+ for every temporal column that carries no format at all.
+ """
+ if col is None:
+ return dttm
+
+ if col.type and self.db_engine_spec.convert_dttm(
+ col.type, dttm, db_extra=self.db_extra
+ ):
+ # The format is unreachable in `dttm_sql_literal` for this column,
+ # so reproducing it here would describe a different bound.
+ return dttm
+
+ tf = col.python_date_format
+ if not tf and self.db_extra:
+ tf = self.db_extra.get("python_date_format_by_column_name", {}).get(
+ col.column_name
+ )
+ if not tf:
+ return dttm
+
+ if tf in EPOCH_FORMATS:
+ dttm_tz_aware = dttm
+ if dttm_tz_aware.tzinfo is None:
+ dttm_tz_aware = dttm_tz_aware.replace(tzinfo=timezone.utc)
+ return int(dttm_tz_aware.timestamp()) * EPOCH_FORMATS[tf]
+ return dttm.strftime(tf)
+
+ def _engine_literal_resolution(
+ self, dttm: datetime, col: Optional["TableColumn"]
+ ) -> LiteralResolution:
+ """
+ How much of ``dttm`` survives into this engine's literal for ``col``.
+
+ The real predicate compares `dttm_sql_literal(dttm, col)`, so whatever
+ that literal throws away is a bound the engine never sees. A mirror
+ derived from the full precision then describes a *narrower* range than
+ the predicate it stands in for -- and narrower means it drops rows the
+ filter keeps.
+
+ Two things get thrown away in practice:
+
+ - the sub-second part. SQLite renders a timestamp with
+ ``timespec="seconds"``.
+ - the time of day entirely. Every engine spec with a ``types.Date``
+ branch renders ``dttm.date().isoformat()``, so Presto, Trino,
+ BigQuery and some two dozen others answer `DATE '2026-01-01'` for a
+ bound of 10:00 -- and `T(DATE '2026-01-01')` is below the mirror's
+ own lower bound, so the whole first day is dropped.
+
+ Detected rather than enumerated per engine, because the branch depends
+ on the column's type as well as the spec: instants differing only in the
+ part under test render as the same text exactly when the engine has
+ thrown that part away.
+
+ The day test uses two fixed times of day rather than ``dttm`` and one
+ alternative, so a bound that happens to sit on the hour the alternative
+ uses cannot read as "no time at all". Neither probe sits at midnight on
+ purpose: SQLite renders a DATE column at exactly midnight as a bare
+ date, so a midnight probe would differ from its alternative for a
+ reason that has nothing to do with resolution.
+
+ Likewise both sub-second probes carry a non-zero remainder. Comparing
+ against ``dttm`` truncated to the second looks like the obvious test and
+ is wrong for the same formatting-boundary reason.
+
+ A non-temporal column has no answer here, and asking anyway gets a wrong
+ one. SQLite's ``convert_dttm`` renders for ``types.String`` as well as
+ for the date types, so a ``VARCHAR`` mapped column reads as
+ second-resolution -- and a filter value that happens to *look* like an
+ instant then has its bound rounded as though the engine had truncated
+ it. On a VARCHAR ``code`` mapped onto a VARCHAR ``p`` by ``:value``,
+ ``code < '2026-07-06T10:08:11.500000'`` was mirrored as
+ ``p <= '2026-07-06 10:08:12.000000'``; a space sorts before ``T``, so a
+ row holding ``2026-07-06T09:00:00`` fell outside the mirror while
+ matching the filter.
+
+ The guard lives here rather than in each caller so this and
+ `_column_literal_resolution` cannot disagree about which column is
+ coarse -- which is the same reason that helper delegates to this one.
+
+ "Temporal" is the column's generic type, not just its ``is_dttm`` flag.
+ `get_time_filter` renders a bound through ``convert_dttm`` for any
+ ``DATE`` column, flagged or not, so a ``DATE`` column left unflagged
+ still compares a bare day -- and skipping the resolution check there
+ would hand the probe 10:00 for a bound the engine reads as midnight.
+ """
+ if col is None or not col.type or col.type_generic != GenericDataType.TEMPORAL:
+ return LiteralResolution.FULL
+
+ def render(moment: datetime) -> Optional[str]:
+ return self.db_engine_spec.convert_dttm(
+ col.type, moment, db_extra=self.db_extra
+ )
+
+ try:
+ early = render(dttm.replace(hour=1, minute=2, second=3, microsecond=444444))
+ late = render(
+ dttm.replace(hour=22, minute=33, second=44, microsecond=555555)
+ )
+ if early is not None and early == late:
+ return LiteralResolution.DAY
+
+ # Flooring to the second is a no-op on a bound that has no
+ # sub-second part, so there is nothing to detect.
+ if not dttm.microsecond:
+ return LiteralResolution.FULL
+
+ first = render(dttm.replace(microsecond=111111))
+ second = render(dttm.replace(microsecond=222222))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return LiteralResolution.FULL
+
+ if first is not None and first == second:
+ return LiteralResolution.SECOND
+ return LiteralResolution.FULL
+
+ def _round_bounds_outward(
self,
- time_col: "TableColumn",
+ start_dttm: Optional[datetime],
+ end_dttm: Optional[datetime],
+ col: Optional["TableColumn"],
+ ) -> tuple[Optional[datetime], Optional[datetime]]:
+ """
+ The bounds widened to whatever the engine's literal actually resolves to.
+
+ Rounding outward is never narrower than the predicate being mirrored,
+ which is the only property the mirror has to hold.
+ """
+ resolutions = {
+ self._engine_literal_resolution(bound, col)
+ for bound in (start_dttm, end_dttm)
+ if bound is not None
+ }
+
+ if LiteralResolution.DAY in resolutions:
+ # The engine compares a bare date, so the real predicate's lower
+ # bound is the start of that day and its upper bound admits the
+ # whole of the day before. Anything finer excludes rows it keeps.
+ if start_dttm is not None:
+ start_dttm = start_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ )
+ if end_dttm is not None and end_dttm != end_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ ):
+ end_dttm = end_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ ) + timedelta(days=1)
+ elif LiteralResolution.SECOND in resolutions:
+ if start_dttm is not None:
+ start_dttm = start_dttm.replace(microsecond=0)
+ if end_dttm is not None and end_dttm.microsecond:
+ end_dttm = end_dttm.replace(microsecond=0) + timedelta(seconds=1)
+
+ return start_dttm, end_dttm
+
+ def _literal_is_coarser_than(
+ self, dttm: datetime, col: Optional["TableColumn"]
+ ) -> bool:
+ """
+ Whether the engine's literal for ``dttm`` throws away part of it.
+
+ Unlike a range, an equality cannot be widened outward, so the only safe
+ answer when the engine compares less than the full value is to decline
+ the mirror.
+ """
+ resolution = self._engine_literal_resolution(dttm, col)
+ if resolution is LiteralResolution.DAY:
+ return dttm != dttm.replace(hour=0, minute=0, second=0, microsecond=0)
+ if resolution is LiteralResolution.SECOND:
+ return bool(dttm.microsecond)
+ return False
+
+ def _column_literal_resolution(
+ self, col: Optional["TableColumn"]
+ ) -> LiteralResolution:
+ """
+ How much of *any* value this engine compares on ``col``.
+
+ `_engine_literal_resolution` answers about a particular instant, which
+ is what a mirror derived from one needs. Two callers have no instant to
+ ask about -- the summary the Explore glyph reads, and a filter value
+ `_instant_from_filter_value` cannot read as an instant at all -- and
+ both need the column's own answer. Through one helper so that the glyph
+ and the query path cannot disagree about which column is coarse, which
+ is the same reason `mirrorable_operators` is computed once.
+
+ A non-temporal column has no answer, and asking anyway gets a wrong one:
+ SQLite's ``convert_dttm`` renders for ``types.String`` as well as for the
+ date types, so a reference instant makes a ``VARCHAR`` mapped column look
+ second-resolution -- and ``country = 'US'``, the text half of this
+ feature, reads as a value the engine compares coarsely.
+
+ That guard is `_engine_literal_resolution`'s, not this function's. It
+ used to be here, on the belief that the per-instant callers never met
+ the case because they arrive only with a value that parsed as an
+ instant -- which is untrue of a text column holding ISO-shaped text,
+ where the value parses and the column is still not temporal.
+ """
+ return self._engine_literal_resolution(_RESOLUTION_REFERENCE_INSTANT, col)
+
+ def _round_bound_outward(
+ self,
+ instant: datetime,
+ col: Optional["TableColumn"],
+ *,
+ is_upper: bool,
+ ) -> datetime:
+ """
+ One bound widened to whatever the engine resolves ``col`` to.
+
+ `_round_bounds_outward` answers for a since/until pair, because a time
+ range is the shape it was written for. A single comparison is one end of
+ such a pair with the other end absent, and the widening is per-end
+ already -- a lower bound moves back, an upper bound forward.
+
+ Narrowing the return type is the other half of the point: a bound handed
+ in non-`None` comes back non-`None`, and saying so here saves every
+ caller from re-establishing it.
+ """
+ start_dttm, end_dttm = self._round_bounds_outward(
+ None if is_upper else instant,
+ instant if is_upper else None,
+ col,
+ )
+ rounded = end_dttm if is_upper else start_dttm
+ return rounded if rounded is not None else instant
+
+ def _in_column_number_type(self, value: Any, col: Optional["TableColumn"]) -> Any:
+ """
+ A numeric ``value`` in the number type the mapped column stores.
+
+ The engine compares a number against the column in the column's own
+ domain, so ``n = '1.0'`` on an integer ``n`` matches the row holding
+ ``1``. `filter_values_handler` hands over ``1.0``, though, and a
+ transform whose output depends on the representation --
+ ``CAST(:value AS TEXT)`` answers ``'1.0'`` where the row's key is
+ ``'1'`` -- then mirrors to a partition value no matching row holds.
+ Probing at the value the column would hold keeps ``T(col) = T(v)``.
+
+ Only lossless conversions: an integral number for an integer column, a
+ number a float represents exactly for a float column. Anything else is
+ returned unchanged -- a non-integral value on an integer column matches
+ no row, so its mirror cannot drop one, and a ``DECIMAL`` column's text
+ depends on a scale the spec does not expose.
+ """
+ if (
+ col is None
+ or not col.type
+ or isinstance(value, bool)
+ or not isinstance(value, (int, float, Decimal))
+ ):
+ return value
+ try:
+ column_spec = self.db_engine_spec.get_column_spec(
+ col.type, db_extra=self.db_extra
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return value
+ if column_spec is None:
+ return value
+ sqla_type = column_spec.sqla_type
+ type_class = sqla_type if isinstance(sqla_type, type) else type(sqla_type)
+ if issubclass(type_class, sa.Integer):
+ if isinstance(value, int):
+ return value
+ try:
+ return int(value) if value == int(value) else value
+ except (OverflowError, ValueError):
+ # Infinity and NaN have no integer, and match no integer row.
+ return value
+ if issubclass(type_class, sa.Float) and float(value) == value:
+ return float(value)
+ return value
+
+ def _mirror_probe_input(
+ self,
+ operator: utils.FilterOperator,
+ value: Any,
+ col: Optional["TableColumn"],
+ ) -> Any:
+ """
+ ``value`` in the representation the mirror may probe the transform at.
+
+ A simple filter on a temporal column carries a *string*.
+ `filter_values_handler` rewrites only an all-digit value, which it reads
+ as epoch milliseconds, so ``'2026-07-06 10:08:11'`` reaches here exactly
+ as the chart author typed it and is bound as text. The engine compares
+ that text against the column under its own cast, and on a ``DATE``
+ column the cast drops the time of day: the filter keeps the whole of
+ 2026-07-06 while a mirror probed at 10:08:11 keeps one instant of it,
+ which is narrower than the predicate it stands in for.
+
+ So the text is read back into the instant it denotes -- the only way
+ `_engine_literal_resolution`, which answers about a `datetime`, reaches
+ a filter value at all -- and where the engine compares less of that
+ instant than the filter carries, what to do about it is a property of
+ the *operator*:
+
+ * a bound rounds outward, through the helper the range collector uses.
+ Reading one extra bucket at the edge is the trade this feature makes
+ everywhere else too -- see `mirror_operator` -- and the original
+ predicate is still in the query to exclude the rows that bucket adds.
+ * an equality, or one member of an ``IN`` list, has nowhere to widen to.
+ These entries are ``AND``-ed onto the query, so "or the day either
+ side" is not something this sink can express, and the request is
+ declined with `_UNMIRRORABLE`. The query is then correct and unpruned,
+ which is the one failure mode this feature is allowed.
+
+ An instant carrying a UTC offset is declined for every operator, a
+ bound included. Rounding one outward would first have to place it in the
+ frame the partition column was written in, and guessing that frame is
+ how a mirror ends up a whole offset narrower than the filter -- see the
+ load-bearing assumption in
+ `superset.connectors.sqla.partition_mapping`.
+
+ A *string* `_instant_from_filter_value` cannot read at all is declined on
+ the same terms, and for the same reason one more step back: there is no
+ instant to round. ``'07/06/2026 10:08:11'`` is not ISO 8601, so the
+ parser leaves it alone -- and Postgres casts that same text to a DATE and
+ keeps the whole of July 6 while the probe, handed the string verbatim,
+ evaluates the transform at 10:08:11 and asks for a partition key no row
+ holds. That is exactly the narrowing the ISO-only parser was written to
+ prevent, reached through a value it declines to read, so the decline has
+ to travel with it. Which costs a non-ISO *date* its pruning too, because
+ telling July 6 from June 7 is the guess that started this.
+
+ Only a string. `_as_probe_input` has already run, so the engine SQL
+ `filter_values_handler` returns for an epoch-millisecond bound arrives
+ here as a `RawProbeValue` rather than text -- and that literal was
+ rendered by the engine at the engine's own resolution, so it is the one
+ thing on this path with nothing left to resolve.
+
+ Where the engine compares the whole instant, a string is returned
+ exactly as it arrived -- down to the type the probe binds and the cache
+ key it lands on, because every query that was already correct has to
+ stay byte-for-byte correct. A `datetime` is still converted, which it
+ has always needed: on a column stored as an epoch integer the transform
+ is a function of an integer, and a `datetime` is not the value the real
+ predicate compares.
+ """
+ value = self._in_column_number_type(value, col)
+ parsed = _instant_from_filter_value(value)
+ if parsed is None:
+ if (
+ isinstance(value, str)
+ and self._column_literal_resolution(col) is not LiteralResolution.FULL
+ ):
+ return _UNMIRRORABLE
+ return value
+
+ # Ahead of the full-resolution return: a transform such as
+ # `CAST(:value AS TIMESTAMP)` drops the offset, so even an engine that
+ # compares the whole instant would probe it in the wrong frame.
+ if parsed.tzinfo is not None:
+ return _UNMIRRORABLE
+
+ if self._engine_literal_resolution(parsed, col) is LiteralResolution.FULL:
+ return (
+ self._mirror_probe_value(parsed, col)
+ if isinstance(value, datetime)
+ else value
+ )
+
+ if operator in LOWER_BOUND_OPERATORS:
+ instant = self._round_bound_outward(parsed, col, is_upper=False)
+ elif operator in UPPER_BOUND_OPERATORS:
+ instant = self._round_bound_outward(parsed, col, is_upper=True)
+ elif self._literal_is_coarser_than(parsed, col):
+ return _UNMIRRORABLE
+ else:
+ instant = parsed
+
+ if instant == parsed and not isinstance(value, datetime):
+ return value
+ return self._mirror_probe_value(instant, col)
+
+ def _collect_partition_mirror_range(
+ self,
+ mapping: Optional["PartitionMapping"],
+ sink: list[tuple[utils.FilterOperator, Any]],
+ column_name: str,
start_dttm: Optional[sa.DateTime],
end_dttm: Optional[sa.DateTime],
- time_grain: Optional[str] = None,
- label: Optional[str] = "__time",
- template_processor: Optional[BaseTemplateProcessor] = None,
- ) -> Optional[ColumnElement]:
- col = (
- time_col.get_timestamp_expression(
- time_grain=time_grain,
- label=label,
- template_processor=template_processor,
+ widen_bounds_by: Optional[relativedelta] = None,
+ ) -> None:
+ """
+ Record a time range for mirroring onto the partition column.
+
+ The bounds are adjusted first, by the same helper `get_time_filter` uses:
+ the mirrored predicate has to describe the same instants as the
+ timestamp predicate it stands in for, or the pruning is wrong by exactly
+ the dataset's timezone offset -- silently.
+
+ Either bound may be `None` for an open-ended range, in which case only
+ the bound that exists is mirrored.
+
+ Both bounds are recorded with the operators the real predicate uses,
+ `>=` and `<`. Relaxing the strict one is `mirror_operator`'s job, at the
+ single point where an operator becomes SQL -- which is also the point
+ the preview endpoint goes through.
+
+ `widen_bounds_by` is one grain bucket width, passed when the filter this
+ stands in for compares a *truncated* column. The real predicate then
+ keeps rows the raw bounds exclude, and widening both ends by one bucket
+ is the smallest range guaranteed to contain all of them -- see the "Time
+ grains" section of `superset.connectors.sqla.partition_mapping`.
+
+ A widened range can also be wide enough to fail `_bounds_are_ordered`
+ against a tighter filter on the same column. That fails open -- no
+ mirroring, no pruning, no dropped rows.
+ """
+ if mapping is None or column_name != mapping.mapped_column:
+ return
+ if not mapping.mirrors(utils.FilterOperator.TEMPORAL_RANGE):
+ return
+
+ # Resolve the column so the offset adjustment sees the same type
+ # `get_time_filter` does -- an offset the column's type cannot represent
+ # is dropped, and the mirrored bounds have to agree with the originals.
+ mapped_col = next(
+ (col for col in self.columns if col.column_name == column_name), None
+ )
+ start_dttm, end_dttm = self.adjust_time_bounds(start_dttm, end_dttm, mapped_col)
+
+ # Adjust first, then widen. `adjust_time_bounds` moves the naive UI
+ # bounds into the frame the column is *stored* in, and the grain
+ # truncation in the real predicate happens in that same frame, so the
+ # bucket width has to be added there too. The two commute for the
+ # hour-offset branch but not for the `ZoneInfo` one, where widening
+ # across a DST boundary first lands an hour out.
+ if widen_bounds_by is not None:
+ if start_dttm is not None:
+ start_dttm -= widen_bounds_by
+ if end_dttm is not None:
+ end_dttm += widen_bounds_by
+
+ # Then round outward, to whatever the engine's literal resolves to.
+ start_dttm, end_dttm = self._round_bounds_outward(
+ start_dttm, end_dttm, mapped_col
+ )
+
+ # Converted last. The widening and rounding above are `datetime`
+ # arithmetic, and the stored representation may be an integer.
+ if start_dttm is not None:
+ sink.append(
+ (
+ utils.FilterOperator.GREATER_THAN_OR_EQUALS,
+ self._mirror_probe_value(start_dttm, mapped_col),
+ )
)
- if time_grain
- else self.convert_tbl_column_to_sqla_col(
- time_col, label=label, template_processor=template_processor
+ if end_dttm is not None:
+ sink.append(
+ (
+ utils.FilterOperator.LESS_THAN,
+ self._mirror_probe_value(end_dttm, mapped_col),
+ )
)
+
+ def _array_mirror_probe_value(
+ self,
+ value: Any,
+ operator: utils.FilterOperator,
+ element_type: Optional[utils.GenericDataType],
+ db_engine_spec: builtins.type["BaseEngineSpec"],
+ ) -> Any:
+ """
+ The array literal the real predicate compares, ready to probe with.
+
+ On an array column the predicate is not built from `eq` at all: the
+ branch below reads the raw `val`, parses the pasted literal into
+ elements, coerces them to the array's element type and asks the engine
+ spec for its own array syntax. Mirroring `eq` would probe the transform
+ at a value the query never compares, so this reproduces that chain
+ instead -- the mirror then probes exactly what the predicate holds.
+
+ The result is SQL text rather than a value, because an array literal is
+ an expression; `RawProbeValue` carries it and `build_probe_sql`
+ substitutes rather than binds. Returns `None` when the engine spec
+ claims multi-value columns without implementing a literal for them,
+ which costs the query its pruning and nothing else.
+ """
+
+ def literal(entry: Any) -> Any:
+ return raw_probe_value(
+ self.database,
+ db_engine_spec.array_literal(
+ coerce_array_values(parse_array_literal(entry), element_type)
+ ),
+ )
+
+ try:
+ if operator in {utils.FilterOperator.IN, utils.FilterOperator.NOT_IN}:
+ candidates = (
+ list(value) if isinstance(value, (list, tuple)) else [value]
+ )
+ return tuple(literal(candidate) for candidate in candidates)
+ return literal(value)
+ except NotImplementedError:
Review Comment:
Addressed on Hugh's behalf in 54fe432f54: `_array_mirror_probe_value` now catches `sa.exc.CompileError` alongside `NotImplementedError` and returns `None`, so the preview declines instead of returning a 500. The chart path declines the mirror the same way. Added a parametrized preview test for `[[1, 2]]` on `Array(Array(Int32))` and `[1j]`. Both cases returned a 500 before the fix.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4260730919
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,3041 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: The opening and closing delimiters of each kind of Jinja block. The probe
+#: would render these in a different context at a different time from the chart
+#: query, so a transform holding one is rejected at save time.
+JINJA_BLOCK_DELIMITERS = (("{{", "}}"), ("{%", "%}"), ("{#", "#}"))
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: A PostgreSQL Unicode-escaped identifier, ``U&"..."``.
+#:
+#: The second construct that breaks the premise above, and in the same way:
+#: ``U&"\\0071uery_to_xml"(...)`` parses as an anonymous function whose name is
+#: the *literal* ``\\0071uery_to_xml``, so the function denylist is matching a
+#: name the engine never sees -- PostgreSQL decodes the escape and runs
+#: ``query_to_xml``, handing a dataset owner rows from outside their RLS scope
+#: through the preview's ``emitted_predicate``.
+#:
+#: Normalizing the escapes and re-checking would be the other repair, and is
+#: worse: it means reimplementing one engine's identifier decoding well enough
+#: to be a security boundary. Refusing the construct is exact, and costs
+#: nothing real -- a transform is a scalar function of ``:value``, and there is
+#: no reason to name a function or column through an escape sequence.
+#:
+#: Refused on every engine, like the executable comment, so a transform stored
+#: on SQLite cannot detonate when the dataset is re-pointed at PostgreSQL. The
+#: ``&`` may be separated from the ``U`` by nothing at all, but whitespace or a
+#: comment between the prefix and the string is not accepted by PostgreSQL
+#: either, so the strict form is the whole surface.
+#:
+#: Matched in raw text, so the prefix is refused inside a string literal too.
+#: That is the same trade the executable comment makes and has the same
+#: justification: a gate whose contract is to fire *before* the parse cannot
+#: ask the parse whether the text was quoted. ``concat(:value, 'u&"x"')`` is
+#: refused, which costs an owner nothing anyone writes.
+UNICODE_ESCAPED_IDENTIFIER_RE = re.compile(r'\bU&"', re.IGNORECASE)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
Review Comment:
This wall-clock list is matched by SQL function name, so `clock_timestamp()` and `statement_timestamp()` on PostgreSQL, `sysdate()` on MySQL, and `SYSTIMESTAMP`/`LOCALTIMESTAMP` pass the gate. A transform like `datediff(day, :value, LOCALTIMESTAMP)` for a relative partition key is accepted, its probe result is cached, and after midnight the cached partition value is emitted for a filter it no longer matches, so the chart silently drops rows. Should these be added here, or should the engine specs supply their own volatile names?
##########
tests/unit_tests/connectors/sqla/partition_mapping_test.py:
##########
@@ -0,0 +1,2928 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Unit tests for ``superset.connectors.sqla.partition_mapping``."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from decimal import Decimal
+from importlib import import_module
+from typing import Any, cast
+from unittest.mock import MagicMock, patch, PropertyMock
+
+import pandas as pd
+import pytest
+from dateutil.relativedelta import relativedelta
+from flask import Flask
+from pytest_mock import MockerFixture
+from sqlalchemy.dialects import mysql, postgresql
+
+from superset.config import DISALLOWED_SQL_FUNCTIONS
+from superset.connectors.sqla.models import SqlaTable, TableColumn
+from superset.connectors.sqla.partition_mapping import (
+ _mirror_verdict_cache_key,
+ _placeholder_is_bindable,
+ _probe_cache_key,
+ _reads_as_temporal,
+ _render_literal,
+ build_mirrored_predicates,
+ build_probe_sql,
+ contains_executable_comment,
+ contains_jinja,
+ contains_value_placeholder,
+ drop_unmapped_value_transforms,
+ equality_mirrors_safely,
+ evaluate_transform,
+ find_non_deterministic_functions,
+ grain_bucket_width,
+ GRAIN_BUCKET_WIDTHS,
+ is_bare_expression,
+ is_parseable,
+ is_transform_active,
+ is_unfinished,
+ known_mirror_verdict,
+ MappingValidationIssue,
+ mirror_operator,
+ MIRRORABLE_ALWAYS,
+ MIRRORABLE_IF_MONOTONIC,
+ mirrorable_operators,
+ parse_error_detail,
+ placeholder_is_executable,
+ probe_sql_is_evaluable,
+ probed_value_type_error,
+ RawProbeValue,
+ resolve_partition_mapping,
+ stored_expression_error,
+ validate_partition_mapping,
+ validate_transform,
+)
+from superset.constants import TimeGrain
+from superset.db_engine_specs.base import BaseEngineSpec
+from superset.db_engine_specs.oracle import OracleEngineSpec
+from superset.db_engine_specs.postgres import PostgresEngineSpec
+from superset.models.core import Database
+from superset.sql.parse import SQLStatement
+from superset.utils.core import FilterOperator, GenericDataType, override_user
+
+
+@pytest.fixture(autouse=True)
+def real_probe_cache(app: Flask) -> Any:
+ """
+ The test app runs a null cache, which would make every cache assertion here
+ vacuously pass. Swap in a real in-memory one for the duration.
+ """
+ from flask_caching import Cache
+
+ from superset.extensions import cache_manager
+
+ cache = Cache(config={"CACHE_TYPE": "SimpleCache", "CACHE_DEFAULT_TIMEOUT": 300})
+ cache.init_app(app)
+ original = cache_manager._cache # noqa: SLF001
+ cache_manager._cache = cache # noqa: SLF001
+ yield
+ cache_manager._cache = original # noqa: SLF001
+
+
+@pytest.fixture(autouse=True)
+def enable_partition_filter_mapping(app: Flask) -> Any:
+ """The feature ships off; every test here exercises it on."""
+ original = app.config["DEFAULT_FEATURE_FLAGS"].get("PARTITION_FILTER_MAPPING")
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = True
+ yield
+ if original is None:
+ del app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"]
+ else:
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = original
+
+
+def _table(**kwargs: Any) -> SqlaTable:
+ database = Database(database_name="test_db", sqlalchemy_uri="sqlite://")
+ defaults: dict[str, Any] = {
+ "table_name": "web_events",
+ "database": database,
+ "main_dttm_col": "event_time",
+ "columns": [
+ TableColumn(column_name="event_time", is_dttm=True, type="TIMESTAMP"),
+ TableColumn(
+ column_name="dt_epoch",
+ type="BIGINT",
+ partition_value_transform=None,
+ ),
+ TableColumn(column_name="country", type="VARCHAR"),
+ TableColumn(column_name="region_key", type="VARCHAR"),
+ ],
+ }
+ defaults.update(kwargs)
+ return SqlaTable(**defaults)
+
+
+def _mapped_table(
+ *,
+ partition_column: str = "dt_epoch",
+ mapped_column: str = "event_time",
+ transform: str | None = "unix_timestamp(:value)",
+ monotonic: bool = True,
+ partition_mapped_column: str | None = None,
+ main_dttm_col: str | None = "event_time",
+) -> SqlaTable:
+ table = _table(main_dttm_col=main_dttm_col)
+ table.partition_column = partition_column
+ table.partition_mapped_column = partition_mapped_column
+ for column in table.columns:
+ if column.column_name == mapped_column:
+ column.partition_value_transform = transform
+ column.partition_transform_is_monotonic = monotonic
+ return table
+
+
+# ---------------------------------------------------------------------------
+# §2 — operator safety matrix
+# ---------------------------------------------------------------------------
+
+
+def test_equality_and_in_are_always_mirrorable() -> None:
+ """``=`` and ``IN`` are safe for any function ``T``."""
+ assert MIRRORABLE_ALWAYS == {FilterOperator.EQUALS, FilterOperator.IN}
+
+
+def test_range_operators_require_a_monotonic_transform() -> None:
+ assert MIRRORABLE_IF_MONOTONIC == {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+ }
+
+
+def test_mirrorable_operators_excludes_ranges_when_not_monotonic() -> None:
+ assert mirrorable_operators(is_monotonic=False) == MIRRORABLE_ALWAYS
+
+
+def test_mirrorable_operators_includes_ranges_when_monotonic() -> None:
+ assert mirrorable_operators(is_monotonic=True) == (
+ MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+ )
+
+
+@pytest.mark.parametrize(
+ "operator",
+ [
+ FilterOperator.NOT_EQUALS,
+ FilterOperator.NOT_IN,
+ FilterOperator.LIKE,
+ FilterOperator.ILIKE,
+ FilterOperator.NOT_LIKE,
+ FilterOperator.NOT_ILIKE,
+ FilterOperator.IS_NULL,
+ FilterOperator.IS_NOT_NULL,
+ FilterOperator.IS_TRUE,
+ FilterOperator.IS_FALSE,
+ ],
+)
+def test_negations_and_pattern_matches_are_never_mirrorable(
+ operator: FilterOperator,
+) -> None:
+ """
+ ``T`` is not injective, so ``col != v`` does **not** imply ``T(col) != T(v)``:
+ mirroring it would drop rows the original filter keeps.
+ """
+ assert operator not in mirrorable_operators(is_monotonic=True)
+
+
+def test_equality_is_dropped_when_the_engine_does_not_compare_byte_exactly() -> None:
+ """
+ "Safe for any function ``T``" reasons about value equality: ``T`` is a
+ function, so ``col = v`` gives ``T(col) = T(v)``. The engine reasons about
+ *SQL* equality, and the two part company under a case-insensitive
+ collation -- a stored ``'us'`` satisfies a filter for ``'US'`` while the
+ mirror ``hex('US')`` excludes the row, and the chart loses it silently.
+ """
+ assert mirrorable_operators(is_monotonic=False, equality_is_safe=False) == set()
+
+
+def test_ranges_survive_an_unsafe_equality() -> None:
+ """
+ Range mirroring already rests on the owner declaring ``T``
+ order-preserving with respect to the column's own order -- an assertion
+ about the very comparison semantics this gate checks for. Equality has no
+ such declaration behind it, which is why only equality is withdrawn.
+ """
+ assert (
+ mirrorable_operators(is_monotonic=True, equality_is_safe=False)
+ == MIRRORABLE_IF_MONOTONIC
+ )
+
+
+@pytest.mark.parametrize(
+ "operator,expected",
+ [
+ (FilterOperator.GREATER_THAN, FilterOperator.GREATER_THAN_OR_EQUALS),
+ (FilterOperator.LESS_THAN, FilterOperator.LESS_THAN_OR_EQUALS),
+ (
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ ),
+ (FilterOperator.LESS_THAN_OR_EQUALS, FilterOperator.LESS_THAN_OR_EQUALS),
+ (FilterOperator.EQUALS, FilterOperator.EQUALS),
+ (FilterOperator.IN, FilterOperator.IN),
+ ],
+)
+def test_a_strict_bound_mirrors_non_strictly(
+ operator: FilterOperator, expected: FilterOperator
+) -> None:
+ """
+ Order-preserving means non-decreasing, not injective, so ``col < v``
+ implies only ``T(col) <= T(v)``. A day-key transform maps a whole day onto
+ one value and a strict mirror drops the boundary bucket. The non-strict
+ cases are already safe and pass through, which is what makes applying this
+ twice harmless.
+ """
+ assert mirror_operator(operator) == expected
+
+
+def test_relaxing_a_bound_stays_inside_the_mirrorable_set() -> None:
+ """
+ The substitution is about strictness, not about which filters mirror. The
+ Explore indicator reads `mirrorable_operators`, so leaving that set alone is
+ what keeps the glyph from promising pruning the SQL does not do -- and it is
+ also what guarantees `handle_comparison_filter` is never handed an operator
+ it has no case for.
+ """
+ assert {
+ mirror_operator(operator) for operator in MIRRORABLE_IF_MONOTONIC
+ } <= MIRRORABLE_IF_MONOTONIC
+
+
+def _column(type_: str) -> TableColumn:
+ database = Database(database_name="t", sqlalchemy_uri="sqlite://")
+ table = SqlaTable(table_name="t", database=database)
+ return TableColumn(column_name="c", type=type_, table=table)
+
+
+@pytest.mark.parametrize(
+ "type_, binary, expected",
+ [
+ ("VARCHAR", True, True),
+ ("VARCHAR", False, False),
+ # Numeric and temporal comparison is exact everywhere.
+ ("BIGINT", False, True),
+ ("TIMESTAMP", False, True),
+ ("DOUBLE", False, True),
+ ],
+)
+def test_equality_mirrors_safely_only_guards_string_columns(
+ app: Flask, type_: str, binary: bool, expected: bool
+) -> None:
+ class _Spec(BaseEngineSpec):
+ binary_string_comparison = binary
+
+ with app.app_context():
+ assert equality_mirrors_safely(_column(type_), _Spec) is expected
+
+
+@pytest.mark.parametrize(
+ "type_, expected",
+ [
+ # The padded types: `'US'` and `'US '` are equal in the column, and
+ # `lower()` of the two is not.
+ ("CHAR(2)", False),
+ ("CHAR", False),
+ ("CHARACTER(2)", False),
+ ("NCHAR(2)", False),
+ # What PostgreSQL reflection reports for a `CHAR(n)` column.
+ ("BPCHAR", False),
+ ("bpchar(2)", False),
+ ("NATIONAL CHARACTER(2)", False),
+ # The variable-width types start with the same letters and must not be
+ # caught by it.
+ ("VARCHAR(2)", True),
+ ("NVARCHAR(2)", True),
+ ("CHARACTER VARYING(2)", True),
+ ("TEXT", True),
+ ],
+)
+def test_a_padded_character_column_declines_equality_on_a_byte_exact_engine(
+ app: Flask, type_: str, expected: bool
+) -> None:
+ """
+ `binary_string_comparison` speaks for the engine's default comparison,
+ which PostgreSQL declares -- and a `CHAR(2)` there still matches a filter
+ for `'US '` against a stored `'US'`, so the mirror `lower('US ')` excludes
+ the row. Padding is a property of the type, so it is asked per column.
+ """
+
+ class _Spec(BaseEngineSpec):
+ binary_string_comparison = True
+
+ with app.app_context():
+ assert equality_mirrors_safely(_column(type_), _Spec) is expected
+
+
+def test_redshift_does_not_opt_in_to_byte_exact_comparison() -> None:
+ """
+ Redshift ignores trailing blanks for `VARCHAR` as well as `CHAR`, so the
+ `True` it inherits from `PostgresBaseEngineSpec` would be wrong.
+ """
+ from superset.db_engine_specs.redshift import RedshiftEngineSpec
+
+ assert RedshiftEngineSpec.binary_string_comparison is False
+
+
+def test_equality_mirrors_safely_fails_closed_on_an_unresolvable_type(
+ app: Flask,
+) -> None:
+ """
+ The gate exists to stop a silent wrong answer, so a column whose type it
+ cannot read is treated as the risky case rather than waved through.
+ """
+ column = MagicMock()
+ type(column).type_generic = PropertyMock(side_effect=ValueError("no type"))
+
+ with app.app_context():
+ assert equality_mirrors_safely(column, BaseEngineSpec) is False
+
+
+def test_no_mapped_column_leaves_the_matrix_alone(app: Flask) -> None:
+ """Nothing to reason about, and the resolver bails out on it anyway."""
+ with app.app_context():
+ assert equality_mirrors_safely(None, BaseEngineSpec) is True
+
+
+@pytest.mark.parametrize(
+ "module, spec_name",
+ [
+ ("presto", "PrestoEngineSpec"),
+ ("hive", "HiveEngineSpec"),
+ ("trino", "TrinoEngineSpec"),
+ ("impala", "ImpalaEngineSpec"),
+ ("postgres", "PostgresEngineSpec"),
+ ("bigquery", "BigQueryEngineSpec"),
+ ("sqlite", "SqliteEngineSpec"),
+ ],
+)
+def test_the_byte_exact_engines_opt_in(module: str, spec_name: str) -> None:
+ """
+ The engines this feature targets compare text byte-exactly, so the gate
+ must not cost them the second canonical mapping (`lower(:value)` onto a
+ lowercased key).
+ """
+ spec = getattr(import_module(f"superset.db_engine_specs.{module}"), spec_name)
+ assert spec.binary_string_comparison is True
+
+
+@pytest.mark.parametrize("module, spec_name", [("mysql", "MySQLEngineSpec")])
+def test_a_case_insensitive_engine_does_not_opt_in(module: str, spec_name: str) -> None:
+ """
+ MySQL's default collation is `utf8mb4_0900_ai_ci`, which is exactly the
+ case the reviewer raised.
+ """
+ spec = getattr(import_module(f"superset.db_engine_specs.{module}"), spec_name)
+ assert spec.binary_string_comparison is False
+
+
+def test_the_base_spec_does_not_opt_in() -> None:
+ """A spec that has not said so does not mirror string equality."""
+ assert BaseEngineSpec.binary_string_comparison is False
+
+
+# ---------------------------------------------------------------------------
+# Time grain bucket widths
+# ---------------------------------------------------------------------------
+
+
+@pytest.mark.parametrize("grain", list(TimeGrain))
+def test_every_builtin_grain_has_a_known_bucket_width(
+ app: Flask, grain: TimeGrain
+) -> None:
+ """
+ The widening is only sound for a grain whose bucket width we know, so a
+ grain added upstream without a width here would silently stop mirroring.
+ This is the test that notices.
+ """
+ with app.app_context():
+ assert grain_bucket_width(grain.value, "sqlite") is not None
+
+
+def test_a_calendar_grain_widens_by_a_calendar_month(app: Flask) -> None:
+ """A month is not thirty days, and the month it lands in decides its width."""
+ with app.app_context():
+ width = grain_bucket_width(TimeGrain.MONTH.value, "sqlite")
+
+ assert width is not None
+ assert datetime(2026, 1, 31) + width == datetime(2026, 2, 28)
+ assert datetime(2026, 2, 1) + width == datetime(2026, 3, 1)
+
+
+def test_a_fractional_grain_has_a_width(app: Flask) -> None:
+ """
+ ``PT0.5H`` and ``P0.25Y`` are why the widths are written out rather than
+ parsed -- and the anchored week grains are intervals ``parse_duration``
+ rejects outright.
+ """
+ with app.app_context():
+ assert grain_bucket_width(TimeGrain.HALF_HOUR.value, "sqlite") == relativedelta(
+ minutes=30
+ )
+ assert grain_bucket_width(
+ TimeGrain.WEEK_ENDING_SATURDAY.value, "sqlite"
+ ) == relativedelta(days=7)
+
+
+def test_an_unknown_grain_has_no_known_width(app: Flask) -> None:
+ with app.app_context():
+ assert grain_bucket_width("P13X", "sqlite") is None
+ assert grain_bucket_width(None, "sqlite") is None
+
+
+def test_an_addon_grain_has_no_known_width(app: Flask) -> None:
+ """An operator-declared grain carries whatever duration string they typed."""
+ with app.app_context():
+ app.config["TIME_GRAIN_ADDONS"] = {"PT2S": "2 second"}
+ try:
+ assert grain_bucket_width("PT2S", "sqlite") is None
+ finally:
+ app.config["TIME_GRAIN_ADDONS"] = {}
+
+
+def test_a_builtin_grain_an_operator_redefined_has_no_known_width(
+ app: Flask,
+) -> None:
+ """
+ ``TIME_GRAIN_ADDON_EXPRESSIONS`` replaces a built-in grain's SQL for one
+ engine, so its duration no longer bounds the displacement *there* -- but it
+ still does on every other engine.
+ """
+ with app.app_context():
+ app.config["TIME_GRAIN_ADDON_EXPRESSIONS"] = {
+ "sqlite": {"P1D": "DATETIME({col}, 'start of year')"}
+ }
+ try:
+ assert grain_bucket_width(TimeGrain.DAY.value, "sqlite") is None
+ assert grain_bucket_width(TimeGrain.DAY.value, "hive") is not None
+ finally:
+ app.config["TIME_GRAIN_ADDON_EXPRESSIONS"] = {}
+
+
+def test_the_width_table_is_keyed_on_grain_durations(app: Flask) -> None:
+ """Keys are the ISO duration a filter carries, not the enum member name."""
+ assert GRAIN_BUCKET_WIDTHS[TimeGrain.DAY] == relativedelta(days=1)
+ assert set(GRAIN_BUCKET_WIDTHS) == {grain.value for grain in TimeGrain}
+
+
+# ---------------------------------------------------------------------------
+# §4.1 — resolving the effective mapping, and the defensive bail-outs
+# ---------------------------------------------------------------------------
+
+
+def test_resolve_returns_the_mapping_when_everything_lines_up(app: Flask) -> None:
+ with app.app_context():
+ mapping = resolve_partition_mapping(_mapped_table())
+
+ assert mapping is not None
+ assert mapping.partition_column == "dt_epoch"
+ assert mapping.mapped_column == "event_time"
+ assert mapping.value_transform == "unix_timestamp(:value)"
+ assert mapping.is_monotonic is True
+
+
+def test_effective_mapped_column_follows_main_dttm_col(app: Flask) -> None:
+ """No explicit override: the mapping follows the default datetime column."""
+ with app.app_context():
+ mapping = resolve_partition_mapping(_mapped_table())
+
+ assert mapping is not None
+ assert mapping.mapped_column == "event_time"
+
+
+def test_explicit_override_wins_over_main_dttm_col(app: Flask) -> None:
+ table = _mapped_table(
+ mapped_column="country",
+ transform="lower(:value)",
+ monotonic=False,
+ partition_mapped_column="country",
+ )
+ table.partition_column = "region_key"
+
+ with app.app_context():
+ mapping = resolve_partition_mapping(table)
+
+ assert mapping is not None
+ assert mapping.mapped_column == "country"
+ assert mapping.partition_column == "region_key"
+ assert mapping.is_monotonic is False
+
+
+def test_resolve_returns_none_when_the_feature_flag_is_off(app: Flask) -> None:
+ table = _mapped_table()
+ with app.app_context():
+ with patch(
+ "superset.connectors.sqla.partition_mapping.feature_flag_manager."
+ "is_feature_enabled",
+ return_value=False,
+ ):
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_without_a_partition_column(app: Flask) -> None:
+ table = _mapped_table()
+ table.partition_column = None
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_partition_column_no_longer_exists(
+ app: Flask,
+) -> None:
+ """A column sync can drop the physical partition column out from under us."""
+ table = _mapped_table()
+ table.partition_column = "dt_epoch_gone"
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_the_mapped_column_no_longer_exists(
+ app: Flask,
+) -> None:
+ table = _mapped_table(main_dttm_col="vanished")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_on_self_mapping(app: Flask) -> None:
+ """
+ ``partition_column == effective mapped column`` mirrors a column onto itself.
+ Save-time validation rejects it, but rows predating that validation exist.
+ """
+ table = _mapped_table(
+ partition_column="event_time",
+ mapped_column="event_time",
+ )
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+@pytest.mark.parametrize("transform", [None, "", " "])
+def test_resolve_returns_none_without_a_transform(
+ app: Flask, transform: str | None
+) -> None:
+ table = _mapped_table(transform=transform)
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_the_transform_lacks_the_placeholder(
+ app: Flask,
+) -> None:
+ table = _mapped_table(transform="unix_timestamp(event_time)")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_for_a_non_deterministic_transform(app: Flask) -> None:
+ """
+ The query-time gate is `is_transform_active`, the same one the Explore
+ indicator reads. Anything narrower would let a transform that reached
+ storage without passing `UpdateDatasetCommand` -- through import, or a
+ hand-written bundle -- mirror a filter with a value frozen at probe time,
+ while the editor reported the mapping as inactive and nothing on screen
+ said otherwise.
+ """
+ table = _mapped_table(transform="unix_timestamp(:value) + rand()")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_for_a_multi_expression_transform(app: Flask) -> None:
+ """A select list is not an expression; the probe cannot align its columns."""
+ table = _mapped_table(transform="lower(:value), 'x'")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_for_an_unparseable_transform(app: Flask) -> None:
+ table = _mapped_table(transform="unix_timestamp(:value")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_the_mapped_column_has_an_advanced_data_type(
+ app: Flask,
+) -> None:
+ """
+ ``translate_filter`` builds its own predicate shape from *translated* values,
+ so the ``(operator, value)`` pair the operator matrix reasons about does not
+ exist. Mirroring anyway would silently apply the wrong values (§4.1).
+ """
+ table = _mapped_table()
+ for column in table.columns:
+ if column.column_name == "event_time":
+ column.advanced_data_type = "port"
+
+ with app.app_context():
+ with patch.dict(app.config["ADVANCED_DATA_TYPES"], {"port": MagicMock()}):
+ with patch(
+ "superset.connectors.sqla.partition_mapping.feature_flag_manager."
+ "is_feature_enabled",
+ side_effect=lambda flag: (
+ flag in {"PARTITION_FILTER_MAPPING", "ENABLE_ADVANCED_DATA_TYPES"}
+ ),
+ ):
+ assert resolve_partition_mapping(table) is None
+
+
+def test_advanced_data_type_does_not_block_when_the_flag_is_off(app: Flask) -> None:
+ """An inert ``advanced_data_type`` is not a reason to skip mirroring."""
+ table = _mapped_table()
+ for column in table.columns:
+ if column.column_name == "event_time":
+ column.advanced_data_type = "port"
+
+ with app.app_context():
+ with patch(
+ "superset.connectors.sqla.partition_mapping.feature_flag_manager."
+ "is_feature_enabled",
+ side_effect=lambda flag: flag == "PARTITION_FILTER_MAPPING",
+ ):
+ assert resolve_partition_mapping(table) is not None
+
+
+# ---------------------------------------------------------------------------
+# §5 — transform inspection helpers
+# ---------------------------------------------------------------------------
+
+
+@pytest.mark.parametrize(
+ "transform,expected",
+ [
+ ("unix_timestamp(:value)", True),
+ ("lower(:value)", True),
+ ("CAST(:value AS BIGINT)", True),
+ ("unix_timestamp(event_time)", False),
+ (":values", False),
+ ("", False),
+ (None, False),
+ ],
+)
+def test_contains_value_placeholder(transform: str | None, expected: bool) -> None:
+ assert contains_value_placeholder(transform) is expected
+
+
+@pytest.mark.parametrize(
+ "transform,expected",
+ [
+ ("unix_timestamp(:value)", False),
+ ("{{ current_username() }}", True),
+ ("lower({% if x %}:value{% endif %})", True),
+ ("lower(:value) -- {# comment #}", True),
+ ],
+)
+def test_contains_jinja(transform: str, expected: bool) -> None:
+ assert contains_jinja(transform) is expected
+
+
+def test_contains_jinja_answers_as_the_block_pattern_does() -> None:
+ """
+ The scan has to agree with the lazy, ``DOTALL`` pattern it stands in for
+ on every input, including overlapping and unclosed delimiters, so that no
+ stored transform changes verdict. Every string of up to seven characters
+ over the delimiter characters, a newline and a filler is checked.
+ """
+ import itertools
+ import re
+
+ pattern = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+ for length in range(8):
+ for chars in itertools.product("{}%#\na", repeat=length):
+ text = "".join(chars)
+ assert contains_jinja(text) is (pattern.search(text) is not None), text
+
+
+@pytest.mark.parametrize("opening", ["{{", "{%", "{#"])
+def test_contains_jinja_is_linear_in_a_run_of_opening_delimiters(
+ opening: str,
+) -> None:
+ """
+ A run of opening delimiters with no closing one made the lazy pattern retry
+ from every position, which is quadratic. Stored transforms are not
+ length-bounded here, so a long run has to stay cheap.
+ """
+ import time
+
+ started = time.monotonic()
+ assert contains_jinja(opening * 200_000) is False
+ assert time.monotonic() - started < 1
+
+
+@pytest.mark.parametrize(
+ ("transform", "expected"),
+ [
+ ("lower(:value)", False),
+ ("lower(:value) /* an ordinary comment */", False),
+ ("lower(:value) -- a line comment", False),
+ (":value /*!50000 + 1 */", True),
+ (":value /*M!50000 + 1 */", True),
+ (":value /*! + 1 */", True),
+ ("", False),
+ (None, False),
+ ],
+)
+def test_contains_executable_comment(transform: str | None, expected: bool) -> None:
+ assert contains_executable_comment(transform) is expected
+
+
+@pytest.mark.parametrize(
+ "transform",
+ [
+ "unix_timestamp(:value)",
+ "lower(:value)",
+ "CAST(:value AS BIGINT)",
+ "date_format(:value, 'yyyyMMdd')",
+ ],
+)
+def test_pure_transforms_report_no_non_deterministic_functions(
+ transform: str,
+) -> None:
+ assert find_non_deterministic_functions(transform, "hive") == set()
+
+
+@pytest.mark.parametrize(
+ "transform,expected_name",
+ [
+ ("date_diff(:value, now())", "NOW"),
+ ("CAST(:value AS BIGINT) + rand()", "RAND"),
+ ("CAST(:value AS DATE) - current_date", "CURRENT_DATE"),
+ ],
+)
+def test_non_deterministic_functions_are_reported(
+ transform: str, expected_name: str
+) -> None:
+ """
+ The probe runs at a different moment and in a different session from the
+ chart query, and its result is cached, so anything time- or
+ randomness-dependent freezes a snapshot of probe time into the predicate.
+ """
+ assert expected_name in find_non_deterministic_functions(transform, "hive")
+
+
+def test_niladic_unix_timestamp_is_rejected_but_the_unary_form_is_not() -> None:
+ """
+ On Hive/Impala ``unix_timestamp()`` means "now" while ``unix_timestamp(x)``
+ -- the canonical temporal transform -- is pure. The distinction is the whole
+ reason this check inspects arity rather than just the name.
+ """
+ assert find_non_deterministic_functions("unix_timestamp(:value)", "hive") == set()
+ assert find_non_deterministic_functions(
+ "unix_timestamp(:value) - unix_timestamp()", "hive"
+ )
+
+
+# ---------------------------------------------------------------------------
+# §4.2 — probe evaluation
+# ---------------------------------------------------------------------------
+
+
+def _user(username: str) -> Any:
+ """A stand-in for `override_user`, which only needs `.username` here."""
+ user = MagicMock()
+ user.username = username
+ user.is_anonymous = False
+ return user
+
+
+def _database_returning(values: list[Any]) -> Database:
+ """A real ``Database`` (so the dialect is real) with only ``get_df`` stubbed."""
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ return_value=pd.DataFrame(
+ [values], columns=[f"v{i}" for i in range(len(values))]
+ )
+ )
+ return database
+
+
+def _database_returning_frame(frame: pd.DataFrame) -> Database:
+ """
+ ``_database_returning`` for a probe result whose column dtypes matter.
+
+ The flat-list sibling builds its frame from one Python list, so pandas
+ infers a single dtype and the row-versus-cell distinction cannot be seen.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ return_value=frame
+ )
+ return database
+
+
+def _probe(database: Database) -> MagicMock:
+ """
+ The stubbed ``get_df``, typed for call assertions.
+
+ ``Database.get_df`` is a real method, so mypy reads its declared signature
+ rather than the mock that replaced it and rejects ``.call_args`` and
+ friends.
+ """
+ return cast(MagicMock, database.get_df)
+
+
+def test_evaluate_transform_returns_one_value_per_input(app: Flask) -> None:
+ database = _database_returning([1767225600, 1769904000])
+
+ with app.app_context():
+ result = evaluate_transform(
+ database,
+ None,
+ "default",
+ "unix_timestamp(:value)",
+ ["2026-01-01 00:00:00", "2026-02-01 00:00:00"],
+ )
+
+ assert result == [1767225600, 1769904000]
+ _probe(database).assert_called_once()
+
+
+def test_evaluate_transform_binds_values_rather_than_interpolating(
+ app: Flask,
+) -> None:
+ """
+ Filter values are attacker-controlled (a Gamma user picks them), so they must
+ be bound and escaped, never pasted into the probe SQL.
+ """
+ database = _database_returning(["o''brien"])
+
+ with app.app_context():
+ evaluate_transform(database, None, None, "lower(:value)", ["O'Brien"])
+
+ sql = _probe(database).call_args.kwargs["sql"]
+ assert "O'Brien" not in sql
+ assert "O''Brien" in sql
+
+
+@pytest.mark.parametrize(
+ ("transform", "expected"),
+ [
+ ("lower(:value)", True),
+ ("CAST(:value AS BIGINT)", True),
+ ("date_format(:value, '%Y%m%d')", True),
+ # The cast shorthand: a trailing colon stops SQLAlchemy's bind scan.
+ (":value::bigint", False),
+ ("(:value::date)::text", False),
+ ],
+)
+def test_a_postgres_cast_shorthand_is_not_bindable(
+ transform: str, expected: bool
+) -> None:
+ """
+ `VALUE_PLACEHOLDER_RE` is `:value\b`, which matches inside `:value::bigint`.
+ SQLAlchemy's own scan ends with `(?![:\\w$])`, so the following colon stops
+ it: `text(":value::bigint")` reports a parameter named `valu`, and asking it
+ to bind `value` raises.
+
+ Pinned because the two regexes disagreeing is the whole bug: every
+ write-side gate accepted the transform and the probe then died on an
+ `ArgumentError` that `_probe` swallows.
+ """
+ assert _placeholder_is_bindable(transform) is expected
+
+
+def test_a_cast_shorthand_transform_still_probes(app: Flask) -> None:
+ """
+ The transform is valid SQL, passes every gate, and used to prune nothing:
+ `build_probe_sql` raised, `_probe` swallowed it, and the only symptom was a
+ mapping that silently never mirrored -- with the preview reporting an engine
+ failure for SQL that was never sent.
+ """
+ database = _database_returning([20260115])
+
+ with app.app_context():
+ result = evaluate_transform(
+ database, None, None, ":value::bigint", ["20260115"]
+ )
+
+ assert result == [20260115]
+ assert _probe(database).call_count == 1
+ assert "::bigint" in _probe(database).call_args.kwargs["sql"]
+
+
+def test_a_cast_shorthand_value_is_still_escaped_by_the_dialect(
+ app: Flask,
+) -> None:
+ """
+ The fallback substitutes where the bind path binds, so it has to earn the
+ same guarantee its sibling above pins: the value is rendered by the
+ dialect's literal processor, not pasted in.
+
+ Binding was only ever the vehicle for reaching that processor --
+ `_compile_literal` inlines the result either way -- so this renders first
+ and substitutes second. Same string, different order.
+ """
+ database = _database_returning(["x"])
+
+ with app.app_context():
+ evaluate_transform(database, None, None, ":value::text", ["O'Brien"])
+
+ sql = _probe(database).call_args.kwargs["sql"]
+ assert "O'Brien" not in sql
+ assert "O''Brien" in sql
+
+
+def test_evaluate_transform_dedupes_repeated_values(app: Flask) -> None:
+ """Three inputs, two distinct: the probe evaluates the transform twice."""
+ database = _database_returning(["us", "us"])
+
+ with app.app_context():
+ result = evaluate_transform(
+ database, None, None, "lower(:value)", ["US", "US", "us"]
+ )
+
+ assert result == ["us", "us", "us"]
+ sql = _probe(database).call_args.kwargs["sql"]
+ assert sql.count("lower") == 2
+
+
+def test_evaluate_transform_fails_open_on_a_short_result_row(app: Flask) -> None:
+ """A row narrower than the probe asked for means the results cannot be
+ aligned back to their inputs; pruning is skipped rather than guessed at."""
+ database = _database_returning(["us"])
+
+ with app.app_context():
+ assert (
+ evaluate_transform(database, None, None, "lower(:value)", ["US", "CA"])
+ is None
+ )
+
+
+def test_evaluate_transform_fails_open_on_a_wide_result_row(app: Flask) -> None:
+ """
+ Too many columns is the dangerous direction. A transform whose select list
+ holds two expressions returns 2N columns for N inputs, and reading the first
+ N interleaves the expressions instead of taking one per value -- a predicate
+ built from the wrong values rather than one that is merely short. A frame of
+ `('us', 'x', 'ca', 'x')` read as the first two columns would have yielded
+ `('us', 'x')` and dropped every CA row.
+
+ The transform is a perfectly ordinary `lower(:value)` and the width comes
+ from the stubbed frame, which is the only way to reach the guard: a
+ transform that really does carry two expressions -- `lower(:value), 'x'` --
+ is refused by `stored_expression_error` for not being a single expression,
+ so `get_df` is never called and `None` comes back for an unrelated reason.
+ Asserting the probe *ran* is what separates the two, and it is what makes
+ relaxing the guard from `!=` to `<` fail here rather than pass: four columns
+ for two inputs is not fewer than two.
+ """
+ database = _database_returning(["us", "x", "ca", "x"])
+
+ with app.app_context():
+ assert (
+ evaluate_transform(database, None, None, "lower(:value)", ["US", "CA"])
+ is None
+ )
+
+ assert _probe(database).call_count == 1
+
+
+def test_the_probe_select_carries_the_engine_s_from_clause(app: Flask) -> None:
+ """
+ A `SELECT` with no `FROM` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from. Without this every probe on those engines
+ raises, which `evaluate_transform` swallows -- so the only symptom is a
+ correctly configured mapping that silently never prunes.
+ """
+ assert build_probe_sql("lower(:value)", ["US"]) == "SELECT lower('US') AS v0"
+ assert build_probe_sql("lower(:value)", ["US"], None, " FROM DUAL").endswith(
+ " FROM DUAL"
+ )
+ assert OracleEngineSpec.select_without_from_suffix == " FROM DUAL"
+ assert BaseEngineSpec.select_without_from_suffix == ""
+
+
+@pytest.mark.parametrize(
+ ("module", "spec_name", "suffix"),
+ [
+ ("oracle", "OracleEngineSpec", " FROM DUAL"),
+ ("db2", "Db2EngineSpec", " FROM SYSIBM.SYSDUMMY1"),
+ ],
+)
+def test_the_probe_reads_the_from_suffix_off_the_engine_spec(
+ app: Flask, mocker: MockerFixture, module: str, spec_name: str, suffix: str
+) -> None:
+ """
+ The sibling above hands `build_probe_sql` a suffix directly, so it never
+ exercises the step that reads `select_without_from_suffix` off the engine
+ spec and forwards it. Drop that forwarding and the sibling stays green
+ while Oracle and Db2 stop pruning entirely -- a bare `SELECT ...` raises
+ there, `evaluate_transform` swallows it, and the only symptom is a
+ correctly configured mapping that silently never prunes.
+
+ So this drives the real entry point and asserts on the SQL the engine is
+ handed, plus that the result is accepted.
+ """
+ spec = getattr(import_module(f"superset.db_engine_specs.{module}"), spec_name)
+ database = _database_returning(["us"])
+ mocker.patch.object(
+ type(database), "db_engine_spec", PropertyMock(return_value=spec)
+ )
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, "lower(:value)", ["US"]) == [
+ "us"
+ ]
+
+ sql = _probe(database).call_args.kwargs["sql"]
+ assert sql.endswith(suffix)
+ # And the gate that re-parses the compiled probe accepts that shape, rather
+ # than the suffix being appended only to be refused downstream.
+ assert probe_sql_is_evaluable(sql, spec.engine, 1, suffix) is True
+
+
+@pytest.mark.parametrize("dialect", [mysql.dialect(), postgresql.dialect()])
+def test_the_probe_select_does_not_double_percent_signs(dialect: Any) -> None:
+ """
+ `TextClause` compilation runs the dialect's `post_process_text`, which
+ doubles every `%` on any paramstyle whose DBAPI later interpolates
+ parameters -- MySQL and Postgres, and every spec inheriting from them. The
+ probe has no such interpolation pass: it executes with no bound parameters
+ at all. Left doubled, `date_format(:value, '%Y%m%d')` asks the warehouse
+ for the literal string `%%Y%%m%%d`, so the probe returns that instead of a
+ date and the mirrored predicate drops every row the filter keeps.
+ """
+ sql = build_probe_sql("date_format(:value, '%Y%m%d')", ["2026-01-15"], dialect)
+
+ assert "'%Y%m%d'" in sql
+ assert "%%" not in sql
+
+
+def test_the_probe_select_is_unchanged_on_a_dialect_that_does_not_double() -> None:
+ """
+ Pins the no-dialect path, which is also the blind spot: the default dialect
+ does not double percent signs, so no assertion made through it can see the
+ bug the two cases above cover.
+ """
+ assert (
+ build_probe_sql("date_format(:value, '%Y%m%d')", ["2026-01-15"])
+ == "SELECT date_format('2026-01-15', '%Y%m%d') AS v0"
+ )
+
+
+def test_a_raw_probe_value_is_substituted_literally() -> None:
+ r"""
+ `RawProbeValue.sql` is rendered from a filter value, so it reaches
+ `parse_skeleton` as the *replacement* for `:value`. Read as a replacement
+ template, a backslash in it is an escape: `array('a\nb')` -- which is how a
+ dialect renders the two characters `\` and `n` -- would become a real
+ newline, so the engine is asked about a different array than the predicate
+ compares and the mirror can exclude rows the filter keeps.
+ """
+ sql = build_probe_sql("toYYYYMM(:value)", [RawProbeValue(r"array('a\nb')")])
+
+ assert sql == r"SELECT toYYYYMM(array('a\nb')) AS v0"
+
+
+def test_a_raw_probe_value_does_not_re_inject_the_placeholder() -> None:
+ r"""
+ `\g<0>` in a replacement template expands to the whole match, which would
+ put `:value` back into the probe -- an unbound parameter the engine refuses.
+ """
+ sql = build_probe_sql("toYYYYMM(:value)", [RawProbeValue(r"'a\g<0>b'")])
+
+ assert sql == r"SELECT toYYYYMM('a\g<0>b') AS v0"
+ assert ":value" not in sql
+
+
+def test_a_raw_probe_value_with_a_group_reference_does_not_raise() -> None:
+ r"""
+ `\1` is an invalid group reference for this pattern, so as a replacement
+ template it raised `re.PatternError` rather than probing anything.
+ """
+ sql = build_probe_sql("toYYYYMM(:value)", [RawProbeValue(r"'a\1b'")])
+
+ assert sql == r"SELECT toYYYYMM('a\1b') AS v0"
+
+
+def test_a_probed_literal_keeps_its_percent_sign(app: Flask) -> None:
+ """
+ The preview panel renders probed values through the same dialect, so a
+ value that merely contains a `%` would be shown doubled.
+ """
+ database = Database(database_name="pct_db", sqlalchemy_uri="postgresql://h/d")
+
+ with app.app_context():
+ assert _render_literal(database, "100%") == "'100%'"
+
+
+def test_the_probe_reads_each_cell_without_row_wide_dtype_coercion(
+ app: Flask,
+) -> None:
+ """
+ A row is a Series, so it carries one dtype across every probe column: a row
+ mixing an exact int64 with a float unifies to float64 and an integer
+ partition key above 2^53 comes back rounded. The mirror then asks for a key
+ the warehouse does not hold, and the row the filter matched is dropped.
+ """
+ database = _database_returning_frame(
+ pd.DataFrame({"v0": [9007199254740993], "v1": [1.5]})
+ )
+
+ with app.app_context():
+ probed = evaluate_transform(
+ database, None, None, "CAST(:value AS NUMERIC)", ["9007199254740993", "1.5"]
+ )
+
+ assert probed == [9007199254740993, 1.5]
+
+
+def test_evaluate_transform_pins_catalog_and_schema(app: Flask) -> None:
+ """
+ The probe runs in a different session from the chart query; pinning the
+ catalog and schema keeps session settings as close as the pool allows.
+ """
+ database = _database_returning([1])
+
+ with app.app_context():
+ evaluate_transform(database, "prod", "analytics", "lower(:value)", ["x"])
+
+ kwargs = _probe(database).call_args.kwargs
+ assert kwargs["catalog"] == "prod"
+ assert kwargs["schema"] == "analytics"
+
+
+def test_evaluate_transform_fails_open_when_the_probe_raises(app: Flask) -> None:
+ """A wedged engine must not break the chart — it just stops pruning."""
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ side_effect=RuntimeError("connection reset")
+ )
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, "lower(:value)", ["x"]) is None
+
+
+def test_evaluate_transform_fails_open_on_an_empty_result(app: Flask) -> None:
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ return_value=pd.DataFrame()
+ )
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, "lower(:value)", ["x"]) is None
+
+
+def test_evaluate_transform_returns_none_for_no_values(app: Flask) -> None:
+ database = _database_returning([])
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, "lower(:value)", []) is None
+
+ _probe(database).assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "transform",
+ [
+ "(SELECT password FROM ab_user LIMIT 1) || :value",
+ "lower(:value) UNION ALL SELECT password FROM ab_user",
+ "lower(:value); DROP TABLE ab_user",
+ "password || :value FROM ab_user",
+ "lower(:value) FROM ab_user WHERE 1 = 1",
+ ],
+ ids=[
+ "subquery",
+ "set-operation",
+ "multi-statement",
+ "bare-from",
+ "from-and-where",
+ ],
+)
+def test_a_transform_that_is_not_a_storable_expression_never_runs(
+ app: Flask, transform: str
+) -> None:
+ """
+ The probe is where a transform stops being text and becomes SQL.
+
+ `build_probe_sql` binds `:value` and splices the rest in verbatim, so a
+ transform that was never a single harmless expression is arbitrary SQL
+ against the dataset's database -- read back out of the emitted predicate
+ by anyone who can open "View query". The write-side gates refuse these,
+ but they can only speak for rows written after they existed, so the last
+ word belongs here.
+ """
+ database = _database_returning(["irrelevant"])
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, transform, ["us"]) is None
+
+ _probe(database).assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "transform, unfinished",
+ [
+ ("unix_timestamp(:value", True),
+ ("unix_timestamp(:value))", True),
+ ("unix_timestamp(:value) +", True),
+ ("unix_timestamp(:value)", False),
+ ("unix_timestamp(:value); DROP TABLE ab_user", False),
+ ("unix_timestamp(:value) UNION ALL SELECT password FROM ab_user", False),
+ ("password || :value FROM ab_user", False),
+ ],
+)
+def test_is_unfinished_separates_not_sql_yet_from_the_wrong_sql(
+ transform: str, unfinished: bool
+) -> None:
+ """
+ The two deserve opposite treatment -- a half-typed transform is stored and
+ parked inactive, the wrong SQL is refused -- and neither `is_parseable` nor
+ parsing as a single statement tells them apart, because the multi-statement
+ form fails both exactly as unfinished text does. Parsing as a script does.
+ """
+ assert is_unfinished(transform, "hive") is unfinished
+
+
+def test_a_transform_smuggling_its_own_from_clause_is_refused(app: Flask) -> None:
+ """
+ The hole this gate was added for.
+
+ `is_parseable` counts only the projection, so `password || :value FROM
+ ab_user` reads as a single select expression and passed every write-side
+ gate -- including with `ALLOW_ADHOC_SUBQUERY` off, since a top-level FROM
+ is not a sub-query. `build_probe_sql` then emitted `SELECT password || 'us'
+ AS v0 FROM ab_user`, where its own alias is read as a table alias on the
+ FROM clause the transform brought with it: valid SQL, one row, and the
+ secret handed back through the predicate the preview panel renders.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ transform = "password || :value FROM ab_user"
+
+ assert is_parseable(transform, "sqlite") is True
+ assert is_bare_expression(transform, "sqlite") is False
+
+ with app.app_context():
+ reason = stored_expression_error(database, None, None, transform)
+ assert reason is not None
+
+ blocking = _blocking(validate_transform(transform, "sqlite"))
+ assert len(blocking) == 1
+ assert "single SQL expression" in str(blocking[0].message)
+ assert is_transform_active(transform, "sqlite") is False
+
+
+def test_a_subquery_transform_is_refused_even_with_adhoc_subquery_enabled(
+ app: Flask,
+) -> None:
+ """
+ `validate_adhoc_subquery` admits a sub-query under `ALLOW_ADHOC_SUBQUERY`
+ and returns RLS-rewritten SQL -- which this path has no way to propagate,
+ because `build_probe_sql` splices the original transform text. So the probe
+ ran a sub-query with no row-level-security predicates at all and reported
+ the hidden row in `emitted_predicate`. A transform is a scalar function of
+ `:value`, so refusing the sub-query outright is both correct and what makes
+ the missing RLS rewrite moot.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ transform = "(SELECT secret FROM vault LIMIT 1) || :value"
+
+ with app.app_context():
+ app.config["DEFAULT_FEATURE_FLAGS"]["ALLOW_ADHOC_SUBQUERY"] = True
+ try:
+ reason = stored_expression_error(database, None, None, transform)
+ finally:
+ del app.config["DEFAULT_FEATURE_FLAGS"]["ALLOW_ADHOC_SUBQUERY"]
+
+ assert reason is not None
+ assert "sub-query" in reason
+
+
+@pytest.mark.parametrize(
+ "comment",
+ ["/*!50000 + (SELECT secret FROM vault LIMIT 1) */", "/*M!50000 + 1 */"],
+)
+def test_an_executable_comment_is_refused_by_every_gate(
+ app: Flask, comment: str
+) -> None:
+ """
+ The one construct that made the shape gates describe a statement the engine
+ would not run.
+
+ sqlglot reads a MySQL executable comment as comment data: the pinned parse
+ below reports no sub-query and no clause, so `stored_expression_error` and
+ `probe_sql_is_evaluable` both passed it, while MySQL and MariaDB execute
+ what is inside. An owner with dataset write and no SQL Lab could put one in
+ a transform, call the preview and read a table back out of
+ `emitted_predicate`, with no RLS on the hidden query.
+
+ Refused on every engine, not only the two that honour it -- hence SQLite
+ here. There is no legitimate transform carrying one, and a per-engine gate
+ would store on Postgres what detonates after the dataset is re-pointed.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ transform = f"(:value {comment})"
+
+ # The premise: no parse-tree gate can see it.
+ statement = SQLStatement(f"SELECT (1 {comment}) AS v0", "mysql")
+ assert statement.has_subquery() is False
+ assert statement.get_clause_names() == set()
+
+ with app.app_context():
+ assert stored_expression_error(database, None, None, transform) is not None
+
+ blocking = [
+ issue for issue in validate_transform(transform, "mysql") if issue.blocking
+ ]
+ assert len(blocking) == 1
+ assert "executable comment" in str(blocking[0].message)
+
+
+def test_an_executable_comment_stops_the_probe_before_the_engine(app: Flask) -> None:
+ """
+ The gate above is the save path. This is the row an earlier release stored:
+ `_probe` consults `stored_expression_error` on every call, so a transform
+ already in the metadata database never reaches `get_df`.
+ """
+ database = _database_returning(["x"])
+ transform = "(:value /*!50000 + (SELECT secret FROM vault LIMIT 1) */)"
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, transform, ["US"]) is None
+
+ assert _probe(database).call_count == 0
+
+
+def test_a_unicode_escaped_identifier_is_refused_by_every_gate(app: Flask) -> None:
+ """
+ The second construct that made the gates reason about a name the engine
+ does not use. sqlglot reports `U&"\\0071uery_to_xml"` as an anonymous
+ function literally called `\\0071uery_to_xml`, so the function denylist --
+ which matches on the reported name -- never sees `query_to_xml`, while
+ PostgreSQL decodes the escape and runs it. An owner with dataset write and
+ no SQL Lab could read rows outside their RLS scope back out of
+ `emitted_predicate`.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="postgresql://u@h/d")
+ transform = "CAST(U&\"\\0071uery_to_xml\"(:value, false, true, '') AS TEXT)"
+
+ # The premise: the denylist is matching the wrong name.
+ statement = SQLStatement(
+ "SELECT CAST(U&\"\\0071uery_to_xml\"('x', false, true, '') AS TEXT) AS v0",
+ "postgresql",
+ )
+ assert statement.get_disallowed_functions({"query_to_xml"}) == set()
+
+ with app.app_context():
+ assert stored_expression_error(database, None, None, transform) is not None
+
+ blocking = [
+ issue for issue in validate_transform(transform, "postgresql") if issue.blocking
+ ]
+ assert len(blocking) == 1
+ assert "escape sequence" in str(blocking[0].message)
+
+
+def test_a_unicode_escaped_identifier_stops_the_probe_before_the_engine(
+ app: Flask,
+) -> None:
+ """The row an earlier release stored, as for the executable comment."""
+ database = _database_returning(["x"])
+ transform = "U&\"\\0071uery_to_xml\"(:value, false, true, '') || ''"
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, transform, ["US"]) is None
+
+ assert _probe(database).call_count == 0
+
+
+def test_an_ordinary_quoted_identifier_is_still_allowed(app: Flask) -> None:
+ """
+ Only the escape prefix is refused. A plainly quoted identifier names what
+ it says, so the denylist sees the real name and rejecting it would cost an
+ owner a transform that works.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="postgresql://u@h/d")
+
+ with app.app_context():
+ assert (
+ stored_expression_error(database, None, None, 'lower("Mixed Case")') is None
+ )
+
+
+def test_the_escape_gate_reads_raw_text_and_says_so(app: Flask) -> None:
+ """
+ The prefix is refused wherever it appears, including inside a string
+ literal -- the same trade the executable-comment gate makes, and for the
+ same reason: a gate whose whole job is to fire before the parse cannot ask
+ the parse whether the text is quoted. `concat(:value, 'u&"x"')` is refused,
+ which costs an owner nothing anyone writes.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="postgresql://u@h/d")
+
+ with app.app_context():
+ assert (
+ stored_expression_error(database, None, None, "concat(:value, 'u&\"x\"')")
+ is not None
+ )
+
+
+def test_a_plain_comment_is_still_allowed_through_the_shape_gates(
+ app: Flask,
+) -> None:
+ """
+ Only the executable form is refused. An ordinary comment is inert on every
+ engine, so rejecting it would cost an owner a transform that works -- and
+ the placeholder gate already covers the case that matters, a `:value` the
+ comment swallows.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+
+ with app.app_context():
+ assert (
+ stored_expression_error(database, None, None, "lower(:value) /* ok */")
+ is None
+ )
+
+
+def test_a_transform_calling_a_disallowed_function_is_refused(app: Flask) -> None:
+ """
+ The probe executes the transform, so the operator's function denylist has
+ to apply to it for the same reason it applies in SQL Lab.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ transform = "version() || :value"
+
+ with app.app_context():
+ original = app.config["DISALLOWED_SQL_FUNCTIONS"]
+ try:
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = {"sqlite": {"version"}}
+ reason = stored_expression_error(database, None, None, transform)
+ assert reason is not None
+ assert "version" in reason
+
+ # Named, rather than echoing the operator's whole denylist back.
+ assert "current_user" not in reason
+
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = {}
+ assert stored_expression_error(database, None, None, transform) is None
+ finally:
+ # Restored: `app.config` is shared, and leaving it emptied silently
+ # disabled this gate for every test that ran afterwards.
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = original
+
+
+@pytest.mark.parametrize(
+ "function",
+ [
+ "database_to_xml",
+ "database_to_xmlschema",
+ "database_to_xml_and_xmlschema",
+ "schema_to_xml",
+ "schema_to_xmlschema",
+ "schema_to_xml_and_xmlschema",
+ "table_to_xml",
+ "table_to_xmlschema",
+ "table_to_xml_and_xmlschema",
+ "query_to_xml",
+ "query_to_xmlschema",
+ "query_to_xml_and_xmlschema",
+ ],
+)
+def test_the_whole_postgres_xml_family_is_denied_by_default(function: str) -> None:
+ """
+ These read tables with no FROM clause and no sub-query, so every gate that
+ reasons about table references is blind to them -- the denylist is the only
+ thing that can refuse them, and it has to name each shape. `schema_to_xml`
+ and three siblings were missing, so a bare scalar call cleared
+ `stored_expression_error` entirely and returned connection-user-readable
+ schema contents through preview.
+
+ Asserted against the shipped default rather than through the gate, because
+ the gap was an incomplete enumeration rather than broken wiring -- and
+ because `app.config` is ambient here, which the behavioural test below
+ handles by setting the denylist itself.
+ """
+ assert function in DISALLOWED_SQL_FUNCTIONS["postgresql"]
+
+
+def test_a_denied_read_capable_function_is_refused_despite_having_no_from(
+ app: Flask,
+) -> None:
+ """
+ The wiring half: a bare scalar call passes the length, single-statement,
+ bare-expression, sub-query and placeholder gates, so the denylist is what
+ has to stop it.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="postgresql://u@h/d")
+ transform = "schema_to_xml('public', true, false, '') || :value"
+
+ with app.app_context():
+ original = app.config["DISALLOWED_SQL_FUNCTIONS"]
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = {"postgresql": {"schema_to_xml"}}
+ try:
+ reason = stored_expression_error(database, None, None, transform)
+ finally:
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = original
+
+ assert reason is not None
+ assert "schema_to_xml" in reason
+
+
+@pytest.mark.parametrize("function", ["ts_rewrite", "ts_stat"])
+def test_the_postgres_full_text_query_functions_are_denied_by_default(
+ function: str,
+) -> None:
+ """
+ `ts_stat('select ...')` and `ts_rewrite(q, 'select ...')` run their *text*
+ argument as a query. The query is a string, so these have the same blind
+ spot the XML family above does: no FROM clause and no sub-query for a
+ table-reference gate to reason about, which leaves the denylist as the only
+ thing that can refuse them.
+ """
+ assert function in DISALLOWED_SQL_FUNCTIONS["postgresql"]
+
+
+@pytest.mark.parametrize(
+ "function",
+ [
+ "getxml",
+ "getxmltype",
+ "newcontext",
+ "newcontextfromhierarchy",
+ # No function argument to inspect at all: the table is named by the
+ # path string handed to the constructor.
+ "dburitype",
Review Comment:
The new `geturi`, `xdburitype` and `httpuritype` denylist entries in `config.py` have no case here; this parametrization stops at `dburitype`. Deleting those three names would leave every test green and reopen the factory path to the same table read. Could this add cases like `URIFACTORY.GETURI('/oradb/HR/EMPLOYEES/ROW[ID=1]/SALARY').getclob() || :value` and assert that `stored_expression_error` names the denied function?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "eschutho (via GitHub)" <gi...@apache.org>.
eschutho commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4233511037
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/utils.ts:
##########
@@ -0,0 +1,587 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { t } from '@apache-superset/core/translation';
+import type {
+ PartitionMappingColumn,
+ PartitionMappingDatasource,
+ PartitionMappingIssue,
+ PartitionRowState,
+} from './types';
+
+/**
+ * Jinja delimiters.
+ *
+ * A transform is evaluated in a different context and at a different time from
+ * the chart query, so a template would not render the same way -- the backend
+ * rejects one outright. Shared so the check that declines to preview a Jinja
+ * transform and the check that blocks saving it cannot drift apart.
+ */
+const JINJA_PATTERN = /\{\{|\{%|\{#/;
+
+/**
+ * The column whose filters are mirrored.
+ *
+ * `partition_mapped_column` is an explicit override; `null` means "follow the
+ * default datetime column", so re-pointing that column moves the mapping with
+ * it. Mirrors `SqlaTable.partition_filter_mapping_summary` on the backend.
+ */
+export function resolveMappedColumn(
+ datasource: PartitionMappingDatasource,
+): string | null {
+ if (!datasource.partition_column) {
+ return null;
+ }
+ return datasource.partition_mapped_column || datasource.main_dttm_col || null;
+}
+
+/** Whether the mapped column came from `main_dttm_col` rather than an override. */
+export function mappedColumnIsImplicit(
+ datasource: PartitionMappingDatasource,
+): boolean {
+ return Boolean(
+ datasource.partition_column &&
+ !datasource.partition_mapped_column &&
+ datasource.main_dttm_col,
+ );
+}
+
+/**
+ * Whether a transform is worth spending a preview request on.
+ *
+ * A necessary condition, never a sufficient one: the server stays the authority
+ * on whether a transform is usable, and anything this cannot see -- an
+ * unparseable expression, a non-deterministic function -- still comes back from
+ * it. What this catches is the cases that are knowably hopeless while the owner
+ * is still typing, which would otherwise spend the per-user preview budget and
+ * leave none for the transform they eventually finish writing.
+ */
+export function transformCanPreview(
+ transform: string | null | undefined,
+ mappedColumn?: string | null,
+ partitionColumn?: string | null,
+): boolean {
+ const trimmed = transform?.trim();
+ if (!trimmed) {
+ return false;
+ }
+ // Without the placeholder there is no value to substitute, so the transform
+ // is inert however well-formed it is.
+ if (!/:value\b/.test(trimmed)) {
+ return false;
+ }
+ // Jinja is rejected on save, so previewing it is pointless.
+ if (JINJA_PATTERN.test(trimmed)) {
+ return false;
+ }
+ // A column cannot stand in for itself; the backend rejects this outright.
+ if (mappedColumn && partitionColumn && mappedColumn === partitionColumn) {
+ return false;
+ }
+ return true;
+}
+
+/**
+ * Whether the mapping will actually mirror anything.
+ *
+ * Drives the choice between the green "filters will automatically apply"
+ * message and the warning that nothing is mirrored yet, so "non-blank text in
+ * the box" is not a good enough test: a transform with no `:value` to
+ * substitute, or one carrying Jinja, is as inert as an empty one and the
+ * backend's own summary reports it inactive. Claiming otherwise tells an owner
+ * their queries are pruning when they are not.
+ *
+ * Shares `transformCanPreview`'s conditions rather than restating them, and is
+ * necessary rather than sufficient for the same reason: an unparseable
+ * expression or a non-deterministic function needs a SQL parser to spot, so the
+ * server stays the authority -- `valueTransformIssues` surfaces what it says at
+ * the transform field itself.
+ */
+export function mappingIsActive(
+ datasource: PartitionMappingDatasource,
+ columns: PartitionMappingColumn[],
+): boolean {
+ const mappedColumnName = resolveMappedColumn(datasource);
+ if (!mappedColumnName || mappedColumnName === datasource.partition_column) {
+ return false;
+ }
+ const mappedColumn = columns.find(
+ column => column.column_name === mappedColumnName,
+ );
+ return transformCanPreview(
+ mappedColumn?.partition_value_transform,
+ mappedColumnName,
+ datasource.partition_column,
+ );
+}
+
+/**
+ * What is wrong with one column's value transform, if anything.
+ *
+ * Split out of `partitionMappingErrors` because the two callers disagree about
+ * which text to judge. The save gate reads the committed column record; the
+ * field's own message has to describe the text on screen, which lags the commit
+ * by a debounce. Passing the transform separately lets both ask the same
+ * question about different values instead of reimplementing the checks.
+ */
+export function valueTransformIssues(
+ column: PartitionMappingColumn | undefined,
+ transform: string | null | undefined,
+): PartitionMappingIssue[] {
+ if (!column) {
+ return [];
+ }
+
+ if (JINJA_PATTERN.test(transform ?? '')) {
+ return [
+ {
+ field: 'partition_value_transform',
+ message: t(
+ 'Jinja templating is not supported in a partition value transform. The transform is evaluated in a different context and at a different time from the chart query, so a template would not render the same way.',
+ ),
+ },
+ ];
+ }
+
+ // A temporal column falls back on the engine's own default, so leaving the box
+ // empty there only makes the mapping inactive -- which the dataset-level
+ // warning already says. A non-temporal column has nothing to fall back on.
+ if (!column.is_dttm && !transform?.trim()) {
+ return [
+ {
+ field: 'partition_value_transform',
+ message: t(
+ 'A value transform is required on %(name)s, which is not a temporal column. Use :value for each value.',
+ { name: column.column_name },
+ ),
+ },
+ ];
+ }
+
+ return [];
+}
+
+/**
+ * Everything wrong with the mapping that should stop the save.
+ *
+ * The client half of `validate_partition_mapping` in
+ * `superset/connectors/sqla/partition_mapping.py`, restricted to its blocking
+ * (Tier 1) issues. Those are the ones the PUT would reject anyway, so catching
+ * them here turns a 400 toast arriving after the modal closed into a disabled
+ * Save button that says why. Tier 2 is deliberately absent: an unparseable
+ * transform, or one missing `:value`, is "saved but stays inactive until it
+ * parses" per the PRD, and must not cost the owner the rest of their edits.
+ *
+ * One check is stricter than the backend's: an empty transform on a
+ * non-temporal mapped column blocks. The backend files that as Tier 2 for every
+ * column, but a non-temporal column has no default transform to fall back on --
+ * the field carries a required marker saying exactly this -- so the marker
+ * should mean something.
+ *
+ * Callers gate on the feature flag themselves, the way the two mount sites in
+ * `DatasourceEditor` already do; a dataset carrying a stale `partition_column`
+ * on an engine that cannot use one must not block a save the backend accepts.
+ */
+export function partitionMappingErrors(
+ datasource: PartitionMappingDatasource,
+ columns: PartitionMappingColumn[],
+): PartitionMappingIssue[] {
+ const partitionColumn = datasource.partition_column;
+ if (!partitionColumn) {
+ return [];
+ }
+
+ const issues: PartitionMappingIssue[] = [];
+ const columnNames = new Set(columns.map(column => column.column_name));
+
+ if (!columnNames.has(partitionColumn)) {
+ issues.push({
+ field: 'partition_column',
+ message: t('Partition column %(name)s is not a column on this dataset.', {
+ name: partitionColumn,
+ }),
+ });
+ }
+
+ const override = datasource.partition_mapped_column;
+ if (override && !columnNames.has(override)) {
+ issues.push({
+ field: 'partition_mapped_column',
+ message: t('Mapped column %(name)s is not a column on this dataset.', {
+ name: override,
+ }),
+ });
+ }
+
+ const mappedColumnName = resolveMappedColumn(datasource);
+ if (mappedColumnName === partitionColumn) {
+ // Only the *explicit* self-mapping blocks the save, matching
+ // `validate_partition_mapping`: an override naming the partition column is
+ // something the owner asked for and can take back, so it is Tier 1 there.
+ //
+ // The implicit one -- no override, and `main_dttm_col` happens to equal the
+ // partition column -- is Tier 2 on purpose. Blocking it here disabled Save
+ // on a dataset already in that state (metadata sync used to be able to
+ // produce one) even for a description-only edit, which is exactly the
+ // unsaveable dataset the backend comment says it avoids. The owner gets the
+ // same message, as a warning they can save through.
+ //
+ // No transform check can follow either way: the transform is a property of
+ // the mapped column, and there is no coherent mapped column to read it from.
+ issues.push({
+ field: 'partition_column',
+ blocking: Boolean(datasource.partition_mapped_column),
+ message: t(
+ 'The partition column cannot be mapped onto itself. %(name)s is both the partition column and the mapped column.',
+ { name: partitionColumn },
+ ),
+ });
+ return issues;
+ }
+
+ const mappedColumn = columns.find(
+ column => column.column_name === mappedColumnName,
+ );
+ issues.push(
+ ...valueTransformIssues(
+ mappedColumn,
+ mappedColumn?.partition_value_transform,
+ ),
+ );
+
+ return issues;
+}
+
+/** Which of the three row-expand treatments a column gets. */
+export function partitionRowState(
+ datasource: PartitionMappingDatasource,
+ columnName: string,
+): PartitionRowState {
+ if (!datasource.partition_column) {
+ return 'none';
+ }
+ if (columnName === datasource.partition_column) {
+ return 'partition';
+ }
+ return resolveMappedColumn(datasource) === columnName ? 'mapped' : 'unmapped';
+}
+
+/**
+ * The transform to pre-fill when a column becomes the mapped one.
+ *
+ * Only temporal columns get one, and only when the engine supplies it:
+ * `unix_timestamp(:value)` is Hive-family syntax and would not parse on
+ * Postgres or BigQuery, so a wrong default is worse than none.
+ */
+export function defaultTransformFor(
+ datasource: PartitionMappingDatasource,
+ column: PartitionMappingColumn | undefined,
+): string {
+ if (!column?.is_dttm) {
+ return '';
+ }
+ return datasource.partition_value_transform_default || '';
+}
+
+/** Declared types whose values are numbers rather than strings. */
+const NUMERIC_TYPE_RE =
+ /INT|NUMERIC|DECIMAL|DOUBLE|FLOAT|REAL|NUMBER|BIGNUMERIC/i;
+
+/**
+ * Samples the preview evaluates the transform at.
+ *
+ * Temporal columns get one timestamp, because a time-range bound is what they
+ * are mapped for. Everything else gets two values, so the preview demonstrates
+ * the element-wise `IN` an ordinary categorical filter actually produces.
+ *
+ * The samples follow the column's declared type, not just whether it is
+ * temporal. A mapped integer column with `CAST(:value AS INTEGER)` is a real
+ * configuration, and evaluating it at `'US'` makes the engine reject a transform
+ * that an actual `IN (2025, 2026)` filter would mirror perfectly well -- the
+ * preview was reporting a fault in its own sample data.
+ */
+export function sampleValuesFor(
+ column: PartitionMappingColumn | undefined,
+): string[] {
+ if (column?.is_dttm) {
+ return ['2026-01-15 00:00:00'];
Review Comment:
Addressed on Hugh's behalf in dee9cca8f8: `sampleValuesFor` now generates the sample in the column's stored representation for a numeric temporal column. It uses `1768435200` for `epoch_s`, `1768435200000` for `epoch_ms`, and the plain numeric samples for any other format, never a timestamp string. Non-numeric temporal columns still get the timestamp. `python_date_format` was added to `PartitionMappingColumn`, with unit tests in `utils.test.ts`. I couldn't run jest locally, so this relies on CI.
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/PartitionColumnFields.tsx:
##########
@@ -0,0 +1,319 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { useMemo } from 'react';
+import { t } from '@apache-superset/core/translation';
+import { css, useTheme } from '@apache-superset/core/theme';
+import { Alert } from '@apache-superset/core/components';
+import {
+ Button,
+ Flex,
+ Icons,
+ InfoTooltip,
+ Label,
+ Select,
+ Tooltip,
+ Typography,
+} from '@superset-ui/core/components';
+import {
+ mappedColumnIsImplicit,
+ mappingIsActive,
+ partitionMappingErrors,
+ resolveMappedColumn,
+ suggestedMappedColumn,
+} from './utils';
+import type {
+ PartitionMappingColumn,
+ PartitionMappingDatasource,
+ PartitionMappingIssue,
+} from './types';
+
+interface PartitionColumnFieldsProps {
+ datasource: PartitionMappingDatasource;
+ /**
+ * Physical columns: what the partition-column dropdown may offer, and where
+ * a replacement mapped column may be suggested from. A calculated column
+ * belongs in neither -- the engine cannot partition on an expression, and
+ * the mapping picker only renders on a physical column's row.
+ */
+ columns: PartitionMappingColumn[];
+ /**
+ * Every column on the dataset, physical and calculated. What *exists* is a
+ * different question from what may be picked, and validation asks the first:
+ * the backend accepts a calculated column as the mapped-column override, so
+ * checking existence against the physical columns alone reported a column
+ * that is really there as missing -- and blocked Save with no way out, since
+ * the dropdown cannot offer it back.
+ */
+ allColumns: PartitionMappingColumn[];
+ onPartitionColumnChange: (columnName: string | null) => void;
+ /** Open the given column's row expand in the Columns table. */
+ onNavigateToColumn: (columnName: string) => void;
+ /**
+ * Whether the mapped column's own preview says the transform mirrors, or
+ * `null`/undefined when no verdict is in yet. The checks this section can
+ * make are all static -- a transform the database rejects clears every one
+ * of them -- so without the preview's answer the banner claimed a speed-up
+ * the query never delivers.
+ */
+ previewMirrors?: boolean | null;
+}
+
+/**
+ * "Partition column" and the computed "Maps to partition" (wireframes 1a, 1g).
+ *
+ * "Maps to partition" is deliberately read-only. It reflects
+ * `partition_mapped_column ?? main_dttm_col`, and a peer dropdown would let it
+ * drift from the default datetime column silently. The only way to override it
+ * is from the target column's own row, where a transform has to be supplied
+ * alongside.
+ */
+export default function PartitionColumnFields({
+ datasource,
+ columns,
+ allColumns,
+ onPartitionColumnChange,
+ onNavigateToColumn,
+ previewMirrors,
+}: PartitionColumnFieldsProps) {
+ const theme = useTheme();
+
+ const options = useMemo(
+ () =>
+ columns.map(column => ({
+ value: column.column_name,
+ label: column.column_name,
+ customLabel: (
+ <Flex align="center" gap={theme.sizeUnit}>
+ <span>{column.column_name}</span>
+ {column.type && <Label>{column.type}</Label>}
+ </Flex>
+ ),
+ })),
+ [columns, theme.sizeUnit],
+ );
+
+ const mappedColumn = resolveMappedColumn(datasource);
+ const isImplicit = mappedColumnIsImplicit(datasource);
+ // The static checks are necessary, not sufficient: an unparseable expression
+ // or a function the database does not have needs the engine to spot, and the
+ // mapped column's row already asks it. Deferring to that answer where there
+ // is one is what keeps this banner and that panel from contradicting each
+ // other. A stored transform whose last probe failed says the same thing
+ // through the datasource's own summary, which is what an owner sees on
+ // reopening the editor.
+ const isActive =
+ mappingIsActive(datasource, allColumns) &&
+ previewMirrors !== false &&
+ datasource.partition_filter_mapping?.evaluable !== false;
+ const { partition_column: partitionColumn } = datasource;
+
+ // `field` is what the issues carry it for: a message about the partition
+ // column belongs under the partition column, not only in the Save button's
+ // tooltip, where an owner has to guess which of the two selects is at fault.
+ const issues = useMemo(
+ () => partitionMappingErrors(datasource, allColumns),
+ [datasource, allColumns],
+ );
+ const issueFor = (field: PartitionMappingIssue['field']) =>
+ issues.find(issue => issue.field === field)?.message;
+
+ // "Map a different column instead" normally opens the currently-mapped
+ // column's row, which is where the picker lives. When the mapped column *is*
+ // the partition column -- the self-mapping the backend rejects, and reachable
+ // in one click because the picker offers every column -- that row renders no
+ // mapping section at all, so the one guided way out of the broken state led
+ // nowhere. Offer a column that is not the partition column instead.
+ //
+ // Null only when there is no mapped column at all, which is also when the
+ // block below does not render -- but a dataset whose every column is the
+ // partition column would otherwise be offered a link to nothing, so the link
+ // is guarded rather than the type asserted away.
+ const differentColumnTarget =
+ mappedColumn && mappedColumn !== partitionColumn
+ ? mappedColumn
+ : (suggestedMappedColumn(columns, partitionColumn) ?? mappedColumn);
+
+ return (
+ <Flex vertical gap={theme.sizeUnit} data-test="partition-column-fields">
+ <Flex align="center" gap={theme.sizeUnit}>
+ <Typography.Text>{t('Partition column')}</Typography.Text>
+ <InfoTooltip
+ tooltip={t(
+ 'The physical column the engine partitions on. Filters on the mapped column are mirrored onto it so the engine can prune partitions.',
+ )}
+ />
+ </Flex>
+ <Select
+ ariaLabel={t('Partition column')}
+ options={options}
+ value={partitionColumn ?? undefined}
+ onChange={value => onPartitionColumnChange((value as string) ?? null)}
+ onClear={() => onPartitionColumnChange(null)}
+ placeholder={t('None')}
+ allowClear
+ data-test="partition-column-select"
+ />
+ {issueFor('partition_column') && (
+ <Typography.Text type="danger" data-test="partition-column-error">
+ {issueFor('partition_column')}
+ </Typography.Text>
+ )}
+ <Typography.Text type="secondary">
+ {t(
+ "Column used for partition pruning on this table. Selecting one hides it from Explore's dimension and filter pickers by default.",
+ )}
+ </Typography.Text>
+
+ {partitionColumn && (
+ <Flex vertical gap={theme.sizeUnit} data-test="maps-to-partition">
+ <Flex align="center" gap={theme.sizeUnit}>
+ <Typography.Text type="secondary">
+ {t('Maps to partition')}
+ </Typography.Text>
+ <InfoTooltip
+ tooltip={t(
+ 'The column whose filters are mirrored. It follows the default datetime column unless a different column holds the mapping.',
+ )}
+ />
+ </Flex>
+
+ {mappedColumn ? (
+ <>
+ <Flex align="center" gap={theme.sizeUnit}>
+ <Label>{mappedColumn}</Label>
+ {isImplicit && (
+ <>
+ <Typography.Text type="secondary">
+ {t('Default datetime column')}
+ </Typography.Text>
+ <Tooltip
+ title={t(
+ 'Set from the default datetime column above, so re-pointing that column moves the mapping with it.',
+ )}
+ >
+ <Icons.LockOutlined
+ iconSize="s"
+ iconColor={theme.colorTextTertiary}
+ />
+ </Tooltip>
+ </>
+ )}
+ </Flex>
+ {issueFor('partition_mapped_column') && (
+ <Typography.Text
+ type="danger"
+ data-test="partition-mapped-column-error"
+ >
+ {issueFor('partition_mapped_column')}
+ </Typography.Text>
+ )}
+ <Typography.Text type="secondary">
+ {t(
+ 'Filters on this column are mirrored onto the partition column.',
+ )}
+ {differentColumnTarget && (
+ <>
+ {' '}
+ <Button
+ buttonStyle="link"
+ onClick={() => onNavigateToColumn(differentColumnTarget)}
+ data-test="map-a-different-column"
+ >
+ {t('Map a different column instead →')}
+ </Button>
+ </>
+ )}
+ </Typography.Text>
+ {isActive ? (
+ <Alert
+ type="info"
+ showIcon
+ icon={<Icons.FilterOutlined />}
+ message={
+ <span>
+ {t(
+ 'Filters on %(mapped)s will automatically apply an equivalent filter to %(partition)s.',
+ { mapped: mappedColumn, partition: partitionColumn },
+ )}{' '}
+ <Button
+ buttonStyle="link"
+ onClick={() => onNavigateToColumn(mappedColumn)}
+ >
+ {t('Customize the value transform →')}
+ </Button>
+ </span>
+ }
+ />
+ ) : (
+ <Alert
+ type="warning"
+ showIcon
+ message={t(
+ 'No value transform is set on %(mapped)s, so nothing is mirrored yet and queries will scan every partition.',
+ { mapped: mappedColumn },
+ )}
+ />
+ )}
+ </>
+ ) : (
+ <>
+ <Flex align="center" gap={theme.sizeUnit}>
+ <Label
+ css={css`
+ color: ${theme.colorTextTertiary};
+ `}
+ >
+ {t('No mapping')}
+ </Label>
+ <Button
+ buttonStyle="link"
+ onClick={() => {
+ const candidate = suggestedMappedColumn(
+ columns,
+ partitionColumn,
+ );
+ if (candidate) {
+ onNavigateToColumn(candidate);
+ }
+ }}
+ data-test="map-a-column"
+ >
+ {t('Map a column →')}
+ </Button>
+ </Flex>
+ <Typography.Text type="secondary">
+ {t(
+ 'Normally the default datetime column, but none is set on this dataset.',
+ )}
+ </Typography.Text>
+ <Alert
+ type="warning"
+ showIcon
+ message={t(
+ '%(partition)s is hidden from Explore, but no filter is mirrored onto it — queries will scan every partition until a column is mapped.',
Review Comment:
Your suggested warning text was applied earlier. On Hugh's behalf, e61585070e also fixes the helper text under the selector, which still said that choosing a partition column hides it from Explore's pickers. It now says the column's Is filterable / Is dimension settings decide whether Explore offers it, and the existing test also asserts the old phrase is gone. Catalogs regenerated in d808efd1f0.
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,1314 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` always -- ``T`` is a function
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import re
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLStatement
+from superset.utils import json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: Every entry point enforces it -- the typed column field, the import schema
+#: and the preview request -- because `is_transform_active` parses the stored
+#: value on each Explore load, and an unbounded string would make that parse
+#: the expensive part of rendering a chart.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
Review Comment:
Helping on Hugh's behalf. No code change in this pass, and I'm leaving this open for Hugh and you. Engine-level comparison semantics are covered by f3f49af437: `equality_mirrors_safely` withdraws `=`/`IN` on string columns unless the engine spec declares `binary_string_comparison`. The case you describe, a column with its own collation (`COLLATE NOCASE`) on an otherwise byte-exact engine, is still not detected, because neither SQLAlchemy reflection nor the engine specs expose per-column collation. It's documented as an owner assumption next to `p = T(mapped_col)`. Two ways to close it would be an explicit per-mapping opt-in for exact string equality, or reflecting collation where engines expose it. Both are product decisions I'd rather Hugh make than guess.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "hughhhh (via GitHub)" <gi...@apache.org>.
hughhhh commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4162113317
##########
superset-frontend/src/explore/components/controls/DateFilterControl/DateFilterLabel.tsx:
##########
@@ -406,7 +408,12 @@ export default function DateFilterLabel(props: DateFilterControlProps) {
{...props}
onDescriptionHoverChange={setIsDescriptionHovered}
/>
- {popoverContent}
+ {/* The glyph sits outside the popover trigger so clicking it opens the
+ tooltip rather than the time-range editor. */}
+ <Flex align="center" gap={theme.sizeUnit}>
+ {popoverContent}
+ <PartitionPruningIndicator mapping={props.partitionMapping} />
Review Comment:
Fixed in `f06a9ad100` / `46e4cd7c54` (earlier on this branch) + `1e132aefc9`. The control is handed a mapping only when the range resolves to a bound and the selected temporal column is the mapped one. `1e132aefc9` closed the two holes left in that gate: a `time_range` that is absent rather than `No filter`, and the `always_filter_main_dttm` path firing with no granularity selected.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "geido (via GitHub)" <gi...@apache.org>.
geido commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4361509756
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/DatasourceEditor.tsx:
##########
@@ -1365,19 +1695,76 @@ function DatasourceEditor({
try {
const newCols = await fetchSyncedColumns(datasource, signal);
+ // Everything past the `await` reads the refs rather than the closure;
+ // see their declaration.
+ const liveColumns = currentColumnsRef.current;
+ const liveDatasource = datasourceRef.current;
+
const columnChanges = updateColumns(
- datasource.columns,
+ liveColumns,
Review Comment:
I think merging against `liveColumns` has a side effect with the flag off. If I delete a column row that still exists in the source and then sync, it comes back with a `nanoid()` id, so the save fails with "One or more columns already exist" (master reused the old row and saved fine). Could the merge fall back to `datasource.columns` for names missing from `liveColumns`?

[mp4](https://gist.githubusercontent.com/geido/2e9a0de274464f8bac4b8ac43e8888e9/raw/bug2-sync-after-delete.mp4)
##########
superset/db_engine_specs/base.py:
##########
@@ -580,6 +580,47 @@ def normalize_custom_sql_metric(cls, expression: str) -> str:
allows_joins = True
allows_subqueries = True
allows_alias_in_select = True
+ # Appended to a ``SELECT`` that has no ``FROM`` -- evaluating expressions
+ # and nothing else. Most engines accept a bare ``SELECT 1``; Oracle, DB2
+ # and Db2 for i require a one-row table to select it from.
+ select_without_from_suffix: str = ""
+ # Whether ``=`` on a text column compares byte-exactly by default: no case
+ # folding, no trailing-space padding, no accent insensitivity.
+ #
+ # Partition filter mapping needs this. It mirrors ``col = v`` onto
+ # ``partition_col = T(v)`` on the strength of ``col = v`` implying
+ # ``T(col) = T(v)``, which holds for value equality and not for SQL
+ # equality: under a case-insensitive collation a stored ``'us'`` satisfies
+ # a filter for ``'US'``, while the mirror ``hex('US')`` excludes the row,
+ # and the chart silently loses it. False by default, so a spec that has
+ # not said so does not mirror string equality.
+ #
+ # This speaks for the engine's *default* comparison only. A column
+ # declaring its own non-binary collation (``country COLLATE NOCASE``) is
+ # invisible to Superset -- nothing in SQLAlchemy's reflection or the engine
+ # specs exposes it -- so on such a column the assumption remains the
+ # owner's, like ``p = T(mapped_col)`` itself.
+ binary_string_comparison: bool = False
+
+ # Every text form this engine reads as a date or timestamp when one is
+ # compared against a temporal column. `strftime`/`strptime` patterns.
+ #
+ # Partition filter mapping needs this. A bucketing key such as
+ # ``to_char(:value, 'YYYYMMDD')`` is legitimately text, so the mirror
+ # ``part_date = '20260115'`` has to be allowed against a ``DATE`` partition
+ # column -- but only where the engine reads it, because comparing a
+ # temporal column against text is an implicit coercion an engine need not
+ # have. Trino has no VARCHAR-to-DATE comparison and BigQuery coerces only a
+ # canonical ``YYYY-MM-DD`` *literal*, so on those even plain ISO text fails
+ # the whole chart rather than merely losing the pruning -- which is why the
+ # ISO forms are declared here too rather than assumed universal.
+ #
+ # Empty by default, so an engine Superset has not confirmed declines the
+ # mirror and keeps the query working. Declared on concrete specs, not on a
+ # shared base: `PostgresBaseEngineSpec` is inherited by Snowflake, whose
+ # AUTO date input reads an all-digit string as epoch seconds instead.
+ temporal_literal_formats: tuple[str, ...] = ()
Review Comment:
IIUC this guard only covers `str` results, while a `date`/`datetime` result is written by the Trino dialect as the same bare string. On Trino, `date(CAST(:value AS TIMESTAMP))` onto a DATE `dt` previews as valid, then the chart fails with "Cannot apply operator: date <= varchar(10)" (`=`/`IN` too). Could these get the `_reads_as_temporal` check, or a typed literal, so only pruning is lost?

[mp4](https://gist.githubusercontent.com/geido/2e9a0de274464f8bac4b8ac43e8888e9/raw/bug1-trino-date-partition.mp4)
##########
superset-frontend/src/explore/components/controls/DateFilterControl/DateFilterLabel.tsx:
##########
@@ -420,7 +422,12 @@ export default function DateFilterLabel(props: DateFilterControlProps) {
{...props}
onDescriptionHoverChange={setIsDescriptionHovered}
/>
- {popoverContent}
+ {/* The glyph sits outside the popover trigger so clicking it opens the
+ tooltip rather than the time-range editor. */}
+ <Flex align="center" gap={theme.sizeUnit}>
Review Comment:
I think this `Flex` changes the layout with the flag off too. The trigger span becomes a flex item, so the Time Range box in the ad-hoc filter popover shrinks to its label instead of filling the popover like on master (250px vs 320px here). Would rendering the `Flex` only when `partitionMapping` is set keep the old markup?

[gif](https://gist.githubusercontent.com/geido/2e9a0de274464f8bac4b8ac43e8888e9/raw/bug3-time-range-width.gif) · [mp4](https://gist.githubusercontent.com/geido/2e9a0de274464f8bac4b8ac43e8888e9/raw/bug3-time-range-width.mp4)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "geido (via GitHub)" <gi...@apache.org>.
geido commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4366311176
##########
superset/datasets/api.py:
##########
@@ -2064,6 +2165,134 @@ def get(self, id_or_uuid: str, **kwargs: Any) -> Response:
entity_concurrency_token(SqlaTable, table.id, table.uuid),
)
+ @expose("/<int:pk>/partition_mapping/preview/", methods=("POST",))
+ @protect()
+ @safe
+ @statsd_metrics
+ @event_logger.log_this_with_context(
+ action=lambda self, *args, **kwargs: (
+ f"{self.__class__.__name__}.partition_mapping_preview"
+ ),
+ log_to_statsd=False,
+ )
+ def partition_mapping_preview(self, pk: int) -> Response:
Review Comment:
Thanks! The midnight sample is refused now, but the editor previews a TIMESTAMP column at `10:47:23`, where the text probe is declined first, so it still says Valid. Charts don't run the check: set up in the editor, 06:30-18:30 returns 0 rows vs 48 with the flag off, and with `NLS_DATE_FORMAT='YYYY-MM-DD'` the preview looks right but totals are short. Could the chart path compare both shapes too?

[mp4](https://gist.githubusercontent.com/geido/2e9a0de274464f8bac4b8ac43e8888e9/raw/final-oracle-todate-ui.mp4) · [NLS_DATE_FORMAT='YYYY-MM-DD': preview looks right, 482 vs 554 rows](https://gist.githubusercontent.com/geido/2e9a0de274464f8bac4b8ac43e8888e9/raw/final-oracle-todate-iso-nls.gif) ([mp4](https://gist.githubusercontent.com/geido/2e9a0de274464f8bac4b8ac43e8888e9/raw/final-oracle-todate-iso-nls.mp4))
##########
superset/models/helpers.py:
##########
@@ -4552,36 +4661,777 @@ def dttm_sql_literal(self, dttm: datetime, col: "TableColumn") -> str:
return f"""'{dttm.strftime("%Y-%m-%d %H:%M:%S.%f")}'"""
- def get_time_filter( # pylint: disable=too-many-arguments # noqa: C901
+ def _mirror_probe_value(self, dttm: datetime, col: Optional["TableColumn"]) -> Any:
+ """
+ ``dttm`` in the mapped column's own stored representation.
+
+ The predicate this mirror stands in for compares the column against
+ `dttm_sql_literal(dttm, col)`, so the transform has to be probed with
+ the same value. On a column stored as an epoch integer, ``T`` is a
+ function of an integer: probing it with a `datetime` either returns
+ something unrelated to the partition keys or raises, and a raise costs
+ the dataset its pruning silently.
+
+ Only the ``python_date_format`` branches of `dttm_sql_literal` are
+ reproduced, because only those produce a *value*. `convert_dttm` yields
+ engine-specific SQL text, which cannot be bound as a parameter; its own
+ divergence from the probe is handled by widening the bounds instead
+ (`_engine_literal_resolution`).
+
+ In `dttm_sql_literal`'s own order, though: it asks ``convert_dttm``
+ first and reaches the format only when the engine answers nothing. A
+ column can carry both -- a TIMESTAMP with a ``%Y%m%d``
+ ``python_date_format``, or an entry in
+ ``python_date_format_by_column_name`` -- and applying the format
+ unconditionally probed a value the real predicate never compares.
+ ``event_time >= '2026-01-01 00:00:00'`` mirrored as
+ ``partition_col >= '20260101'``, and a January 15 row keyed
+ ``2026-01-15`` sorts below that string, so the chart lost a row the
+ filter keeps.
+
+ Where the engine does answer, the `datetime` is returned unchanged and
+ the widening path takes over -- which is exactly what already happens
+ for every temporal column that carries no format at all.
+ """
+ if col is None:
+ return dttm
+
+ if col.type and self.db_engine_spec.convert_dttm(
+ col.type, dttm, db_extra=self.db_extra
+ ):
+ # The format is unreachable in `dttm_sql_literal` for this column,
+ # so reproducing it here would describe a different bound.
+ return dttm
+
+ tf = col.python_date_format
+ if not tf and self.db_extra:
+ tf = self.db_extra.get("python_date_format_by_column_name", {}).get(
+ col.column_name
+ )
+ if not tf:
+ return dttm
+
+ if tf in EPOCH_FORMATS:
+ dttm_tz_aware = dttm
+ if dttm_tz_aware.tzinfo is None:
+ dttm_tz_aware = dttm_tz_aware.replace(tzinfo=timezone.utc)
+ return int(dttm_tz_aware.timestamp()) * EPOCH_FORMATS[tf]
+ return dttm.strftime(tf)
+
+ def _engine_literal_resolution(
+ self, dttm: datetime, col: Optional["TableColumn"]
+ ) -> LiteralResolution:
+ """
+ How much of ``dttm`` survives into this engine's literal for ``col``.
+
+ The real predicate compares `dttm_sql_literal(dttm, col)`, so whatever
+ that literal throws away is a bound the engine never sees. A mirror
+ derived from the full precision then describes a *narrower* range than
+ the predicate it stands in for -- and narrower means it drops rows the
+ filter keeps.
+
+ Two things get thrown away in practice:
+
+ - the sub-second part. SQLite renders a timestamp with
+ ``timespec="seconds"``.
+ - the time of day entirely. Every engine spec with a ``types.Date``
+ branch renders ``dttm.date().isoformat()``, so Presto, Trino,
+ BigQuery and some two dozen others answer `DATE '2026-01-01'` for a
+ bound of 10:00 -- and `T(DATE '2026-01-01')` is below the mirror's
+ own lower bound, so the whole first day is dropped.
+
+ Detected rather than enumerated per engine, because the branch depends
+ on the column's type as well as the spec: instants differing only in the
+ part under test render as the same text exactly when the engine has
+ thrown that part away.
+
+ The day test uses two fixed times of day rather than ``dttm`` and one
+ alternative, so a bound that happens to sit on the hour the alternative
+ uses cannot read as "no time at all". Neither probe sits at midnight on
+ purpose: SQLite renders a DATE column at exactly midnight as a bare
+ date, so a midnight probe would differ from its alternative for a
+ reason that has nothing to do with resolution.
+
+ Likewise both sub-second probes carry a non-zero remainder. Comparing
+ against ``dttm`` truncated to the second looks like the obvious test and
+ is wrong for the same formatting-boundary reason.
+
+ A non-temporal column has no answer here, and asking anyway gets a wrong
+ one. SQLite's ``convert_dttm`` renders for ``types.String`` as well as
+ for the date types, so a ``VARCHAR`` mapped column reads as
+ second-resolution -- and a filter value that happens to *look* like an
+ instant then has its bound rounded as though the engine had truncated
+ it. On a VARCHAR ``code`` mapped onto a VARCHAR ``p`` by ``:value``,
+ ``code < '2026-07-06T10:08:11.500000'`` was mirrored as
+ ``p <= '2026-07-06 10:08:12.000000'``; a space sorts before ``T``, so a
+ row holding ``2026-07-06T09:00:00`` fell outside the mirror while
+ matching the filter.
+
+ The guard lives here rather than in each caller so this and
+ `_column_literal_resolution` cannot disagree about which column is
+ coarse -- which is the same reason that helper delegates to this one.
+
+ "Temporal" is the column's generic type, not just its ``is_dttm`` flag.
+ `get_time_filter` renders a bound through ``convert_dttm`` for any
+ ``DATE`` column, flagged or not, so a ``DATE`` column left unflagged
+ still compares a bare day -- and skipping the resolution check there
+ would hand the probe 10:00 for a bound the engine reads as midnight.
+ """
+ if col is None or not col.type or col.type_generic != GenericDataType.TEMPORAL:
+ return LiteralResolution.FULL
+
+ def render(moment: datetime) -> Optional[str]:
+ return self.db_engine_spec.convert_dttm(
+ col.type, moment, db_extra=self.db_extra
+ )
+
+ try:
+ early = render(dttm.replace(hour=1, minute=2, second=3, microsecond=444444))
+ late = render(
+ dttm.replace(hour=22, minute=33, second=44, microsecond=555555)
+ )
+ if early is not None and early == late:
+ return LiteralResolution.DAY
+
+ # Flooring to the second is a no-op on a bound that has no
+ # sub-second part, so there is nothing to detect.
+ if not dttm.microsecond:
+ return LiteralResolution.FULL
+
+ first = render(dttm.replace(microsecond=111111))
+ second = render(dttm.replace(microsecond=222222))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return LiteralResolution.FULL
+
+ if first is not None and first == second:
+ return LiteralResolution.SECOND
+ return LiteralResolution.FULL
+
+ def _round_bounds_outward(
self,
- time_col: "TableColumn",
+ start_dttm: Optional[datetime],
+ end_dttm: Optional[datetime],
+ col: Optional["TableColumn"],
+ ) -> tuple[Optional[datetime], Optional[datetime]]:
+ """
+ The bounds widened to whatever the engine's literal actually resolves to.
+
+ Rounding outward is never narrower than the predicate being mirrored,
+ which is the only property the mirror has to hold.
+ """
+ resolutions = {
+ self._engine_literal_resolution(bound, col)
+ for bound in (start_dttm, end_dttm)
+ if bound is not None
+ }
+
+ if LiteralResolution.DAY in resolutions:
+ # The engine compares a bare date, so the real predicate's lower
+ # bound is the start of that day and its upper bound admits the
+ # whole of the day before. Anything finer excludes rows it keeps.
+ if start_dttm is not None:
+ start_dttm = start_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ )
+ if end_dttm is not None and end_dttm != end_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ ):
+ end_dttm = end_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ ) + timedelta(days=1)
+ elif LiteralResolution.SECOND in resolutions:
+ if start_dttm is not None:
+ start_dttm = start_dttm.replace(microsecond=0)
+ if end_dttm is not None and end_dttm.microsecond:
+ end_dttm = end_dttm.replace(microsecond=0) + timedelta(seconds=1)
+
+ return start_dttm, end_dttm
+
+ def _literal_is_coarser_than(
+ self, dttm: datetime, col: Optional["TableColumn"]
+ ) -> bool:
+ """
+ Whether the engine's literal for ``dttm`` throws away part of it.
+
+ Unlike a range, an equality cannot be widened outward, so the only safe
+ answer when the engine compares less than the full value is to decline
+ the mirror.
+ """
+ resolution = self._engine_literal_resolution(dttm, col)
+ if resolution is LiteralResolution.DAY:
+ return dttm != dttm.replace(hour=0, minute=0, second=0, microsecond=0)
+ if resolution is LiteralResolution.SECOND:
+ return bool(dttm.microsecond)
+ return False
+
+ def _column_literal_resolution(
+ self, col: Optional["TableColumn"]
+ ) -> LiteralResolution:
+ """
+ How much of *any* value this engine compares on ``col``.
+
+ `_engine_literal_resolution` answers about a particular instant, which
+ is what a mirror derived from one needs. Two callers have no instant to
+ ask about -- the summary the Explore glyph reads, and a filter value
+ `_instant_from_filter_value` cannot read as an instant at all -- and
+ both need the column's own answer. Through one helper so that the glyph
+ and the query path cannot disagree about which column is coarse, which
+ is the same reason `mirrorable_operators` is computed once.
+
+ A non-temporal column has no answer, and asking anyway gets a wrong one:
+ SQLite's ``convert_dttm`` renders for ``types.String`` as well as for the
+ date types, so a reference instant makes a ``VARCHAR`` mapped column look
+ second-resolution -- and ``country = 'US'``, the text half of this
+ feature, reads as a value the engine compares coarsely.
+
+ That guard is `_engine_literal_resolution`'s, not this function's. It
+ used to be here, on the belief that the per-instant callers never met
+ the case because they arrive only with a value that parsed as an
+ instant -- which is untrue of a text column holding ISO-shaped text,
+ where the value parses and the column is still not temporal.
+ """
+ return self._engine_literal_resolution(_RESOLUTION_REFERENCE_INSTANT, col)
+
+ def _round_bound_outward(
+ self,
+ instant: datetime,
+ col: Optional["TableColumn"],
+ *,
+ is_upper: bool,
+ ) -> datetime:
+ """
+ One bound widened to whatever the engine resolves ``col`` to.
+
+ `_round_bounds_outward` answers for a since/until pair, because a time
+ range is the shape it was written for. A single comparison is one end of
+ such a pair with the other end absent, and the widening is per-end
+ already -- a lower bound moves back, an upper bound forward.
+
+ Narrowing the return type is the other half of the point: a bound handed
+ in non-`None` comes back non-`None`, and saying so here saves every
+ caller from re-establishing it.
+ """
+ start_dttm, end_dttm = self._round_bounds_outward(
+ None if is_upper else instant,
+ instant if is_upper else None,
+ col,
+ )
+ rounded = end_dttm if is_upper else start_dttm
+ return rounded if rounded is not None else instant
+
+ def _in_column_number_type(self, value: Any, col: Optional["TableColumn"]) -> Any:
+ """
+ A numeric ``value`` in the number type the mapped column stores.
+
+ The engine compares a number against the column in the column's own
+ domain, so ``n = '1.0'`` on an integer ``n`` matches the row holding
+ ``1``. `filter_values_handler` hands over ``1.0``, though, and a
+ transform whose output depends on the representation --
+ ``CAST(:value AS TEXT)`` answers ``'1.0'`` where the row's key is
+ ``'1'`` -- then mirrors to a partition value no matching row holds.
+ Probing at the value the column would hold keeps ``T(col) = T(v)``.
+
+ Integer columns only. A non-integral value on an integer column is
+ returned unchanged -- it matches no row, so its mirror cannot drop one.
+
+ Nothing is converted for an approximate or exact decimal column, even
+ though ``1`` and ``1.0`` are the same number to a ``REAL``. What the
+ transform sees is the *literal*, and how an engine renders one is not
+ something the engine spec exposes: on PostgreSQL ``CAST(1.0 AS TEXT)``
+ is ``'1.0'`` while the ``REAL`` column holding that value renders as
+ ``'1'``, so coercing the value to ``float`` mirrored onto a partition
+ key no matching row holds -- the same failure this helper exists to
+ stop, in the other direction. A ``DECIMAL`` column says it louder,
+ since its text also depends on a scale the spec does not carry. For
+ both, the rendering stays the owner's assumption, like
+ ``p = T(mapped_col)`` itself.
+ """
+ if (
+ col is None
+ or not col.type
+ or isinstance(value, bool)
+ or not isinstance(value, (int, float, Decimal))
+ ):
+ return value
+ try:
+ column_spec = self.db_engine_spec.get_column_spec(
+ col.type, db_extra=self.db_extra
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return value
+ if column_spec is None:
+ return value
+ sqla_type = column_spec.sqla_type
+ type_class = sqla_type if isinstance(sqla_type, type) else type(sqla_type)
+ if issubclass(type_class, sa.Integer):
+ if isinstance(value, int):
+ return value
+ try:
+ return int(value) if value == int(value) else value
+ except (OverflowError, ValueError):
+ # Infinity and NaN have no integer, and match no integer row.
+ return value
+ return value
+
+ def _mirror_probe_input(
+ self,
+ operator: utils.FilterOperator,
+ value: Any,
+ col: Optional["TableColumn"],
+ ) -> Any:
+ """
+ ``value`` in the representation the mirror may probe the transform at.
+
+ A simple filter on a temporal column carries a *string*.
+ `filter_values_handler` rewrites only an all-digit value, which it reads
+ as epoch milliseconds, so ``'2026-07-06 10:08:11'`` reaches here exactly
+ as the chart author typed it and is bound as text. The engine compares
+ that text against the column under its own cast, and on a ``DATE``
+ column the cast drops the time of day: the filter keeps the whole of
+ 2026-07-06 while a mirror probed at 10:08:11 keeps one instant of it,
+ which is narrower than the predicate it stands in for.
+
+ So the text is read back into the instant it denotes -- the only way
+ `_engine_literal_resolution`, which answers about a `datetime`, reaches
+ a filter value at all -- and where the engine compares less of that
+ instant than the filter carries, what to do about it is a property of
+ the *operator*:
+
+ * a bound rounds outward, through the helper the range collector uses.
+ Reading one extra bucket at the edge is the trade this feature makes
+ everywhere else too -- see `mirror_operator` -- and the original
+ predicate is still in the query to exclude the rows that bucket adds.
+ * an equality, or one member of an ``IN`` list, has nowhere to widen to.
+ These entries are ``AND``-ed onto the query, so "or the day either
+ side" is not something this sink can express, and the request is
+ declined with `_UNMIRRORABLE`. The query is then correct and unpruned,
+ which is the one failure mode this feature is allowed.
+
+ An instant carrying a UTC offset is declined for every operator, a
+ bound included. Rounding one outward would first have to place it in the
+ frame the partition column was written in, and guessing that frame is
+ how a mirror ends up a whole offset narrower than the filter -- see the
+ load-bearing assumption in
+ `superset.connectors.sqla.partition_mapping`.
+
+ A *string* `_instant_from_filter_value` cannot read at all is declined on
+ the same terms, and for the same reason one more step back: there is no
+ instant to round. ``'07/06/2026 10:08:11'`` is not ISO 8601, so the
+ parser leaves it alone -- and Postgres casts that same text to a DATE and
+ keeps the whole of July 6 while the probe, handed the string verbatim,
+ evaluates the transform at 10:08:11 and asks for a partition key no row
+ holds. That is exactly the narrowing the ISO-only parser was written to
+ prevent, reached through a value it declines to read, so the decline has
+ to travel with it. Which costs a non-ISO *date* its pruning too, because
+ telling July 6 from June 7 is the guess that started this.
+
+ Only a string. `_as_probe_input` has already run, so the engine SQL
+ `filter_values_handler` returns for an epoch-millisecond bound arrives
+ here as a `RawProbeValue` rather than text -- and that literal was
+ rendered by the engine at the engine's own resolution, so it is the one
+ thing on this path with nothing left to resolve. The escaping gate has
+ run too, on the value as it arrived; a string this method *returns* is a
+ fresh one, which is why `evaluate_transform` asks again.
+
+ Where the engine compares the whole instant, a string is returned
+ exactly as it arrived -- down to the type the probe binds and the cache
+ key it lands on, because every query that was already correct has to
+ stay byte-for-byte correct. A `datetime` is still converted, which it
+ has always needed: on a column stored as an epoch integer the transform
+ is a function of an integer, and a `datetime` is not the value the real
+ predicate compares.
+ """
+ value = self._in_column_number_type(value, col)
+ parsed = _instant_from_filter_value(value)
+ if parsed is None:
+ if (
+ isinstance(value, str)
+ and self._column_literal_resolution(col) is not LiteralResolution.FULL
+ ):
+ return _UNMIRRORABLE
+ return value
+
+ # Ahead of the full-resolution return: a transform such as
+ # `CAST(:value AS TIMESTAMP)` drops the offset, so even an engine that
+ # compares the whole instant would probe it in the wrong frame. Its own
+ # reason, because mapping a column the engine compares in full -- the
+ # advice the resolution decline carries -- does not help here.
+ if parsed.tzinfo is not None:
+ return _UNMIRRORABLE_OFFSET
+
+ if self._engine_literal_resolution(parsed, col) is LiteralResolution.FULL:
+ return (
+ self._mirror_probe_value(parsed, col)
+ if isinstance(value, datetime)
+ else value
+ )
+
+ if operator in LOWER_BOUND_OPERATORS:
+ instant = self._round_bound_outward(parsed, col, is_upper=False)
+ elif operator in UPPER_BOUND_OPERATORS:
+ instant = self._round_bound_outward(parsed, col, is_upper=True)
+ elif self._literal_is_coarser_than(parsed, col):
+ return _UNMIRRORABLE
+ else:
+ instant = parsed
+
+ if instant == parsed and not isinstance(value, datetime):
+ return value
+ return self._mirror_probe_value(instant, col)
+
+ def _collect_partition_mirror_range(
+ self,
+ mapping: Optional["PartitionMapping"],
+ sink: list[tuple[utils.FilterOperator, Any]],
+ column_name: str,
start_dttm: Optional[sa.DateTime],
end_dttm: Optional[sa.DateTime],
- time_grain: Optional[str] = None,
- label: Optional[str] = "__time",
- template_processor: Optional[BaseTemplateProcessor] = None,
- ) -> Optional[ColumnElement]:
- col = (
- time_col.get_timestamp_expression(
- time_grain=time_grain,
- label=label,
- template_processor=template_processor,
+ widen_bounds_by: Optional[relativedelta] = None,
+ ) -> None:
+ """
+ Record a time range for mirroring onto the partition column.
+
+ The bounds are adjusted first, by the same helper `get_time_filter` uses:
+ the mirrored predicate has to describe the same instants as the
+ timestamp predicate it stands in for, or the pruning is wrong by exactly
+ the dataset's timezone offset -- silently.
+
+ Either bound may be `None` for an open-ended range, in which case only
+ the bound that exists is mirrored.
+
+ Both bounds are recorded with the operators the real predicate uses,
+ `>=` and `<`. Relaxing the strict one is `mirror_operator`'s job, at the
+ single point where an operator becomes SQL -- which is also the point
+ the preview endpoint goes through.
+
+ `widen_bounds_by` is one grain bucket width, passed when the filter this
+ stands in for compares a *truncated* column. The real predicate then
+ keeps rows the raw bounds exclude, and widening both ends by one bucket
+ is the smallest range guaranteed to contain all of them -- see the "Time
+ grains" section of `superset.connectors.sqla.partition_mapping`.
+
+ A widened range can also be wide enough to fail `_bounds_are_ordered`
+ against a tighter filter on the same column. That fails open -- no
+ mirroring, no pruning, no dropped rows.
+ """
+ if mapping is None or column_name != mapping.mapped_column:
+ return
+ if not mapping.mirrors(utils.FilterOperator.TEMPORAL_RANGE):
+ return
+
+ # Resolve the column so the offset adjustment sees the same type
+ # `get_time_filter` does -- an offset the column's type cannot represent
+ # is dropped, and the mirrored bounds have to agree with the originals.
+ mapped_col = next(
+ (col for col in self.columns if col.column_name == column_name), None
+ )
+ start_dttm, end_dttm = self.adjust_time_bounds(start_dttm, end_dttm, mapped_col)
+
+ # Adjust first, then widen. `adjust_time_bounds` moves the naive UI
+ # bounds into the frame the column is *stored* in, and the grain
+ # truncation in the real predicate happens in that same frame, so the
+ # bucket width has to be added there too. The two commute for the
+ # hour-offset branch but not for the `ZoneInfo` one, where widening
+ # across a DST boundary first lands an hour out.
+ if widen_bounds_by is not None:
+ if start_dttm is not None:
+ start_dttm -= widen_bounds_by
+ if end_dttm is not None:
+ end_dttm += widen_bounds_by
+
+ # Then round outward, to whatever the engine's literal resolves to.
+ start_dttm, end_dttm = self._round_bounds_outward(
+ start_dttm, end_dttm, mapped_col
+ )
+
+ # Converted last. The widening and rounding above are `datetime`
+ # arithmetic, and the stored representation may be an integer.
+ if start_dttm is not None:
+ sink.append(
+ (
+ utils.FilterOperator.GREATER_THAN_OR_EQUALS,
+ self._mirror_probe_value(start_dttm, mapped_col),
+ )
)
- if time_grain
- else self.convert_tbl_column_to_sqla_col(
- time_col, label=label, template_processor=template_processor
+ if end_dttm is not None:
+ sink.append(
+ (
+ utils.FilterOperator.LESS_THAN,
+ self._mirror_probe_value(end_dttm, mapped_col),
+ )
)
+
+ def _array_mirror_probe_value(
+ self,
+ value: Any,
+ operator: utils.FilterOperator,
+ element_type: Optional[utils.GenericDataType],
+ db_engine_spec: builtins.type["BaseEngineSpec"],
+ ) -> Any:
+ """
+ The array literal the real predicate compares, ready to probe with.
+
+ On an array column the predicate is not built from `eq` at all: the
+ branch below reads the raw `val`, parses the pasted literal into
+ elements, coerces them to the array's element type and asks the engine
+ spec for its own array syntax. Mirroring `eq` would probe the transform
+ at a value the query never compares, so this reproduces that chain
+ instead -- the mirror then probes exactly what the predicate holds.
+
+ The result is SQL text rather than a value, because an array literal is
+ an expression; `RawProbeValue` carries it and `build_probe_sql`
+ substitutes rather than binds. Returns `None` when the engine spec
+ claims multi-value columns without implementing a literal for them, or
+ when an element has no literal the dialect can render -- a nested array
+ such as ``[[1, 2]]`` -- which costs the query its pruning and nothing
+ else.
+
+ An element the driver and the engine would not spell the same way
+ declines with `_UNMIRRORABLE_ESCAPING` instead, which the preview can
+ explain. It has to be asked here: once the elements are inside the
+ engine's own array syntax there is no single value left for
+ `value_round_trips` to compare a parse against.
+ """
+
+ def literal(entry: Any) -> Any:
+ elements = coerce_array_values(parse_array_literal(entry), element_type)
+ if not all(
+ value_round_trips(self.database, element) for element in elements
+ ):
+ return _UNMIRRORABLE_ESCAPING
+ return raw_probe_value(
+ self.database,
+ db_engine_spec.array_literal(elements),
+ )
+
+ try:
+ if operator in {utils.FilterOperator.IN, utils.FilterOperator.NOT_IN}:
+ candidates = (
+ list(value) if isinstance(value, (list, tuple)) else [value]
+ )
+ members = tuple(literal(candidate) for candidate in candidates)
+ # One element's problem is the whole list's, for the reason
+ # `mirror_probe_request` gives: mirroring the rest would be
+ # narrower than the filter.
+ return next(
+ (member for member in members if is_unmirrorable(member)),
+ members,
+ )
+ return literal(value)
+ except (NotImplementedError, sa.exc.CompileError):
+ return None
+
+ def _as_probe_input(self, value: Any) -> Any:
+ """
+ ``value`` in a form `build_probe_sql` can put into the probe.
+
+ `filter_values_handler` returns engine SQL rather than a value for an
+ epoch-millisecond bound on a temporal column -- what drill-to-detail and
+ cross-filters send -- and SQL cannot be the value of a bind parameter.
+ Carrying it as text lets the probe substitute it instead, exactly as the
+ preview path's own coercion does and as an array literal needs.
+
+ Text rather than the expression itself also matters for caching: the
+ probe cache keys on `repr` of each value, and a `ColumnClause`'s default
+ `repr` carries its memory address, so every request would miss.
+
+ Returns `_UNRENDERABLE` when the engine cannot render the literal, which
+ costs the query its pruning and nothing else -- the same thing the probe
+ itself does on failure.
+
+ Rendering is only half of what has to hold about a literal: whether the
+ engine reads the rendered text back as the value the filter compares is
+ asked separately, by `mirror_probe_request` through
+ `partition_mapping.value_round_trips`.
+ """
+
+ def rendered(entry: Any) -> Any:
+ if isinstance(entry, ColumnElement):
+ return raw_probe_value(self.database, entry)
+ return entry
+
+ try:
+ if isinstance(value, (list, tuple)):
+ return type(value)(rendered(item) for item in value)
+ return rendered(value)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ logger.warning(
+ "Could not render a filter value for the partition mirror; "
+ "queries will not prune",
+ exc_info=True,
+ )
+ return _UNRENDERABLE
+
+ def _collect_partition_mirror_filter(
+ self,
+ mapping: Optional["PartitionMapping"],
+ sink: list[tuple[utils.FilterOperator, Any]],
+ column_name: str,
+ operator: utils.FilterOperator,
+ value: Any,
+ ) -> None:
+ """
+ Record a structured filter for mirroring onto the partition column.
+
+ Only operators the mapping declares safe are recorded; see the operator
+ matrix in `superset.connectors.sqla.partition_mapping`.
+
+ The value itself is resolved by `mirror_probe_request`, which the preview
+ endpoint calls too so that the two cannot answer differently.
+ """
+ if mapping is None or column_name != mapping.mapped_column:
+ return
+ if not mapping.mirrors(operator):
+ return
+
+ mapped_col = next(
+ (col for col in self.columns if col.column_name == column_name), None
)
+ probe_value = self.mirror_probe_request(operator, value, mapped_col)
+ if is_unmirrorable(probe_value):
+ return
+ sink.append((operator, probe_value))
+
+ def mirror_probe_request(
+ self,
+ operator: utils.FilterOperator,
+ value: Any,
+ col: Optional["TableColumn"],
+ ) -> Any:
+ """
+ ``value`` as the mirror may probe the transform at, or an `Unmirrorable`.
+
+ The whole of what has to happen to a filter value before it can be
+ probed, in one place because two callers need it: the chart query path,
+ and the dataset editor's preview endpoint. The preview used to coerce the
+ value and then probe it directly, so it reported a mirror for a request
+ the chart path declines -- an owner was shown a valid predicate on a
+ `DATE` mapped column whose equality filters never mirror at all.
+
+ Routing per *value* rather than per Python type is what makes a bound
+ widen and an equality decline whichever shape the value arrived in -- a
+ `datetime` from drill-to-detail, or the raw string a simple filter binds.
+ """
+ # A decline the caller already made, passed through: the array branch
+ # and the preview's own coercion both answer with an `Unmirrorable` of
+ # their own, and re-reading it as a filter value here would lose the
+ # reason the preview is about to explain.
+ if is_unmirrorable(value):
+ return value
+
+ # First, and ahead of anything that reads the value as an instant: a
+ # value `filter_values_handler` already turned into engine SQL is
+ # carried as text from here on, and the probe has to receive exactly
+ # that literal -- it is what the real predicate compares, so there is
+ # nothing left to resolve about it. Idempotent, so a caller that has
+ # already rendered its own values may still come through here.
+ value = self._as_probe_input(value)
+ if value is _UNRENDERABLE:
+ return UNMIRRORABLE
+
+ # Then, before any of the resolution rules: whether this database's
+ # driver and engine would write the value down the same way. They do
+ # not always -- see `partition_mapping.literal_round_trips` -- and a
+ # value they disagree about is either probed as something nobody
+ # filtered on or, where it closes its own quote, read as SQL. Its own
+ # reason, because nothing about the column, the operator or the
+ # transform is what went wrong, so none of the advice the resolution
+ # branch carries applies.
+ #
+ # One member is the whole list's problem, as below: mirroring the rest
+ # would be narrower than the filter.
+ candidates = value if isinstance(value, (list, tuple)) else [value]
+ if not all(
+ value_round_trips(self.database, candidate) for candidate in candidates
+ ):
+ return UNMIRRORABLE_ESCAPING
+
+ if operator == utils.FilterOperator.IN:
+ if not isinstance(value, (list, tuple)) or not value:
+ return UNMIRRORABLE
+ if any(item is None for item in value):
+ # A `None` in the list widens the real predicate to
+ # `col IS NULL OR col IN (...)`. Mirroring only the non-null
+ # members would be *narrower* than the original filter and
+ # would drop rows it keeps. Checked before the conversion
+ # below, which passes a `None` straight through and could not
+ # be told apart from a value afterwards.
+ return UNMIRRORABLE
+ members = tuple(
+ self._mirror_probe_input(operator, item, col) for item in value
+ )
+ if declined := next(
+ (member for member in members if is_unmirrorable(member)), None
+ ):
+ # One member the engine compares more coarsely than the mirror
+ # can be built from is the whole list's problem: dropping just
+ # that member is the same narrowing the `None` guard above
+ # refuses. So the list declines entire, carrying the first
+ # member's reason -- the one an owner reading the preview would
+ # have to fix first anyway.
+ return declined
+ return members
+
+ if value is None:
+ return UNMIRRORABLE
+ return self._mirror_probe_input(operator, value, col)
+
+ def _build_partition_mirror_predicates(
+ self,
+ mapping: "PartitionMapping",
+ requests: list[tuple[utils.FilterOperator, Any]],
+ ) -> list[ColumnElement]:
+ """
+ Resolve collected mirror requests into predicates on the partition column.
+
+ Requests are deduplicated first: a chart can reach both collection points
+ for the same column -- a `granularity` time filter *and* a
+ `TEMPORAL_RANGE` ad-hoc filter on the same column is a routine Explore
+ configuration -- and emitting the predicate twice is harmless SQL but
+ makes "View query" surprising.
+ """
+ if not requests:
+ return []
+
+ deduped: list[tuple[utils.FilterOperator, Any]] = []
+ seen: set[Any] = set()
+ for operator, value in requests:
+ # Keyed on the operator the mirror is *emitted* with, not the one
+ # collected: a strict bound and its non-strict twin on the same
+ # value build the same predicate, so they are the same request.
+ key = (
+ mirror_operator(operator),
+ value if isinstance(value, Hashable) else repr(value),
+ )
+ if key not in seen:
+ seen.add(key)
+ deduped.append((operator, value))
+
+ return build_mirrored_predicates(cast("SqlaTable", self), mapping, deduped)
Review Comment:
I think this can now fail every chart filtering the mapped column on ClickHouse. `_holds_days_only` (from 6f37942f48) calls `.get` on `dialect.ischema_names`, a list in clickhouse-connect 1.10/1.11, so `toDate(:value)` onto a `Date` key returns 500 with the flag on (200 off) and the preview shows "Fatal error". Could the lookup accept only a `Mapping`, and this call fail open, as the docs say?

[mp4](https://gist.githubusercontent.com/geido/2e9a0de274464f8bac4b8ac43e8888e9/raw/final-clickhouse-date-key-500.mp4)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4367838475
##########
tests/unit_tests/models/partition_mirroring_test.py:
##########
@@ -0,0 +1,3205 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mirroring inside ``ExploreMixin.get_sqla_query``.
+
+The probe that resolves ``T(v)`` against the engine is stubbed throughout; what
+these tests pin down is *which* predicates get mirrored and with what values,
+which is where the correctness argument lives.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from typing import Any
+from unittest.mock import MagicMock, patch
+
+import pandas as pd
+import pytest
+import sqlalchemy as sa
+from flask import Flask
+
+from superset.connectors.sqla.models import SqlaTable, SqlMetric, TableColumn
+from superset.connectors.sqla.partition_mapping import RawProbeValue
+from superset.db_engine_specs.clickhouse import ClickHouseEngineSpec
+from superset.db_engine_specs.presto import PrestoEngineSpec
+from superset.db_engine_specs.sqlite import SqliteEngineSpec
+from superset.models.core import Database
+from superset.superset_typing import QueryObjectDict
+from superset.utils import json
+from superset.utils.core import FilterOperator
+
+PROBE = "superset.connectors.sqla.partition_mapping.evaluate_transform"
+
+
+@pytest.fixture(autouse=True)
+def enable_partition_filter_mapping(app: Flask) -> Any:
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = True
+ yield
+ del app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"]
+
+
+def _table(
+ *,
+ transform: str = "unix_timestamp(:value)",
+ monotonic: bool = True,
+ partition_column: str | None = "dt_epoch",
+ mapped_column: str = "event_time",
+ partition_mapped_column: str | None = None,
+ main_dttm_col: str | None = "event_time",
+) -> SqlaTable:
+ database = Database(database_name="test_db", sqlalchemy_uri="sqlite://")
+ columns = [
+ TableColumn(column_name="event_time", is_dttm=True, type="TIMESTAMP"),
+ TableColumn(column_name="other_time", is_dttm=True, type="TIMESTAMP"),
+ TableColumn(column_name="dt_epoch", type="BIGINT"),
+ TableColumn(column_name="country", type="VARCHAR"),
+ TableColumn(column_name="region_key", type="VARCHAR"),
+ ]
+ table = SqlaTable(
+ table_name="web_events",
+ database=database,
+ schema=None,
+ main_dttm_col=main_dttm_col,
+ columns=columns,
+ metrics=[SqlMetric(metric_name="hits", expression="COUNT(*)")],
+ )
+ table.partition_column = partition_column
+ table.partition_mapped_column = partition_mapped_column
+ for column in columns:
+ if column.column_name == mapped_column:
+ column.partition_value_transform = transform
+ column.partition_transform_is_monotonic = monotonic
+ return table
+
+
+def _mapped_date_table() -> SqlaTable:
+ """
+ A dataset whose mapped column is a ``DATE``.
+
+ That is the type whose literal an engine resolves to a bare day, which is
+ what the resolution reasoning is about; `_rendering_dates_like_presto` is
+ what makes this table's spec answer that way.
+ """
+ table = _table(mapped_column="event_date", main_dttm_col="event_date")
+ table.columns.append(
+ TableColumn(column_name="event_date", is_dttm=True, type="DATE")
+ )
+ table.columns[-1].partition_value_transform = "unix_timestamp(:value)"
+ table.columns[-1].partition_transform_is_monotonic = True
+ return table
+
+
+def _rendering_dates_like_presto(table: SqlaTable) -> Any:
+ """
+ Make the dataset's engine spec render a bound the way Presto does.
+
+ `Database.db_engine_spec` is a derived property, so the spec cannot be
+ swapped wholesale; delegating `convert_dttm` keeps the test tied to the real
+ spec rather than to a hand-copied format string. Presto's DATE branch is
+ `DATE '{dttm.date().isoformat()}'`, which Trino, BigQuery and some two dozen
+ others share.
+ """
+ return patch.object(
+ table.database.db_engine_spec,
+ "convert_dttm",
+ classmethod(
+ lambda cls, target_type, dttm, db_extra=None: PrestoEngineSpec.convert_dttm(
+ target_type, dttm, db_extra=db_extra
+ )
+ ),
+ )
+
+
+def _query(table: SqlaTable, **kwargs: Any) -> str:
+ defaults: dict[str, Any] = {
+ "columns": ["country"],
+ "metrics": [],
+ "orderby": [],
+ "extras": {},
+ "filter": [],
+ "granularity": None,
+ "is_timeseries": False,
+ }
+ defaults.update(kwargs)
+ result = table.get_sqla_query(**defaults)
+ return str(
+ result.sqla_query.compile(compile_kwargs={"literal_binds": True})
+ ).replace("\n", " ")
+
+
+# ---------------------------------------------------------------------------
+# The safe operators
+# ---------------------------------------------------------------------------
+
+
+def test_equality_filter_mirrors_onto_the_partition_column(app: Flask) -> None:
+ table = _table(
+ transform="lower(:value)",
+ monotonic=False,
+ mapped_column="country",
+ partition_mapped_column="country",
+ partition_column="region_key",
+ )
+
+ with app.app_context():
+ with patch(PROBE, return_value=["us"]):
+ sql = _query(
+ table,
+ filter=[
+ {"col": "country", "op": FilterOperator.EQUALS.value, "val": "US"}
+ ],
+ )
+
+ assert "region_key = 'us'" in sql
+ assert "country = 'US'" in sql
+
+
+def _with_date_partition_column(table: SqlaTable) -> SqlaTable:
+ """Re-point the mapping's partition column at a ``DATE`` column."""
+ table.columns.append(
+ TableColumn(column_name="part_date", is_dttm=True, type="DATE")
+ )
+ table.partition_column = "part_date"
+ return table
+
+
+def test_ordinary_text_does_not_mirror_onto_a_temporal_partition_column(
+ app: Flask,
+) -> None:
+ """
+ `lower(:value)` on a `VARCHAR` mapped column answers with text, and a
+ temporal partition column admits text -- a day key is legitimately text.
+ But it admitted *any* text: `country = 'US'` probed to `'us'` and emitted
+ `part_date = 'us'`, which PostgreSQL refuses as a date. By then the mirror
+ is in the statement, so a chart that worked before the mapping returned an
+ error rather than losing its pruning. The preview called it valid.
+ """
+ table = _with_date_partition_column(
+ _table(
+ transform="lower(:value)",
+ monotonic=False,
+ mapped_column="country",
+ partition_mapped_column="country",
+ )
+ )
+
+ with app.app_context():
+ with patch(PROBE, return_value=["us"]):
+ sql = _query(
+ table,
+ filter=[
+ {"col": "country", "op": FilterOperator.EQUALS.value, "val": "US"}
+ ],
+ )
+
+ assert "part_date" not in sql
+ assert "country = 'US'" in sql
+
+
+def test_a_text_column_s_bound_is_not_rounded_as_though_it_were_temporal(
+ app: Flask,
+) -> None:
+ """
+ SQLite's `convert_dttm` renders for `types.String` as well as the date
+ types, so a VARCHAR mapped column read as second-resolution -- and a filter
+ value that merely *looks* like an instant had its bound rounded as though
+ the engine had truncated it.
+
+ On a VARCHAR `country` mapped onto VARCHAR `region_key` by `:value`,
+ `country < '2026-07-06T10:08:11.500000'` was mirrored as
+ `region_key <= '2026-07-06 10:08:12.000000'`. A space sorts before `T`, so a
+ row holding `2026-07-06T09:00:00` -- which the filter keeps -- fell outside
+ the mirror and was dropped.
+
+ `_column_literal_resolution` already guarded on `is_dttm` and said in its
+ docstring that the per-instant callers never met this case. They do: the
+ value parses as an instant while the column is still text.
+ """
+ table = _table(
+ transform=":value",
+ monotonic=True,
+ mapped_column="country",
+ partition_mapped_column="country",
+ partition_column="region_key",
+ )
+
+ with app.app_context():
+ with patch(PROBE, return_value=["2026-07-06T10:08:11.500000"]) as probe:
+ _query(
+ table,
+ filter=[
+ {
+ "col": "country",
+ "op": FilterOperator.LESS_THAN.value,
+ "val": "2026-07-06T10:08:11.500000",
+ }
+ ],
+ )
+
+ # Handed through untouched: no rounding, and no seconds-shaped rewrite.
+ assert probe.call_args.args[-1] == ["2026-07-06T10:08:11.500000"]
+
+
+def test_a_day_key_still_mirrors_onto_a_temporal_partition_column(
+ app: Flask,
+) -> None:
+ """
+ The narrowing above must not cost the case the text admission exists for:
+ `to_char(:value, 'YYYYMMDD')` answers with a day key, which PostgreSQL
+ reads as a date and so declares in `temporal_literal_formats`.
+
+ Its sibling `test_a_day_key_still_mirrors_onto_a_text_partition_column`
+ covers the same transform onto a *text* key, which is the other axis --
+ that one is about `GenericDataType.STRING` and never reached this gate.
+ """
+ table = _with_date_partition_column(
+ _table(
+ transform="to_char(:value, 'YYYYMMDD')",
+ monotonic=False,
+ mapped_column="country",
+ partition_mapped_column="country",
+ )
+ )
+
+ with app.app_context():
+ with patch.object(SqliteEngineSpec, "temporal_literal_formats", ("%Y%m%d",)):
+ with patch(PROBE, return_value=["20260101"]):
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "country",
+ "op": FilterOperator.EQUALS.value,
+ "val": "US",
+ }
+ ],
+ )
+
+ assert "part_date = '20260101'" in sql
+
+
+def test_a_day_key_declines_where_the_engine_has_not_claimed_it(
+ app: Flask,
+) -> None:
+ """
+ BigQuery coerces a STRING literal to `DATE` only in the canonical
+ `YYYY-MM-DD` form and Trino wants an explicit cast, so `part_date =
+ '20260101'` fails the whole chart there rather than merely losing its
+ pruning. An engine that has not declared the format declines instead.
+ """
+ table = _with_date_partition_column(
+ _table(
+ transform="to_char(:value, 'YYYYMMDD')",
+ monotonic=False,
+ mapped_column="country",
+ partition_mapped_column="country",
+ )
+ )
+
+ assert SqliteEngineSpec.temporal_literal_formats == ()
+
+ with app.app_context():
+ with patch(PROBE, return_value=["20260101"]):
+ sql = _query(
+ table,
+ filter=[
+ {"col": "country", "op": FilterOperator.EQUALS.value, "val": "US"}
+ ],
+ )
+
+ assert "part_date" not in sql
+
+
+def test_in_filter_mirrors_element_wise(app: Flask) -> None:
+ table = _table(
+ transform="lower(:value)",
+ monotonic=False,
+ mapped_column="country",
+ partition_mapped_column="country",
+ partition_column="region_key",
+ )
+
+ with app.app_context():
+ with patch(PROBE, return_value=["us", "ca"]):
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "country",
+ "op": FilterOperator.IN.value,
+ "val": ["US", "CA"],
+ }
+ ],
+ )
+
+ assert "region_key IN ('us', 'ca')" in sql
+
+
+def test_time_range_mirrors_both_bounds(app: Flask) -> None:
+ """
+ The Explore time range is the most important operator in the feature, and it
+ is a range operator -- so it only mirrors on a declared-monotonic transform.
+ """
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1767225600, 1769904000]):
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ )
+
+ assert "dt_epoch >= 1767225600" in sql
+ assert "dt_epoch <= 1769904000" in sql
+
+
+def test_temporal_range_filter_mirrors_both_bounds(app: Flask) -> None:
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1767225600, 1769904000]):
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_time",
+ "op": FilterOperator.TEMPORAL_RANGE.value,
+ "val": "2026-01-01 : 2026-02-01",
+ }
+ ],
+ )
+
+ assert "dt_epoch >= 1767225600" in sql
+ assert "dt_epoch <= 1769904000" in sql
+
+
+@pytest.mark.parametrize(
+ "operator,expected",
+ [
+ (FilterOperator.GREATER_THAN, "dt_epoch >= 1767225600"),
+ (FilterOperator.GREATER_THAN_OR_EQUALS, "dt_epoch >= 1767225600"),
+ (FilterOperator.LESS_THAN, "dt_epoch <= 1767225600"),
+ (FilterOperator.LESS_THAN_OR_EQUALS, "dt_epoch <= 1767225600"),
+ ],
+)
+def test_strict_range_operators_mirror_non_strictly(
+ app: Flask, operator: FilterOperator, expected: str
+) -> None:
+ """
+ The direction is preserved; the strictness is not. "Preserves ordering"
+ means non-decreasing, so `col < v` only implies `T(col) <= T(v)` -- a
+ strict mirror would drop the rows a bucketing transform puts at the
+ boundary. The non-strict mirror reads one extra partition, and the original
+ filter is still there to exclude whatever it admits.
+ """
+ table = _table()
+
+ with app.app_context():
+ with patch(PROBE, return_value=[1767225600]):
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_time",
+ "op": operator.value,
+ "val": "2026-01-01 00:00:00",
+ }
+ ],
+ )
+
+ assert expected in sql
+
+
+def test_a_bucketing_transform_keeps_the_boundary_bucket(app: Flask) -> None:
+ """
+ A day key is monotonic but not *strictly* so: every instant in a day
+ maps to one value, so an upper bound at `2026-07-06 12:00` and a row at
+ `2026-07-06 06:00` share the bucket `20260706`. Mirroring that bound
+ strictly prunes the bucket the row is in and drops it from the chart --
+ silently, with the pruning glyph still promising only a speed-up.
+ """
+ table = _table(
+ transform="to_char(:value, 'YYYYMMDD')",
+ partition_column="region_key",
+ )
+
+ with app.app_context():
+ with patch(PROBE, return_value=["20260705", "20260706"]):
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 7, 5),
+ to_dttm=datetime(2026, 7, 6, 12, 0),
+ )
+
+ assert "region_key >= '20260705'" in sql
+ assert "region_key <= '20260706'" in sql
+
+
+def test_an_intraday_strict_pair_does_not_mirror_to_an_empty_range(
+ app: Flask,
+) -> None:
+ """
+ The zero-instead-of-nine case. `event_time > '2026-07-05 06:00'` plus
+ `event_time < '2026-07-06 00:00'` is an ordinary pair of ad-hoc filters, and
+ under a day key the bounds land in adjacent buckets. Mirrored strictly it
+ reads `day_key > '20260705' AND day_key < '20260706'`, which is empty by
+ construction whatever the table holds -- so the chart returns nothing while
+ SQL Lab returns the real rows.
+ """
+ table = _table(
+ transform="to_char(:value, 'YYYYMMDD')",
+ partition_column="region_key",
+ )
+
+ with app.app_context():
+ with patch(PROBE, return_value=["20260705", "20260706"]):
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_time",
+ "op": FilterOperator.GREATER_THAN.value,
+ "val": "2026-07-05 06:00:00",
+ },
+ {
+ "col": "event_time",
+ "op": FilterOperator.LESS_THAN.value,
+ "val": "2026-07-06 00:00:00",
+ },
+ ],
+ )
+
+ assert "region_key >= '20260705'" in sql
+ assert "region_key <= '20260706'" in sql
+
+
+def test_an_integer_bucket_key_is_mirrored_non_strictly_too(app: Flask) -> None:
+ """
+ The same loss was measured on a day *number* as well as a day string, so it
+ is a property of any many-to-one transform rather than of text keys or of
+ the formatting function used to build them.
+ """
+ table = _table(transform="cast(unix_timestamp(:value) / 86400 as bigint)")
+
+ with app.app_context():
+ with patch(PROBE, return_value=[20638, 20639]):
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 7, 5),
+ to_dttm=datetime(2026, 7, 6, 12, 0),
+ )
+
+ assert "dt_epoch >= 20638" in sql
+ assert "dt_epoch <= 20639" in sql
+
+
+# ---------------------------------------------------------------------------
+# The unsafe operators — nothing is emitted
+# ---------------------------------------------------------------------------
+
+
+@pytest.mark.parametrize(
+ "flt",
+ [
+ {"col": "country", "op": FilterOperator.NOT_EQUALS.value, "val": "US"},
+ {"col": "country", "op": FilterOperator.NOT_IN.value, "val": ["US"]},
+ {"col": "country", "op": FilterOperator.LIKE.value, "val": "U%"},
+ {"col": "country", "op": FilterOperator.ILIKE.value, "val": "U%"},
+ {"col": "country", "op": FilterOperator.NOT_LIKE.value, "val": "U%"},
+ {"col": "country", "op": FilterOperator.IS_NULL.value},
+ {"col": "country", "op": FilterOperator.IS_NOT_NULL.value},
+ ],
+)
+def test_unsafe_operators_emit_nothing(app: Flask, flt: dict[str, Any]) -> None:
+ """
+ ``T`` need not be injective, so ``country != 'US'`` does not imply
+ ``region_key != 'us'`` -- mirroring it would drop rows whose ``country`` is
+ already lowercase, rows the original filter keeps.
+ """
+ table = _table(
+ transform="lower(:value)",
+ monotonic=False,
+ mapped_column="country",
+ partition_mapped_column="country",
+ partition_column="region_key",
+ )
+
+ with app.app_context():
+ with patch(PROBE, side_effect=AssertionError("probe must not run")):
+ sql = _query(table, filter=[flt])
+
+ assert "region_key" not in sql
+
+
+def test_ranges_do_not_mirror_when_the_transform_is_not_order_preserving(
+ app: Flask,
+) -> None:
+ """
+ ``hour(:value)`` is a perfectly reasonable partition transform on a
+ ``TIMESTAMP`` column and it is not monotonic, so a time range must not
+ mirror through it.
+ """
+ table = _table(transform="hour(:value)", monotonic=False)
+
+ with app.app_context():
+ with patch(PROBE, side_effect=AssertionError("probe must not run")):
+ sql = _query(
+ table,
+ granularity="event_time",
+ from_dttm=datetime(2026, 1, 1),
+ to_dttm=datetime(2026, 2, 1),
+ )
+
+ assert "dt_epoch" not in sql
+
+
+def test_equality_still_mirrors_when_the_transform_is_not_order_preserving(
+ app: Flask,
+) -> None:
+ table = _table(transform="hour(:value)", monotonic=False)
+
+ with app.app_context():
+ with patch(PROBE, return_value=[13]):
+ sql = _query(
+ table,
+ filter=[
+ {
+ "col": "event_time",
+ "op": FilterOperator.EQUALS.value,
+ "val": "2026-01-01 13:00:00",
+ }
+ ],
+ )
+
+ assert "dt_epoch = 13" in sql
+
+
+# ---------------------------------------------------------------------------
+# Bail-outs and edge cases
+# ---------------------------------------------------------------------------
+
+
+def test_nothing_mirrors_when_the_feature_flag_is_off(app: Flask) -> None:
+ table = _table()
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = False
+
+ with app.app_context():
+ with patch(PROBE, side_effect=AssertionError("probe must not run")):
Review Comment:
Since the mirror builder now swallows any exception and returns `[]`, the `AssertionError` raised by this booby-trapped probe is caught too, so the test passes whether or not the probe runs. If the chart path regressed and probed with the flag off, `"dt_epoch" not in sql` would still hold. Could this bind the patch (`as probe`) and assert `probe.assert_not_called()` after `_query()`? The same pattern is at the other `side_effect=AssertionError(...)` tests in this file.
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,3889 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Writing the value into the probe
+--------------------------------
+The probe evaluates the transform at a *literal*, because it runs with no bound
+parameters at all -- so every value is written into SQL text by the driver's
+literal renderer and read back by the engine's lexer, and the two do not always
+agree. SQLAlchemy's default renderer doubles apostrophes and leaves backslashes
+alone; Hive honours backslash escapes and not doubling, so ``'O''Brien'`` is
+read there as two adjacent literals and ``'x\\''`` ends four characters into a
+value the filter carries whole. A disagreement is either a mirror built from a
+value nobody filtered on -- dropping rows the filter keeps -- or, where the
+value closes its own quote, an expression of the filterer's choosing running in
+the probe.
+
+Which side is right is not knowable from the driver: it is a per-session server
+setting (``standard_conforming_strings``, ``NO_BACKSLASH_ESCAPES``,
+``spark.sql.parser.escapedStringLiterals``), and SQLAlchemy's own view of it is
+only correct on a dialect that has connected. So escaping is not what makes
+this safe. `literal_round_trips` renders the literal and reads it back in the
+engine's own dialect instead, and a value that does not survive the trip is not
+mirrored -- the usual trade, pruning for correctness. `probe_sql_is_evaluable`
+re-reads the finished statement behind it.
+
+The probe's *answers* make the same trip, in the other direction. The chart
+query is compiled with ``literal_binds``, so a probed partition key is rendered
+into its SQL by the same renderer and read by the same lexer -- and
+``concat(:value, chr(92), 'b')`` turns the unremarkable input ``a`` into the key
+``a\\b``, which Hive reads back as ``a`` followed by a backspace. So
+`_predicates_from_probe` asks `literal_round_trips` about each result too, and
+declines the request rather than emitting a predicate no row can satisfy: the
+mirror is ``AND``-ed onto the query, so a mirror that matches nothing costs the
+chart its rows rather than its pruning.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Mapping, Sequence
+from dataclasses import dataclass
+from datetime import date, datetime, time, timedelta
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: The opening and closing delimiters of each kind of Jinja block. The probe
+#: would render these in a different context at a different time from the chart
+#: query, so a transform holding one is rejected at save time.
+JINJA_BLOCK_DELIMITERS = (("{{", "}}"), ("{%", "%}"), ("{#", "#}"))
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: A PostgreSQL Unicode-escaped identifier, ``U&"..."``.
+#:
+#: The second construct that breaks the premise above, and in the same way:
+#: ``U&"\\0071uery_to_xml"(...)`` parses as an anonymous function whose name is
+#: the *literal* ``\\0071uery_to_xml``, so the function denylist is matching a
+#: name the engine never sees -- PostgreSQL decodes the escape and runs
+#: ``query_to_xml``, handing a dataset owner rows from outside their RLS scope
+#: through the preview's ``emitted_predicate``.
+#:
+#: Normalizing the escapes and re-checking would be the other repair, and is
+#: worse: it means reimplementing one engine's identifier decoding well enough
+#: to be a security boundary. Refusing the construct is exact, and costs
+#: nothing real -- a transform is a scalar function of ``:value``, and there is
+#: no reason to name a function or column through an escape sequence.
+#:
+#: Refused on every engine, like the executable comment, so a transform stored
+#: on SQLite cannot detonate when the dataset is re-pointed at PostgreSQL. The
+#: ``&`` may be separated from the ``U`` by nothing at all, but whitespace or a
+#: comment between the prefix and the string is not accepted by PostgreSQL
+#: either, so the strict form is the whole surface.
+#:
+#: Matched in raw text, so the prefix is refused inside a string literal too.
+#: That is the same trade the executable comment makes and has the same
+#: justification: a gate whose contract is to fire *before* the parse cannot
+#: ask the parse whether the text was quoted. ``concat(:value, 'u&"x"')`` is
+#: refused, which costs an owner nothing anyone writes.
+UNICODE_ESCAPED_IDENTIFIER_RE = re.compile(r'\bU&"', re.IGNORECASE)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate: a transform such as
+#: ``datediff(day, :value, LOCALTIMESTAMP)`` for a relative partition key is
+#: evaluated once and then keeps emitting yesterday's answer, so the chart
+#: silently drops rows after midnight.
+#:
+#: Matched by SQL function name, so every engine's spelling of "now" has to be
+#: named -- the ANSI four were not enough. Listed rather than delegated to the
+#: engine specs because the risk is the same everywhere and a spec that had not
+#: got round to declaring its own would fail open; a name no engine has is
+#: inert, so over-listing costs nothing.
+NON_DETERMINISTIC_FUNCTIONS = {
+ # ANSI, and the engines that spell it this way.
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "LOCALTIME",
+ "LOCALTIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+ # PostgreSQL. `now()` is statement-stable; these two are not even that.
+ "CLOCK_TIMESTAMP",
+ "STATEMENT_TIMESTAMP",
+ "TIMEOFDAY",
+ # MySQL and MariaDB.
+ "CURDATE",
+ "CURTIME",
+ "SYSDATE",
+ "UTC_DATE",
+ "UTC_TIME",
+ "UTC_TIMESTAMP",
+ "UUID_SHORT",
+ # Oracle.
+ "SYSTIMESTAMP",
+ "SYS_GUID",
+ # SQL Server.
+ "GETDATE",
+ "GETUTCDATE",
+ "SYSDATETIME",
+ "SYSUTCDATETIME",
+ "SYSDATETIMEOFFSET",
+ "NEWID",
+ # BigQuery.
+ "CURRENT_DATETIME",
+ "GENERATE_UUID",
+ # Snowflake.
+ "RANDSTR",
+ "UUID_STRING",
+ # ClickHouse.
+ "NOW64",
+ "RANDCANONICAL",
+ "GENERATEUUIDV4",
+ # H2 and Derby, which the test fixtures use.
+ "RANDOM_UUID",
+}
+
+#: The wall-clock names an engine evaluates with no parentheses at all.
+#:
+#: These parse as *column references*, not functions, so the name-based walk
+#: below cannot see them: `datediff(UTC_DATE, :value)` on MySQL and
+#: `:value - SYSDATE` on Oracle both cleared the gate and froze probe time into
+#: a cached mirror.
+#:
+#: A subset of `NON_DETERMINISTIC_FUNCTIONS` rather than the whole of it,
+#: because refusing a bare name costs an owner a column genuinely called that.
+#: Only the names SQL lets you write without ``()`` are listed -- the datetime
+#: keywords -- so `rand`, `uuid` and `newid`, which always need parentheses and
+#: are plausible column names, stay out.
+BARE_WALL_CLOCK_KEYWORDS = frozenset(
+ {
+ "current_date",
+ "current_time",
+ "current_timestamp",
+ "localtime",
+ "localtimestamp",
+ "utc_date",
+ "utc_time",
+ "utc_timestamp",
+ "sysdate",
+ "systimestamp",
+ }
+)
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+class Unmirrorable:
+ """
+ A filter no mirror can stand in for, and why.
+
+ Returned by `ExploreMixin.mirror_probe_request` for a value the engine
+ compares more coarsely than the filter carries, one it cannot render as a
+ literal, one whose rendered literal the engine would not read back as the
+ same value, one in a time frame the transform would discard, or an ``IN``
+ list with a member of any of those kinds. An object rather than `None`,
+ because `None` is a filter value in its own right.
+
+ The reason rides along because the preview has to explain the decline to
+ the owner, and the two declines want different advice: "the engine compares
+ less of this value than you typed, so map a column it compares in full" is
+ sound guidance for a `DATE` column and actively misleading for an
+ offset-bearing bound on a `TIMESTAMP` one, which already is such a column.
+ Carried rather than re-derived so the preview's explanation cannot come
+ apart from the chart path's decision.
+
+ Lives here rather than beside that method so the preview can read it too:
+ `superset.models.helpers` imports this module, so these can only cross the
+ boundary in this direction. Both callers recognise the same instances -- a
+ preview that answered "valid" for a request the chart path declines is the
+ drift this is here to prevent.
+ """
+
+ __slots__ = ("reason",)
+
+ def __init__(self, reason: str) -> None:
+ self.reason = reason
+
+ def __repr__(self) -> str:
+ return f"<Unmirrorable {self.reason}>"
+
+
+#: The ordinary decline: whatever the mirror cannot be built from, with the
+#: engine's own comparison resolution as the reason an owner can act on.
+UNMIRRORABLE = Unmirrorable("resolution")
+
+#: A value carrying a UTC offset, declined whatever the column's resolution.
+#: A transform such as ``CAST(:value AS TIMESTAMP)`` drops the offset, so even
+#: an engine that compares the whole instant would be probed in the wrong
+#: frame -- which is not something mapping a different column fixes.
+UNMIRRORABLE_OFFSET = Unmirrorable("offset")
+
+#: A value the driver and the engine would not spell the same way, declined
+#: whatever the column's resolution and whatever the operator. Nothing about
+#: the column or the transform fixes it -- see `literal_round_trips` -- so the
+#: advice the resolution reason carries would send an owner after the wrong
+#: thing entirely.
+UNMIRRORABLE_ESCAPING = Unmirrorable("escaping")
+
+
+def is_unmirrorable(value: Any) -> bool:
+ """Whether `mirror_probe_request` declined this request."""
+ return isinstance(value, Unmirrorable)
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def _native_generic_type(
+ column: "TableColumn",
+) -> utils.GenericDataType | None:
+ """
+ What the engine spec makes of ``column``'s declared type.
+
+ `TableColumn.type_generic` answers ``TEMPORAL`` for every column carrying
+ ``is_dttm``, which is the right answer for a chart's time axis and the
+ wrong one for a comparison: an epoch ``BIGINT`` is a number to the engine
+ however it is labelled here. Falls back to the flag where the spec has no
+ answer, so a type Superset cannot resolve is no worse off than before.
+ """
+ try:
+ column_spec = column.db_engine_spec.get_column_spec(
+ column.type, db_extra=column.db_extra
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ column_spec = None
+ if column_spec is not None and column_spec.generic_type is not None:
+ return column_spec.generic_type
+ try:
+ return column.type_generic
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+#: A declared type naming an array: PostgreSQL's ``TEXT[]`` / ``INTEGER[][]``
+#: / ``int[3]``, and the ``ARRAY<...>`` / ``ARRAY(...)`` / ``Array(...)``
+#: spellings of Hive, Spark, Trino, BigQuery and ClickHouse.
+#: The bracket body is written so no two runs can match the same blanks:
+#: ``\s*\d*\s*`` backtracks polynomially on a long run of spaces.
+_ARRAY_TYPE_RE = re.compile(r"(?:\[\s*(?:\d+\s*)?\])+\s*$|^\s*ARRAY\b", re.IGNORECASE)
+
+
+def declares_array_type(column_type: str | None) -> bool:
+ """
+ Whether a declared column type is an array, whatever the engine spec says.
+
+ The engine spec only reports ``MULTI_VALUE`` where it has opted into
+ ``supports_multivalue_columns``; PostgreSQL has not, and resolves ``TEXT[]``
+ to ``STRING`` and ``INTEGER[]`` to ``NUMERIC``. So an array partition column
+ there cleared the array refusal, previewed valid, and every equality chart
+ on the mapping failed with ``malformed array literal``. The declared type
+ is what the engine will compare, so it is read directly as well.
+ """
+ return bool(column_type and _ARRAY_TYPE_RE.search(column_type))
+
+
+#: Declared types whose comparison ignores trailing blanks.
+#:
+#: The fixed-width character types, which the SQL standard has compare as
+#: though both sides were padded to the same length -- so ``'US'`` and
+#: ``'US '`` are equal in a ``CHARACTER(3)``, while ``lower()`` of the two is
+#: not. Spelled out rather than matched by prefix because the variable-width
+#: names start with the same letters: ``VARCHAR`` and ``CHARACTER VARYING``
+#: compare the blanks and must not land here.
+PADDED_CHARACTER_TYPES = frozenset(
+ {
+ "CHAR",
+ "NCHAR",
+ # PostgreSQL's own name for ``CHARACTER``, which is what reflection
+ # reports for a ``CHAR(n)`` column there.
+ "BPCHAR",
+ "CHARACTER",
+ "NATIONAL CHAR",
+ "NATIONAL CHARACTER",
+ }
+)
+
+
+def _is_padded_character_type(column: TableColumn) -> bool:
+ """
+ Whether ``column``'s declared type compares without its trailing blanks.
+
+ Read off the declared type rather than the engine spec's resolved one: the
+ specs map ``CHAR`` and ``VARCHAR`` onto the same `sqlalchemy.String`, so
+ the distinction this needs is gone by then. The length suffix is dropped
+ and the name matched against `PADDED_CHARACTER_TYPES`, so an unfamiliar
+ spelling answers ``False`` and the engine-level flag decides as before --
+ this gate adds a decline rather than lifting one. A column with no
+ declared type has nothing to read, and answers the same way.
+ """
+ if not isinstance(column.type, str):
+ return False
+ native = re.sub(r"\s+", " ", column.type.strip().upper())
+ return native.split("(")[0].strip() in PADDED_CHARACTER_TYPES
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ Padding is asked about per column, because it is a property of the *type*
+ rather than of the engine. ``binary_string_comparison`` speaks for an
+ engine's default text comparison, and on PostgreSQL -- which declares it
+ -- a ``CHAR(2)`` still matches a filter for ``'US '`` against a stored
+ ``'US'``, because the standard says a padded character type compares
+ without its trailing blanks. The mirror ``region_key = lower('US ')`` then
+ excludes the row. So a fixed-width character type declines whatever the
+ engine says, and an engine that ignores trailing blanks on its *variable*
+ types says so by not declaring the flag at all (see `RedshiftEngineSpec`).
+
+ The type asked for is the engine spec's reading of the column's declared
+ type, not `TableColumn.type_generic`, which answers ``TEMPORAL`` for
+ anything carrying ``is_dttm``. A ``VARCHAR`` flagged temporal is still text
+ to the engine: on MySQL a filter for ``'2026-01-01T00:00:00'`` matches a
+ stored ``'...t00:00:00'``, while the mirror ``p = hex('...T...')`` excludes
+ it -- and asking the semantic flag skipped the check entirely.
+
+ A type the spec cannot classify declines, which is what the paragraph above
+ promises and what only the exception branch used to do. PostgreSQL's
+ ``citext`` matches no type pattern, so it answered ``None`` -- neither
+ string nor not-string -- and was waved through, which is precisely wrong
+ for a type whose whole purpose is case-insensitive comparison. Declining
+ costs the pruning; admitting it costs rows.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ # Ahead of the generic-type question, which a padded type can lose: the
+ # specs map ``CHARACTER`` onto no generic type at all on some engines, and
+ # a fixed-width character type is a string whether or not Superset can say
+ # so from the name.
+ if _is_padded_character_type(column):
+ return False
+ generic_type = _native_generic_type(column)
+ if generic_type is None:
+ return False
+ if generic_type != utils.GenericDataType.STRING:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_unicode_escaped_identifier(transform: str | None) -> bool:
+ """Whether the transform names something through a ``U&"..."`` escape.
+
+ See `UNICODE_ESCAPED_IDENTIFIER_RE`. Answered on raw text for the same
+ reason as the comment above: the parse reports a name the engine does not
+ use, which is exactly what makes the denylist blind to it.
+ """
+ return (
+ bool(transform)
+ and UNICODE_ESCAPED_IDENTIFIER_RE.search(transform or "") is not None
+ )
+
+
+#: Sequence pseudo-columns, which advance a sequence when they are *read*.
+#:
+#: ``orders_seq.NEXTVAL`` parses as a qualified column reference, not a
+#: function call, so neither `SQLStatement.is_mutating` -- which walks function
+#: names -- nor the function denylist can see it. The probe would then run
+#: ``SELECT orders_seq.NEXTVAL + 1 FROM DUAL`` and advance the sequence, again
+#: on every cache expiry, for a dataset editor holding neither SQL Lab nor a
+#: DML grant. Reading one is a write however the parser classifies it.
+#:
+#: The function spelling (``nextval('s')`` on PostgreSQL) is a different shape
+#: and is caught as a function; this is only about the suffix form.
+SEQUENCE_PSEUDO_COLUMNS = frozenset({"nextval", "currval"})
+
+#: The same thing written as a call.
+#:
+#: Only the suffix form parses as a column; `nextval('s')` on PostgreSQL and
+#: DuckDB, `NEXTVAL(s)`/`SETVAL(s, 1)` on MySQL and MariaDB, and SQL Server's
+#: `NEXT VALUE FOR s` all parse as functions. `SQLStatement.is_mutating` walks
+#: function names on PostgreSQL alone -- deliberately, since the same names are
+#: read-only elsewhere -- so every other engine let these through.
+#:
+#: Matched on the name whatever the engine, because advancing a sequence is a
+#: write wherever it happens and a transform has no reason to call one.
+SEQUENCE_FUNCTIONS = frozenset(
+ {"nextval", "setval", "next_value_for", "nextvalfor", "prevval", "lastval"}
+)
+
+
+def references_sequence(statement: SQLStatement) -> bool:
+ """Whether the statement reads or advances a sequence.
+
+ Both spellings: the pseudo-column suffix, which parses as a column (see
+ `SEQUENCE_PSEUDO_COLUMNS`), and the call, which parses as a function (see
+ `SEQUENCE_FUNCTIONS`).
+
+ Answered on the parse rather than on raw text, because position is what
+ makes it the construct: a column or alias merely *called* ``nextval`` is
+ an ordinary column, and a string literal holding the word is text.
+ """
+ return bool(
+ statement.get_column_names() & SEQUENCE_PSEUDO_COLUMNS
+ or statement.get_disallowed_functions(set(SEQUENCE_FUNCTIONS))
+ )
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """
+ Whether the transform contains a balanced Jinja block.
+
+ A block is an opening delimiter followed, anywhere later, by its closing
+ one -- the same thing ``{{.*?}}`` and its two siblings match under
+ ``re.DOTALL``. Scanned with `str.find` rather than that pattern, because a
+ lazy match retried from every opening delimiter is quadratic in a run of
+ them, and this runs on stored transforms with no length bound of its own:
+ `is_transform_active` reads whatever the column holds. The earliest opening
+ delimiter is the only one worth trying, since any closing delimiter after a
+ later one is also after it.
+ """
+ if not transform:
+ return False
+ for opening, closing in JINJA_BLOCK_DELIMITERS:
+ start = transform.find(opening)
+ if start != -1 and transform.find(closing, start + len(opening)) != -1:
+ return True
+ return False
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+
+ Three spellings have to be looked for, because one name reaches the parse
+ three ways: as a function call, as a zero-argument call a dialect resolves
+ itself, and -- for the datetime keywords -- as a bare word that parses as a
+ column reference.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ # The parenthesis-free spellings, which parse as columns rather than
+ # functions and so are invisible to the walk above. See
+ # `BARE_WALL_CLOCK_KEYWORDS`.
+ found |= {
+ name.upper() for name in BARE_WALL_CLOCK_KEYWORDS & statement.get_column_names()
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ # An array holds no scalar a transform could return, so no mirror onto it
+ # can ever compare. Refused for the mapping rather than only per value, so
+ # the Explore glyph stops promising one: a probe of ``:value`` succeeds and
+ # records a working transform, and only the later type gate declined.
+ if declares_array_type(columns_by_name[partition_column].type):
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error( # noqa: C901
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ And it must be a *read*. Shape is a separate question from effect: a bare
+ scalar expression can still write, so `SQLStatement.is_mutating` is asked
+ too -- the same question SQL Lab and the chart executor ask before letting
+ SQL run. See the gate itself for what that reaches and what it does not.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ # Also ahead of the parse, and for a stronger reason than cost: every gate
+ # below reasons about the parse tree, and this is the one construct that
+ # makes the parse tree describe a different statement from the one the
+ # engine runs. Checked here as well as in `validate_transform` because this
+ # is the door a row written by an earlier release still comes through.
+ if contains_executable_comment(transform):
+ return str(
+ _(
+ "A partition value transform cannot contain a MySQL "
+ "executable comment, which the database executes and every "
+ "validator reads as a comment."
+ )
+ )
+
+ if contains_unicode_escaped_identifier(transform):
+ return str(
+ _(
+ "A partition value transform cannot name anything through a "
+ 'U&"..." escape sequence, which the database decodes and '
+ "every validator reads literally."
+ )
+ )
+
+ # Same door, same reason: the name the denylist below would match is not
+ # the name the engine resolves. See `UNICODE_ESCAPED_IDENTIFIER_RE`.
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The read-only gate, which nothing above implies. The shape gates ask what
+ # the transform *selects*; this asks what evaluating it *does*, and a bare
+ # scalar expression can still write. `nextval(:value)` on PostgreSQL
+ # advances a sequence: one function call, no clause, no sub-query, and not
+ # in the default `DISALLOWED_SQL_FUNCTIONS` either -- so every gate above
+ # passes it and the probe then runs it. `setval` is the same shape, and
+ # `exp.Execute` and the opaque-`exp.Command` forms arrive the same way.
+ #
+ # The large-object writers (`lo_export`, `lowrite`, `lo_from_bytea`, ...)
+ # are caught here too, and the shipped denylist happens to name them as
+ # well -- but that is config an operator can replace, while this is not.
+ #
+ # `is_mutating` is the same question SQL Lab, `get_virtual_table_metadata`
+ # and the chart executor ask before letting SQL run, so a transform is held
+ # to the bar the rest of Superset already sets rather than to one invented
+ # here. Unconditional rather than gated on `Database.allow_dml`: a transform
+ # is a scalar function of `:value` by definition, so there is no legitimate
+ # mutating one, and the probe runs on a cache schedule nobody chose -- a
+ # write would repeat every time the entry expired.
+ #
+ # It bears saying what this does not reach. A user-defined function whose
+ # body writes is a plain call no parser can tell from `lower(:value)`, and
+ # `is_mutating`'s function-name walk is PostgreSQL-only by design, since the
+ # same names are read-only elsewhere. Neither residual is specific to this
+ # feature -- a dataset editor can already have the engine evaluate an
+ # arbitrary expression through a calculated column or a virtual dataset's
+ # SQL -- and closing them means authorizing the preview against the
+ # database, not parsing harder.
+ if statement.is_mutating():
+ return str(
+ _(
+ "A partition value transform cannot change data. It is "
+ "evaluated against the database to check that it mirrors, so "
+ "it has to be a read."
+ )
+ )
+
+ # Not reached by the walk above, which is why it is its own gate: a
+ # sequence pseudo-column is a *column* to the parser and a write to the
+ # engine. See `SEQUENCE_PSEUDO_COLUMNS`.
+ if references_sequence(statement):
+ return str(
+ _(
+ "A partition value transform cannot read a sequence. "
+ "NEXTVAL advances the sequence every time it is evaluated, "
+ "and the transform is evaluated on a cache schedule."
+ )
+ )
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the
+ probe uninspected. Rendering is not what makes that true: a string element
+ is checked by `literal_round_trips` before it is rendered -- the dialect's
+ literal processor and the engine's lexer do not always agree about what a
+ rendered literal says -- and `probe_sql_is_evaluable` re-reads the finished
+ query, which is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def _placeholder_is_bindable(transform: str) -> bool:
+ """
+ Whether SQLAlchemy's ``text()`` can see ``:value`` as a bound parameter.
+
+ `VALUE_PLACEHOLDER_RE` is ``:value\b``, which matches the placeholder in a
+ Postgres cast such as ``:value::bigint``. SQLAlchemy's own bind scan is
+ ``(?<![:\\w$]):([\\w$]+)(?![:\\w$])`` -- note the trailing exclusion -- so a
+ following colon stops it: ``text(":value::bigint")`` reports a parameter
+ named ``valu``, and ``.bindparams(bindparam("value"))`` then raises
+ ``ArgumentError``.
+
+ `_probe` swallows that, so the only symptom was a perfectly valid transform
+ whose mapping silently never pruned, and a preview reporting an engine
+ failure for SQL that was never sent. Every write-side gate passes the
+ transform: it parses, it is a bare expression, and the placeholder *is* in
+ an executable position.
+
+ Answered by attempting the bind itself rather than by pattern-matching
+ ``::`` or reading ``text()``'s private parameter map, so this cannot
+ disagree with what `build_probe_sql` is about to do -- on any dialect, or on
+ a SQLAlchemy whose scan changes.
+ """
+ try:
+ sa.text(transform).bindparams(sa.bindparam("value", value=None))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return False
+ return True
+
+
+def escape_foreign_colons(transform: str) -> str:
+ """
+ ``transform`` with every colon but the ``:value`` placeholder escaped.
+
+ `sqlalchemy.text` reads any ``:word`` as a bind parameter, including one
+ inside a string literal, and an unbound parameter renders as ``NULL``
+ under literal binds rather than raising. So ``:value || \':suffix\'``
+ compiled to ``'us' || 'NULL'``: the mirror asked for a partition value no
+ row holds and the chart dropped rows, with no error for `_probe` to
+ swallow and nothing on screen to say so.
+
+ Escaped rather than refused, because a colon in a literal is ordinary --
+ ``concat(:value, \':\', region)`` builds a composite key -- and the
+ placeholder is the only colon this module means to interpret. `text()`
+ reads ``\\:`` as a literal colon.
+
+ Only the bound path needs this. A `RawProbeValue` or an unbindable
+ placeholder is substituted as text by `parse_skeleton`, which never hands
+ the transform to `text()` at all.
+ """
+ pieces: list[str] = []
+ cursor = 0
+ for match in VALUE_PLACEHOLDER_RE.finditer(transform):
+ pieces.append(transform[cursor : match.start()].replace(":", r"\:"))
+ pieces.append(match.group(0))
+ cursor = match.end()
+ pieces.append(transform[cursor:].replace(":", r"\:"))
+ return "".join(pieces)
+
+
+def literal_round_trips(value: Any, dialect: Dialect | None, engine: str) -> bool:
+ """
+ Whether the engine reads a rendered ``value`` back as that same value.
+
+ The probe runs with no bound parameters, so every value reaches the engine
+ as literal text the driver wrote (see `build_probe_sql`). Whether that text
+ says what the value says is a question about two independent spellings: the
+ driver's escaping, and the engine's lexer. SQLAlchemy's default renderer
+ doubles apostrophes and passes backslashes through; Hive and Spark honour
+ the backslash and not the doubling, so ``'O''Brien'`` is read there as two
+ adjacent literals -- the transform is evaluated at ``OBrien``, and the
+ mirror asks for a partition key that holds none of the rows the filter
+ keeps. The same gap in the other direction lets a value close its own quote
+ and have the rest of it read as SQL.
+
+ Escaping is not the repair. Whether a backslash introduces an escape is a
+ per-session server setting -- ``standard_conforming_strings`` on Postgres,
+ ``NO_BACKSLASH_ESCAPES`` on MySQL, ``escapedStringLiterals`` on Spark -- and
+ nothing in the engine specs exposes it. SQLAlchemy reads it off the server
+ into ``_backslash_escapes`` during ``initialize(connection)``, which the
+ probe's dialect never reaches: `_dialect_for` asks the ``Database`` for a
+ dialect, not for a connection, so Postgres renders ``a\\b`` as
+ ``'a\\\\b'`` and a server with the standard setting reads four
+ characters. An engine-spec flag would have to be defaulted, and either
+ default is wrong for a dozen engines: one leaves the hole open, the other
+ corrupts the probed value.
+
+ So the premise is verified rather than declared, the way
+ `probe_sql_is_evaluable` verifies the finished statement. A value that does
+ not survive the round trip is not mirrored, which costs the query its
+ pruning and nothing else.
+
+ The short-circuit is a proof, not a guess, and it matters for cost: a
+ 200-member ``IN`` list would otherwise parse 200 times on the chart path.
+ If the renderer emitted the value between two quotes and changed nothing in
+ it, and the value carries neither a quote nor a backslash, then no lexer in
+ play can read it as anything but itself. Both exclusions are load-bearing:
+ on Hive ``a\\b`` renders verbatim and reads as ``a`` followed by a
+ backspace.
+
+ :param value: a filter value about to be rendered into the probe
+ :param dialect: the dialect that will render it, as `_dialect_for` reports
+ :param engine: ``database.backend``, whose lexer reads the result
+ :return: whether the two agree about what the literal says
+ """
+ if isinstance(value, RawProbeValue):
+ # Already SQL, with no single value for a parse to be compared against:
+ # its elements are checked before they are rendered, by
+ # `ExploreMixin._array_mirror_probe_value`. A backslash surviving into
+ # the finished text is refused here all the same, as the backstop for a
+ # renderer this module does not own.
+ return "\\" not in value.sql
+ if not isinstance(value, str):
+ # Numbers and instants are not written between delimiters, so there is
+ # no escaping for the two sides to disagree about.
+ return True
+
+ rendered = _compile_literal(sa.literal(value), dialect)
+ if rendered == f"'{value}'" and "'" not in value and "\\" not in value:
+ return True
+
+ try:
+ return (
+ SQLStatement(f"SELECT {rendered}", engine).get_select_literal_value()
+ == value
+ )
+ except SupersetParseError:
+ # A rendered literal the engine's own dialect will not parse is the
+ # strongest form of disagreement there is.
+ return False
+
+
+def value_round_trips(database: Database, value: Any) -> bool:
+ """
+ `literal_round_trips` for a caller holding a database, not a dialect.
+
+ Which renderer and which lexer apply is this module's business, so the two
+ callers outside it -- the chart path's own gate in
+ `ExploreMixin.mirror_probe_request` and the mapping summary Explore reads
+ -- ask in these terms and stay out of it.
+
+ :param database: the database whose driver renders and whose engine reads
+ :param value: a filter value about to be rendered into the probe
+ :return: whether the two agree about what the literal says
+ """
+ return literal_round_trips(value, _dialect_for(database), database.backend)
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text. That is not itself a boundary:
+ the processor's escaping is not always the escaping the engine honours, and
+ a value can close its own quote through the gap. The boundary is
+ `literal_round_trips` on the way in -- which callers must have run, like
+ `stored_expression_error` below -- and `probe_sql_is_evaluable` on the way
+ out.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ bindable = _placeholder_is_bindable(transform)
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ elif bindable:
+ # Every other colon escaped first: `text()` would read one inside a
+ # string literal as a second bind parameter and render it `NULL`.
+ # See `escape_foreign_colons`.
+ clause = sa.text(escape_foreign_colons(transform)).bindparams(
+ sa.bindparam("value", value=value)
+ )
+ rendered = _compile_literal(clause, dialect)
+ else:
+ # `text()` cannot see the placeholder (see
+ # `_placeholder_is_bindable`), so the value is rendered by the
+ # dialect's own literal processor first and substituted as SQL
+ # text. The same two steps in the other order: binding exists to
+ # get the value through that processor, and `_compile_literal`
+ # inlines the result either way, so this is the same string by a
+ # different route -- not a loosening of the "never interpolate a
+ # raw value" rule. `parse_skeleton` substitutes literally, so the
+ # rendered literal arrives here exactly as it was rendered, which
+ # is what makes `literal_round_trips`' verdict on it good for this
+ # branch as much as for the bound one.
+ rendered = parse_skeleton(
+ transform, _compile_literal(sa.literal(value), dialect)
+ )
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Five things have to hold, and all five are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+ * No comment, anywhere. A value that closes its own quote has to hide the
+ text `build_probe_sql` appended after it, and a comment is the only way
+ to do that and still balance the quotes -- so this is what makes the
+ alias check above sufficient rather than merely necessary. Read off the
+ parse rather than the text, so a comment *inside* a literal is data and
+ costs no pruning, and so the question is asked in the engine's own
+ dialect. A transform has no legitimate reason to carry one either; see
+ `EXECUTABLE_COMMENT_RE`.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ # Before the parse, because this gate's whole contract is that what the
+ # parse describes is what the engine will run, and an executable comment is
+ # precisely the text where that stops being true. The transform is already
+ # refused for carrying one; this covers the compiled statement, so no later
+ # change to how values are rendered can reintroduce it behind the gates
+ # below.
+ if contains_executable_comment(sql) or contains_unicode_escaped_identifier(sql):
+ return False
+
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if not isinstance(statement, SQLStatement):
+ # A dialect whose statements this gate cannot take apart -- KQL -- gets
+ # no probe rather than an unchecked one. It never had one: the clause
+ # inspection below is implemented for SQL statements only, and the
+ # alternative to declining here is an `AttributeError` that `_probe`
+ # swallows into the same outcome, less legibly.
+ return False
+ if statement.has_comment():
+ return False
+ if statement.has_subquery():
+ return False
+ if statement.get_clause_names() - {"from"}:
+ return False
+ if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+ """
+ The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+ Parsed rather than string-compared so that the comparison in
+ `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+ not parse answers ``None``, which no statement carrying a FROM can match --
+ the probe then declines, which is the right way for an unreadable engine
+ constant to fail.
+ """
+ if not from_suffix.strip():
+ return None
+ try:
+ return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+ except SupersetParseError:
+ return None
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+ text_answers: list[tuple[int, Any]] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ :param text_answers: optional sink. When given, every date or timestamp in
+ ``values`` is also asked as the text a simple filter would bind, in the
+ same round trip, and ``(index, answer)`` is appended for each -- see
+ `_declined_for_reading_by_type` for why. A transform that refuses text
+ is asked again with ``values`` alone, so a refusal never costs pruning.
+ """
+ if not values:
+ return None
+
+ if text_answers is not None:
+ indexes = [
+ index
+ for index, value in enumerate(values)
+ if isinstance(value, date) and not is_unmirrorable(value)
+ ]
+ if indexes:
+ combined = evaluate_transform(
+ database,
+ catalog,
+ schema,
+ transform,
+ values + [_as_filter_text(values[index]) for index in indexes],
+ )
+ if combined is not None:
+ text_answers.extend(zip(indexes, combined[len(values) :], strict=False))
+ return combined[: len(values)]
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ # The value side of the premise `probe_sql_is_evaluable` checks on the
+ # finished statement: a value the driver and the engine would spell
+ # differently is not probed at all -- see `literal_round_trips`.
+ #
+ # `ExploreMixin.mirror_probe_request` declines one earlier, with a reason
+ # the preview can explain, and that is the gate an owner sees. This is the
+ # one that cannot be walked around. `_collect_partition_mirror_range`
+ # appends its bounds into the sink without passing through that method at
+ # all, and both paths can hand back a value the gate never saw: on a column
+ # carrying a `python_date_format`, what is probed is
+ # `strftime(that format)` -- text no mapping gate has ever read.
+ #
+ # Above `_run_probe` on purpose. This is a property of one input, not of
+ # the transform, and a verdict recorded here would withdraw the mirror for
+ # every later value of a transform the engine evaluates perfectly well.
+ dialect = _dialect_for(database)
+ if not all(
+ literal_round_trips(value, dialect, database.backend) for value in distinct
+ ):
+ logger.warning(
+ "A filter value is not written the same way by the driver and the "
+ "database, so the partition transform is not probed at it; this "
+ "query will not prune"
+ )
+ return None
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+
+ The verdict is about the *transform*: whether the engine evaluated it at
+ all. A ``NULL`` among the results is not that -- it is this input's answer,
+ and `NULLIF(:value, 0)` returning ``NULL`` for ``n = 0`` says nothing about
+ the same transform on ``n = 2``. Counting it withdrew the promise for the
+ whole transform, and nothing restored it: a *failed* probe is deliberately
+ not cached, so the next chart re-probes and re-records, but a ``NULL`` is a
+ successful probe and *is* cached -- so the false verdict outlived every
+ later hit, and the editor reported a working mapping as not mirroring
+ while the query went on pruning. The per-input skip still happens where it
+ belongs, in the caller's own ``NULL`` guard.
+
+ A probe where *every* input answers ``NULL`` is different only when it is
+ all the evidence there is. ``trunc(..., 'HH')`` on Hive returns ``NULL`` for
+ any input, and recording that as a working transform left Explore's glyph
+ promising a partition predicate no query carried. So an all-``NULL`` probe
+ records ``False`` -- but never over a stored ``True``, which some other
+ input earned and the ``NULLIF`` case above must keep. A later probe that
+ answers anything restores ``True`` the ordinary way: a fresh input misses
+ the probe cache, so it re-records.
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ if values is None:
+ mirrors = False
+ elif any(value is not None for value in values):
+ mirrors = True
+ elif known_mirror_verdict(database, catalog, schema, transform) is not True:
+ mirrors = False
+ else:
+ return values
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=mirrors,
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ from_suffix = database.db_engine_spec.select_without_from_suffix
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ from_suffix,
+ )
+ if not probe_sql_is_evaluable(
+ sql, database.backend, len(distinct), from_suffix
+ ):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _execution_identity(database: Database) -> str | None:
+ """
+ Who the warehouse will run the probe as, when that can vary by caller.
+
+ `_probe_cache_key` keys on the `Database` record, which is the *connection*
+ -- not the identity it is opened under. Two hooks make that identity a
+ function of the Superset user instead:
+
+ * ``impersonate_user`` on the database, which hands the effective username
+ to `db_engine_spec.impersonate_user`;
+ * ``DB_CONNECTION_MUTATOR``, which receives the effective username and may
+ return an entirely different account's URL.
+
+ Under either one, a cached probe result computed under user A's grants was
+ served to user B, and the preview echoed it back in ``emitted_predicate``.
+ A transform wrapping a read-capable function the denylist does not name --
+ Oracle's ``DBMS_XMLGEN.GETXML`` is the worked example -- then leaks across
+ users who were never allowed the same rows.
+
+ Returns ``None`` when neither hook is configured, which is the common case
+ and deliberately leaves the key as it was: the cache exists to keep a
+ synchronous warehouse round trip off the chart-query path, and keying every
+ deployment on the username would cost every deployment the hit rate to fix
+ the two that need it.
+
+ The *Superset* username rather than the resolved warehouse account, because
+ it is the input both hooks branch on, and reading it needs no URL parse and
+ puts no credential in the key.
+ """
+ if not (database.impersonate_user or app.config["DB_CONNECTION_MUTATOR"]):
+ return None
+ return get_username()
+
+
+#: Bumped whenever what the probe cache or the verdict cache *means* changes,
+#: so entries written under the old meaning are never read under the new one.
+#: v2: an all-``NULL`` probe stopped recording a working transform. A ``True``
+#: stored before that is indistinguishable from one another input earned, so
+#: it would have kept Explore's glyph lit for up to a cache timeout -- and the
+#: cached probe results behind it would have kept any query from re-probing
+#: and writing a fresh one.
+PROBE_CACHE_VERSION = "v2"
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{PROBE_CACHE_VERSION}:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _mirror_verdict_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str:
+ """
+ `_probe_cache_key` without the values.
+
+ Whether a transform can be evaluated at all is a property of the transform
+ and the connection, not of the filter that happened to be probing it, so
+ one chart's answer settles the question for the next one.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ # Whether a transform *can* be evaluated is a property of the
+ # transform and the connection -- but under impersonation the
+ # connection is per-user, and a function one account may call can
+ # be refused to another. See `_execution_identity`.
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_verdict:{PROBE_CACHE_VERSION}:{digest}"
+
+
+def record_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ *,
+ mirrors: bool,
+) -> None:
+ """
+ Remember whether this transform produced a mirror, for the UI to read.
+
+ Advisory only. Nothing in the query path consults it: a probe that failed
+ once is retried on the next chart exactly as it is today, because declining
+ to prune for a whole cache timeout over one transient engine blip is the
+ trade `evaluate_transform` deliberately refuses -- see the comment where it
+ declines to cache a failure.
+
+ What this is for is the *claim*. `is_transform_active` parses the transform
+ and no more, so a transform the database rejects -- a misspelled function
+ is the common case -- is "active", and the editor's banner and Explore's
+ pruning glyph promise a speed-up that never happens. A promise is exactly
+ the thing that may be withheld on one bad answer and restored on a good
+ one, which is why this is a separate entry from the probe's own results
+ rather than a relaxation of that rule.
+
+ Written by `_run_probe`, so the preview endpoint -- which shares the
+ evaluator -- settles the question before the owner has even saved.
+ """
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(
+ _mirror_verdict_cache_key(database, catalog, schema, transform),
+ mirrors,
+ timeout=timeout,
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform verdict", exc_info=True)
+
+
+def known_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> bool | None:
+ """
+ The last verdict `record_mirror_verdict` stored, or `None` if there is none.
+
+ `None` is the honest answer on a cold cache and is deliberately not `False`:
+ reporting a working mapping as broken until something probes it would
+ trade one wrong claim for another. The alternative -- probing from the
+ read side -- would put a warehouse round trip on every Explore and
+ dashboard load, and a failing transform is not cached at all, so it would
+ be a round trip every single time.
+ """
+ try:
+ verdict = cache_manager.cache.get(
+ _mirror_verdict_cache_key(database, catalog, schema, transform)
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return verdict if isinstance(verdict, bool) else None
+
+
+def _compile_literal(element: Any, dialect: Dialect | None) -> str:
+ """
+ Compile with inline literals, undoing the paramstyle's percent doubling.
+
+ Both ``TextClause`` and literal compilation run the dialect's
+ ``post_process_text``, which doubles every ``%`` whenever the identifier
+ preparer asks it to -- true for MySQL and Postgres and for every spec
+ inheriting their paramstyle. That doubling exists so a later DBAPI
+ parameter-interpolation pass can undo it, and the probe has no such pass:
+ it executes with no bound parameters at all. So a transform of
+ ``date_format(:value, '%Y%m%d')`` reaches the warehouse asking for the
+ literal string ``%%Y%%m%%d``, the probe returns that instead of a date, and
+ the mirrored predicate drops every row the filter keeps.
+
+ The same normalization ``Database.compile_sqla_query`` applies for the same
+ reason. ``_double_percents`` is private and not guaranteed on a third-party
+ dialect, hence the ``getattr`` default.
+ """
+ compiled = str(
+ element.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
+ )
+ if dialect is not None and getattr(
+ dialect.identifier_preparer, "_double_percents", False
+ ):
+ compiled = compiled.replace("%%", "%")
+ return compiled
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be *asked* to stand in for itself, and the transform
+ cannot carry Jinja or call a non-deterministic function. Tier 2
+ (``blocking=False``) is everything that merely leaves the mapping inactive
+ -- including a self-mapping nobody asked for, where the partition column
+ merely happens to be the default datetime column.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column == partition_column:
+ # Asked for explicitly, so report it as the mistake it is.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+ elif not partition_mapped_column and main_dttm_col == partition_column:
+ # Resolved onto itself only because the default datetime column happens
+ # to be the partition column -- a state metadata sync could produce
+ # without anyone asking for it. The mapping is inert either way, since
+ # `resolve_partition_mapping` bails out on it, so this reports and lets
+ # the write through: blocking here means a dataset already in the state
+ # can never be saved again, not even to change its description, and
+ # there is no field whose edit would clear the error first.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "%(name)s is both the partition column and the default "
+ "datetime column, so the mapping points at itself and "
+ "stays inactive. Set a mapped column override, or change "
+ "the default datetime column.",
+ name=partition_column,
+ ),
+ blocking=False,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def drop_unmapped_value_transforms(
+ columns: list[dict[str, Any]] | None,
+ *,
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ names_by_id: dict[int, str] | None = None,
+ stored_by_name: dict[str, tuple[str | None, bool]] | None = None,
+) -> list[str]:
+ """
+ Null the value transform on every *incoming* column the mapping cannot mirror.
+
+ The write-side twin of `DatasetDAO.clear_unmapped_partition_transforms`,
+ which answers for the model. A mapping has exactly one mirrored column, so
+ at most one column may carry a transform. One parked on any other column is
+ invisible -- no row but the mapped one renders a transform -- and yet it is
+ stored, and it goes live the moment the mapped column resolves back to it.
+ Clearing an override is enough to do that: a null
+ ``partition_mapped_column`` means "follow ``main_dttm_col``".
+
+ Ungated on the feature flag, unlike its model-level twin, and the difference
+ is what each one discards. That one drops stored configuration, so with the
+ flag off it would be pure loss. This one drops only a value the request in
+ hand is asking to write where the invariant says none may live -- and the
+ flag-off window is precisely when such a value gets parked for later, since
+ the editor hides these fields and the model-level pass declines to run.
+
+ Three writers reach the columns with no effective model-level pass between
+ them, which is why this exists at all: the deprecated
+ ``POST /datasource/save/``, which writes straight through
+ `update_from_object` and so never had one; and a
+ ``PUT /api/v1/dataset/<pk>`` or a dataset import made while the flag is
+ off, where the pass runs on both sides of the write and declines on both.
+
+ Mutates the payload in place, because every caller hands its own request
+ dict straight on to the code that writes it. Returns the names it cleared,
+ so the caller can say so in a log: this is a silent correction to a payload
+ whose author may have meant it.
+
+ A column whose payload mentions neither field is left alone. "Incoming" is
+ the whole scope -- a transform already in storage on a column this request
+ says nothing about is the model-level pass's business, under its own flag.
+
+ The mapped column resolves the way every other reader resolves it,
+ ``partition_mapped_column or main_dttm_col``, and resolves to nothing
+ without a partition column -- in which case no column may hold a transform
+ either.
+
+ :param names_by_id: how to read the name off a payload entry that gives
+ only an ``id``. `DatasetDAO._upsert_columns` identifies an existing
+ column by its primary key and lets ``column_name`` be omitted -- the
+ column keeps the name it has -- so without this an ordinary PUT looked
+ like a payload of nameless columns, none of which matched the mapped
+ one, and every transform in it was dropped. Callers whose writer keys
+ on the name instead (`update_from_object`, the importer) pass nothing.
+ An entry this cannot name is left alone rather than guessed at.
+ :param stored_by_name: ``(transform, is_monotonic)`` as currently stored,
+ per column name, so an *echo* can be told from an introduction. A
+ GET-then-PUT client sends back every column exactly as it received it,
+ so changing the default datetime column away from the mapped one made
+ the payload's unchanged copy of its transform look like a value being
+ parked -- and nulling it destroyed configuration the owner never
+ touched, unrecoverably, with the flag off and the editor's own fields
+ hidden. An unchanged value is the model-level pass's business under its
+ own flag, which is the same line this function's docstring already
+ draws for a column the payload omits. Callers that cannot see storage
+ pass nothing and keep the stricter behaviour.
+ """
+ mapped_column = (
+ (partition_mapped_column or main_dttm_col) if partition_column else None
+ )
+ cleared: list[str] = []
+ for column in columns or []:
+ name = column.get("column_name")
+ if name is None and names_by_id is not None:
+ column_id = column.get("id")
+ if column_id is not None:
+ name = names_by_id.get(column_id)
+ if name is None or name == mapped_column:
+ continue
+ transform = column.get("partition_value_transform")
+ is_monotonic = column.get("partition_transform_is_monotonic")
+ if not transform and not is_monotonic:
+ continue
+ if stored_by_name is not None and name in stored_by_name:
+ stored_transform, stored_monotonic = stored_by_name[name]
+ # A key the entry does not carry is unchanged, not `False`:
+ # `_upsert_columns` writes only the keys present, so echoing the
+ # transform without the declaration is a valid partial update. Read
+ # as a change, it failed the exemption and wrote both fields back
+ # as null -- the loss the exemption exists to prevent.
+ monotonic_echoes = "partition_transform_is_monotonic" not in column or bool(
+ is_monotonic
+ ) == bool(stored_monotonic)
+ transform_echoes = (
+ "partition_value_transform" not in column
+ or transform == stored_transform
+ )
+ if transform_echoes and monotonic_echoes:
+ # An echo, not an introduction. See `stored_by_name`.
+ continue
+ column["partition_value_transform"] = None
+ column["partition_transform_is_monotonic"] = False
+ cleared.append(name)
+ return cleared
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if contains_executable_comment(transform):
+ # Blocking, and checked on raw text next to the Jinja gate because no
+ # parse reports it: sqlglot reads `/*!50000 ... */` as comment data
+ # while MySQL and MariaDB execute it, so every shape gate downstream
+ # inspects a statement the engine will not run. See
+ # `EXECUTABLE_COMMENT_RE`.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform cannot contain a MySQL executable "
+ "comment (/*! ... */ or /*M! ... */). Those are comments "
+ "to every validator and statement text to the database, "
+ "so what would run is not what was checked."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if contains_unicode_escaped_identifier(transform):
+ # Beside the comment gate, for the same reason and on raw text: the
+ # parse reports the escape sequence verbatim as the function's name,
+ # so the function denylist compares against a name PostgreSQL never
+ # uses -- it decodes `U&"\0071uery_to_xml"` and runs `query_to_xml`.
+ # See `UNICODE_ESCAPED_IDENTIFIER_RE`.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ 'A value transform cannot name anything through a U&"..." '
+ "escape sequence. The database decodes it and every "
+ "validator reads it literally, so what would run is not "
+ "what was checked."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_bare_expression(transform, engine):
+ # Blocking, and deliberately placed in `validate_transform` rather than
+ # only at the probe: one issue here closes the PUT, the importer, the
+ # query-time gate through `is_transform_active`, the Explore indicator's
+ # active verdict and the preview endpoint, all of which already consult
+ # this function.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform must be a single SQL expression. It "
+ "cannot carry a FROM, WHERE, GROUP BY or any other clause, "
+ "and it cannot contain a sub-query."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not contains_value_placeholder(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform must contain the :value placeholder, "
+ "which stands for the filter value being mirrored."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not placeholder_is_executable(transform, engine):
+ # Blocking, and for the same reason the shape gate above is: this is
+ # the function the PUT, the importer, `is_transform_active`, the
+ # Explore indicator and the preview all consult, so one issue here
+ # closes every door at once. A placeholder inside a string literal is
+ # a sub-query the engine will run once a filter value closes the quote;
+ # one inside a comment silently eats the probe's own alias.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The :value placeholder must appear where the engine will "
+ "evaluate it. It cannot sit inside a string literal or a "
+ "comment."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if functions := find_non_deterministic_functions(transform, engine):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform calls %(functions)s, whose result "
+ "depends on when and where it runs. The transform is "
+ "evaluated in a separate session and the result is cached, "
+ "so the emitted predicate would freeze a snapshot of that "
+ "moment.",
+ functions=", ".join(sorted(functions)),
+ ),
+ blocking=True,
+ )
+ ]
+
+ return []
+
+
+@lru_cache(maxsize=LRU_CACHE_MAX_SIZE)
+def is_transform_active(transform: str | None, engine: str) -> bool:
+ """
+ Whether Superset will mirror filters through this transform.
+
+ `validate_transform` with the messages discarded, so the Explore indicator
+ cannot advertise a mapping the save path recorded as inactive. Anything
+ cheaper here would be a second, weaker statement of the same rule, free to
+ drift from the one the save path applies.
+
+ Blocking issues count too. Jinja and non-deterministic transforms are
+ rejected on PUT, but `CreateDatasetCommand` and import do not validate the
+ mapping, so one can still reach the database -- and it would never mirror a
+ filter either.
+
+ Memoized because `partition_filter_mapping_summary` is serialized on every
+ Explore and dashboard load and this parses the transform. The key is
+ everything the answer depends on: `validate_transform` reads no session, no
+ locale and no config beyond `SQL_MAX_PARSE_LENGTH`, which bounds the parser
+ rather than changing a verdict within that bound.
+ """
+ return not validate_transform(transform, engine)
+
+
+def preview_partition_mapping( # pylint: disable=too-many-return-statements
+ datasource: SqlaTable,
+ *,
+ mapped_column: str,
+ value_transform: str | None,
+ sample_values: list[str],
+ operator: FilterOperator = FilterOperator.EQUALS,
+ is_monotonic: bool = False,
+ partition_column: str | None = None,
+) -> dict[str, Any]:
+ """
+ Evaluate a candidate mapping and describe the predicate it would emit.
+
+ Shares the evaluator -- and therefore the probe cache -- with the query
+ path, so preview and runtime cannot drift and a previewed transform warms
+ the chart path for free. The predicate itself comes from
+ `build_mirrored_predicates`, the same builder the query path uses, so
+ operator shapes cannot drift either: what the panel shows is what a chart
+ would emit.
+
+ Validation runs first and the engine second: a half-typed transform is by
+ definition unparseable, so most of what a text input produces costs zero
+ queries.
+
+ Every part of the mapping is taken from the request rather than the stored
+ dataset. The editor previews while the owner is still editing -- a mapping
+ that has to be saved before it can be checked is not a preview.
+ """
+ partition_column = partition_column or datasource.partition_column
+ if not partition_column:
+ return {
+ "valid": False,
+ "reason": "unconfigured",
+ "error": _("No partition column is set."),
+ }
+
+ columns_by_name = {str(column.column_name): column for column in datasource.columns}
+ if mapped_column not in columns_by_name:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _("%(name)s is not a column on this dataset.", name=mapped_column),
+ }
+
+ # The bail-out `resolve_partition_mapping` makes at query time, and that
+ # `partition_filter_mapping_summary` repeats for the Explore indicator.
+ # Without it here, preview reports a valid emitted predicate for a mapping
+ # no chart will ever mirror -- the one answer a preview panel must not give.
+ if has_active_advanced_data_type(columns_by_name[mapped_column]):
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _(
+ "%(name)s has an advanced data type, so its filters are "
+ "translated into their own predicate shape and cannot be "
+ "mirrored onto the partition column.",
+ name=mapped_column,
+ ),
+ }
+
+ engine = datasource.database.backend
+ for issue in validate_partition_mapping(
+ column_names=set(columns_by_name),
+ partition_column=str(partition_column),
+ partition_mapped_column=mapped_column,
+ main_dttm_col=datasource.main_dttm_col,
+ transform=value_transform,
+ engine=engine,
+ ):
+ return {
+ "valid": False,
+ # The parse failure is the one an owner sees constantly, and it is
+ # the only one the mockup gives its own headline to.
+ "reason": (
+ "parse"
+ if issue.field == "partition_value_transform"
+ and not is_parseable(value_transform, engine)
+ else "validation"
+ ),
+ "error": str(issue.message),
+ }
+
+ # The policy every other stored expression goes through. The save path
+ # applies it in `UpdateDatasetCommand._validate_partition_mapping`, but
+ # preview evaluates a candidate transform that has not been saved, so
+ # without this the gate had a door around it. See
+ # `stored_expression_error` for what is being kept out and why.
+ if reason := stored_expression_error(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ cast(str, value_transform),
+ ):
+ return {"valid": False, "reason": "validation", "error": reason}
+
+ mapping = PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=mapped_column,
+ value_transform=cast(str, value_transform),
+ is_monotonic=is_monotonic,
+ equality_is_safe=equality_mirrors_safely(
+ columns_by_name[mapped_column], datasource.database.db_engine_spec
+ ),
+ )
+ sample_input = _render_sample_input(
+ datasource, mapped_column, operator, sample_values
+ )
+
+ if operator not in PREVIEWABLE_OPERATORS:
+ # Checked before `mirrors`, which lets `TEMPORAL_RANGE` through when the
+ # transform is declared monotonic -- and the single sample value would
+ # then reach `handle_comparison_filter`, which has no case for a range
+ # and raises. The request schema rejects it too; this keeps the function
+ # honest for any other caller.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is mirrored as a pair of bounds, which "
+ "a preview of a single value cannot describe.",
+ operator=operator.value,
+ ),
+ }
+
+ if operator in MIRRORABLE_ALWAYS and not mapping.equality_is_safe:
+ # Withdrawn by `equality_mirrors_safely`, which no declaration about
+ # ordering can change -- so naming monotonicity here would send the
+ # owner to a checkbox that leaves the answer as it is.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter on this text column is not mirrored: "
+ "the database may treat strings that differ in case or "
+ "trailing spaces as equal, and the mirrored predicate could "
+ "then drop rows the filter keeps.",
+ operator=operator.value,
+ ),
+ }
+
+ if not mapping.mirrors(operator):
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is only mirrored when the transform "
+ "preserves ordering, which this one is not declared to do.",
+ operator=operator.value,
+ ),
+ }
+
+ return _preview_probe(
+ datasource,
+ mapping,
+ columns_by_name[mapped_column],
+ operator,
+ sample_values,
+ sample_input,
+ )
+
+
+def _preview_probe(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ mapped_col: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+ sample_input: str,
+) -> dict[str, Any]:
+ """
+ The half of a preview that needs the warehouse.
+
+ Split out from `preview_partition_mapping` so that the gates which answer
+ from the stored mapping alone stay readable as the single run of guard
+ clauses they are. Everything here has either run a query or decided not to.
+
+ A chart hands the transform a temporal value in two shapes. A simple filter
+ binds the text the author typed; a time range binds a `datetime`, which the
+ dialect writes as a typed literal (``TO_DATE(...)`` on Oracle). A
+ transform can read the two differently -- ``TO_DATE(:value, fmt)`` parses
+ the text, but converts the typed value back to text through the session's
+ ``NLS_DATE_FORMAT`` first and lands in year 0012 -- and previewing only the
+ text said valid for a mapping whose every time range came back empty. So a
+ temporal sample is previewed as the time range sends it. Comparing it with
+ the text shape is `build_mirrored_predicates`' job rather than this
+ function's, so the chart path runs the same check -- see
+ `_declined_for_reading_by_type`.
+ """
+ probe_input = _probe_input(datasource, mapped_col, operator, sample_values)
+ range_input = _as_range_bound(mapped_col, operator, probe_input)
+ return _preview_probe_value(
+ datasource,
+ mapping,
+ mapped_col,
+ operator,
+ datasource.mirror_probe_request(
+ operator,
+ range_input if range_input is not None else probe_input,
+ mapped_col,
+ ),
+ sample_input,
+ )
+
+
+def _as_range_bound(
+ column: "TableColumn",
+ operator: FilterOperator,
+ probe_input: Any,
+) -> datetime | None:
+ """
+ The `datetime` a time range would hand the transform for this sample, or
+ `None` where the sample is not a temporal bound a time range could carry.
+ """
+ # Imported here: `superset.models.helpers` imports this module.
+ from superset.models.helpers import ( # pylint: disable=import-outside-toplevel
+ _instant_from_filter_value,
+ )
+
+ if not column.is_dttm or operator == FilterOperator.IN:
+ return None
+ if not isinstance(probe_input, str):
+ return None
+ instant = _instant_from_filter_value(probe_input)
+ if instant is None or instant.tzinfo is not None:
+ return None
+ return instant
+
+
+def _preview_probe_value(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ mapped_col: "TableColumn",
+ operator: FilterOperator,
+ value: Any,
+ sample_input: str,
+) -> dict[str, Any]:
+ """`_preview_probe` for one shape of the probe input."""
+ if is_unmirrorable(value):
+ # The same step the chart path applies, so the preview cannot promise a
+ # mirror the query declines -- and it reports the reason that step
+ # recorded rather than deriving one of its own, which is what let the
+ # offset case be explained as a precision loss it is not.
+ if value.reason == "offset":
+ # The transform is fine and the column may well compare the whole
+ # instant; what cannot be mirrored is the frame. Advising a
+ # different column here would send the owner after a column they
+ # already have.
+ return {
+ "valid": False,
+ "reason": "offset",
+ "sample_input": sample_input,
+ "error": _(
+ "A filter value carrying a UTC offset is not mirrored: a "
+ "transform is evaluated in the database's own time frame, "
+ "so the mirrored predicate could ask for a partition the "
+ "matching rows are not in. Write the bound without an "
+ "offset to mirror this filter.",
+ ),
+ }
+ if value.reason == "escaping":
+ # Nothing about the column, the operator or the transform is wrong
+ # here, so none of the advice the other branches carry applies: the
+ # driver and the database disagree about how to write this value
+ # down. Said in terms of the value, which is the only thing the
+ # owner can change.
+ return {
+ "valid": False,
+ "reason": "escaping",
+ "sample_input": sample_input,
+ "error": _(
+ "A filter value containing a quote or a backslash is not "
+ "mirrored on this database: the driver and the database do "
+ "not agree on how to write it into a query, so the "
+ "transform would be evaluated at a value the filter does "
+ "not compare. Filters whose values carry neither still "
+ "mirror.",
+ ),
+ }
+ # The transform is fine and the engine evaluates it, the filter just
+ # carries more of the value than the engine compares on this column --
+ # which is the column's type talking, not a broken expression.
+ return {
+ "valid": False,
+ "reason": "resolution",
+ "sample_input": sample_input,
+ "error": _(
+ "This engine compares less of a %(operator)s value on "
+ "%(column)s than the filter carries, so there is no mirror a "
+ "predicate on the partition column could stand in for. Map a "
+ "column the engine compares in full to mirror this operator.",
+ operator=operator.value,
+ column=mapped_col.column_name,
+ ),
+ }
+ errors: list[str] = []
+ type_errors: list[str] = []
+ escaping_errors: list[str] = []
+ shape_errors: list[str] = []
+ try:
+ predicates = build_mirrored_predicates(
+ datasource,
+ mapping,
+ [(operator, value)],
+ errors=errors,
+ type_errors=type_errors,
+ escaping_errors=escaping_errors,
+ shape_errors=shape_errors,
+ )
+ except Exception: # pylint: disable=broad-except
+ # The chart path fails open on the same call; the preview reports it
+ # as a mapping that will not mirror rather than as a server error.
+ logger.warning("Could not preview the partition mapping", exc_info=True)
+ return {
+ "valid": False,
+ "reason": "engine",
+ "sample_input": sample_input,
+ "error": _("The transform could not be evaluated against the database."),
+ }
+ if shape_errors:
+ return {
+ "valid": False,
+ "reason": "shape",
+ "sample_input": sample_input,
+ "error": shape_errors[0],
+ }
+ if type_errors:
+ # Its own reason, because "the database would not evaluate this" and
+ # "it evaluated and answered with the wrong kind of thing" are
+ # different problems with different fixes, and the owner is the only
+ # one who can tell which transform they meant to write.
+ return {
+ "valid": False,
+ "reason": "type",
+ "sample_input": sample_input,
+ "error": type_errors[0],
+ }
+ if escaping_errors:
+ # Its own reason, and distinct from the `escaping` one above: that is
+ # about the value the chart author typed, this is about what the
+ # transform made of it. Falling through to `engine` below told the owner
+ # the database would not evaluate the transform, when it evaluated it
+ # perfectly and answered with a key that cannot be asked for here.
+ return {
+ "valid": False,
+ "reason": "transform_escaping",
+ "sample_input": sample_input,
+ "error": escaping_errors[0],
+ }
+ if not predicates:
+ return {
+ "valid": False,
+ "reason": "engine",
+ "sample_input": sample_input,
+ "error": (
+ _(
+ "The transform could not be evaluated against the "
+ "database: %(reason)s",
+ reason=errors[0],
+ )
+ if errors
+ else _("The transform could not be evaluated against the database.")
+ ),
+ }
+
+ return {
+ "valid": True,
+ "sample_input": sample_input,
+ "emitted_predicate": _render_predicate(datasource, predicates[0]),
+ }
+
+
+def _probe_input(
+ datasource: SqlaTable,
+ column: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+) -> Any:
+ """
+ The sample values as the query path would bind them.
+
+ The request carries samples as strings, and the probe is keyed on exactly
+ what it is handed, so passing them through raw asks the engine a different
+ question from the one a chart asks. A sample of ``2025`` on a numeric
+ column has to arrive as the integer the chart compares: under a transform
+ of ``typeof(:value)`` the raw string previewed ``'text'`` where the chart
+ emitted ``'integer'``. And because `_probe_cache_key` keys on each value's
+ ``repr``, the two also missed each other's cache entirely -- so the "a
+ previewed transform warms the chart path for free" claim in
+ `preview_partition_mapping`'s docstring did not actually hold.
+
+ Coerced by `filter_values_handler`, the same function the query path uses,
+ rather than by a second implementation of the same rules. Everything the
+ query path then does to the coerced value -- rendering an expression as a
+ literal, widening a bound, declining a comparison the engine resolves too
+ coarsely -- is `ExploreMixin.mirror_probe_request`'s, and the caller hands
+ this result straight to it.
+
+ Ranges are not previewable (see `PREVIEWABLE_OPERATORS`), so the bound
+ conversion `_collect_partition_mirror_range` applies -- a ``datetime`` into
+ the column's stored representation -- has no counterpart here.
+
+ An array column is the exception to `filter_values_handler`: its predicate
+ is built from the raw value, parsed into elements and rendered as the
+ engine's own array literal, so the chart path probes that literal
+ (`ExploreMixin._array_mirror_probe_value`) and this does too. Passing the
+ handled text instead previewed ``length('[1, 2]')`` for a filter whose
+ query probes ``length(array(1, 2))``.
+
+ Answers with a value, or `None` where an engine spec claims array columns
+ without an array literal -- which `mirror_probe_request` then declines, as
+ the chart path declines it. It may also answer with an `Unmirrorable` the
+ array branch raised itself, which `mirror_probe_request` passes through;
+ otherwise the decline is that method's to make, and the caller hands this
+ straight to it.
+ """
+ is_list = operator == FilterOperator.IN
+ column_spec = datasource.db_engine_spec.get_column_spec(native_type=column.type)
+ if (
+ column_spec
+ and column_spec.generic_type == utils.GenericDataType.MULTI_VALUE
+ and operator in MIRRORABLE_ALWAYS
+ ):
+ # `=` and `IN` are the previewable operators the array branch builds a
+ # literal for; a bound on an array column binds the handled value on
+ # the chart path too, so it falls through to the same here.
+ return datasource._array_mirror_probe_value( # noqa: SLF001
+ sample_values if is_list else sample_values[0],
+ operator,
+ datasource.db_engine_spec.get_array_element_type(column.type),
+ datasource.db_engine_spec,
+ )
+ handled = datasource.filter_values_handler(
+ # `list[str]` is not a `list[FilterValue]` to mypy, invariantly, even
+ # though every `str` is a `FilterValue`.
+ values=cast(FilterValues, sample_values if is_list else sample_values[0]),
+ operator=operator,
+ target_generic_type=(
+ column_spec.generic_type if column_spec else utils.GenericDataType.STRING
+ ),
+ target_native_type=column.type,
+ is_list_target=is_list,
+ db_engine_spec=datasource.db_engine_spec,
+ db_extra=datasource.db_extra,
+ )
+ # No `ColumnElement` conversion here: an epoch-milliseconds sample comes back
+ # as engine SQL rather than a value, and `mirror_probe_request` renders it --
+ # the same step, on the same values, as for a chart filter.
+ return handled
+
+
+def _render_sample_input(
+ datasource: SqlaTable,
+ mapped_column: str,
+ operator: FilterOperator,
+ values: list[str],
+) -> str:
+ """
+ The filter being previewed, written the way an owner would read it.
+
+ Display-only -- it is never executed -- but it is still read as SQL, so the
+ column is quoted and the values are rendered by the dialect rather than
+ concatenated raw. A column named ``order date`` would otherwise come out as
+ two bare words.
+ """
+ quoted = datasource.quote_identifier(mapped_column)
+ if operator == FilterOperator.IN:
+ rendered = ", ".join(
+ _render_literal(datasource.database, value) for value in values
+ )
+ return f"{quoted} IN ({rendered})"
+ return (
+ f"{quoted} {operator.value} {_render_literal(datasource.database, values[0])}"
+ )
+
+
+def _render_predicate(datasource: SqlaTable, predicate: ColumnElement[Any]) -> str:
+ """
+ Compile a mirrored predicate to the text a reader would see in View query.
+
+ Every value in it is a probed constant by this point, so ``literal_binds``
+ renders the same literals the chart query carries.
+ """
+ return _compile_literal(predicate, _dialect_for(datasource.database)).replace(
+ "\n", " "
+ )
+
+
+def _render_literal(database: Database, value: Any) -> str:
+ """
+ Render a value the way it appears in the generated SQL.
+
+ Compiled by the dialect rather than formatted by hand. `str()` would render
+ a NULL as the Python repr `None` and leave a date unquoted, neither of which
+ is SQL, and hand-rolled quote-doubling would only ever have been right for
+ strings.
+ """
+ return _compile_literal(sa.literal(value), _dialect_for(database))
+
+
+def _as_filter_text(value: date) -> str:
+ """``value`` as the text a simple filter on a temporal column carries."""
+ if isinstance(value, datetime):
+ return value.isoformat(
+ sep=" ", timespec="seconds" if not value.microsecond else "auto"
+ )
+ return value.isoformat()
+
+
+def _declined_for_reading_by_type(
+ evaluated: list[Any],
+ text_answers: list[tuple[int, Any]],
+ shape_errors: list[str] | None,
+) -> bool:
+ """
+ Whether a temporal value's text form answered differently from the value.
+
+ A chart hands a temporal value to the transform in two shapes. A time
+ range binds a `datetime`, which the dialect writes as a typed literal
+ (``TO_DATE(...)`` on Oracle); a simple filter binds the text the author
+ typed. A transform can read the two differently: Oracle's
+ ``TO_DATE(:value, fmt)`` parses the text, but turns the typed value back
+ into text through ``NLS_DATE_FORMAT`` first, so every time range asked for
+ a partition in year 0012 and came back empty -- or, under an ISO
+ ``NLS_DATE_FORMAT``, short by whatever the format drops. Nothing about the
+ typed answer alone looks wrong, so `evaluate_transform` asks the same
+ instant as text in the same round trip (``text_answers``), and a mapping
+ whose two answers differ cannot be right for both and is not mirrored.
+
+ The text goes straight to the evaluator rather than through the mirror
+ request path, whose gates decline some text before it reaches the engine
+ -- which is how the preview at a time of day said valid for exactly this
+ transform. Reported to ``shape_errors`` and the log when it declines.
+ """
+ disagreement = next(
+ (
+ (evaluated[index], text_answer)
+ for index, text_answer in text_answers
+ if text_answer is not None and text_answer != evaluated[index]
+ ),
+ None,
+ )
+ if disagreement is None:
+ return False
+ reason = str(
+ _(
+ "The transform gives a different partition value for a "
+ "timestamp (%(typed)s) than for the same instant written as "
+ "text (%(text)s). A time range and a filter typed as text both "
+ "reach it, so it cannot be right for both; filters on this "
+ "mapping will not be mirrored. Write the transform so it reads "
+ ":value the same way in either form.",
+ typed=disagreement[0],
+ text=disagreement[1],
+ )
+ )
+ logger.warning("Partition transform reads :value by type: %s", reason)
+ if shape_errors is not None:
+ shape_errors.append(reason)
+ return True
+
+
+def build_mirrored_predicates(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ requests: list[tuple[FilterOperator, Any]],
+ *,
+ errors: list[str] | None = None,
+ type_errors: list[str] | None = None,
+ escaping_errors: list[str] | None = None,
+ shape_errors: list[str] | None = None,
+) -> list[ColumnElement[Any]]:
+ """
+ Turn collected ``(operator, value)`` mirror requests into predicates.
+
+ ``requests`` is expected to be deduplicated by the caller. Every value is
+ resolved in a single probe round trip -- one per chart query at most -- then
+ emitted as a literal constant, so "View query" shows the reader an ordinary
+ ``WHERE`` clause rather than an inline expression.
+
+ A strict bound is emitted non-strictly; see `mirror_operator`. That happens
+ here, at the one point where a ``FilterOperator`` becomes SQL, rather than
+ at the collection sites in `ExploreMixin`: the preview endpoint calls this
+ directly, so this is what keeps the predicate the editor shows an owner and
+ the predicate the chart carries from disagreeing.
+
+ :param errors: optional sink; see `evaluate_transform`.
+ :param type_errors: optional sink for a probe result the partition column
+ cannot hold -- see `probed_value_type_error`. Separate from ``errors``
+ because the two say different things to an owner: that one is "the
+ database would not evaluate this", and this one is "it evaluated, and
+ answered with the wrong kind of thing".
+ :param escaping_errors: optional sink for a probe result the driver and the
+ engine would spell differently -- see `_predicates_from_probe`. Its own
+ sink for the same reason: "it evaluated, and answered with something
+ this database cannot be asked about" is a third problem, and the only
+ one of the three whose fix is to stop the transform producing the
+ character.
+ """
+ if not requests:
+ return []
+
+ partition_column = next(
+ (
+ column
+ for column in datasource.columns
+ if column.column_name == mapping.partition_column
+ ),
+ None,
+ )
+ if partition_column is None:
+ return []
+
+ # Flatten every value that needs probing into one list, remembering how many
+ # each request consumed so the results can be handed back out.
+ flat: list[Any] = []
+ spans: list[tuple[FilterOperator, int, int]] = []
+ for operator, value in requests:
+ values = list(value) if operator == FilterOperator.IN else [value]
+ spans.append((operator, len(flat), len(values)))
+ flat.extend(values)
+
+ text_answers: list[tuple[int, Any]] = []
+ evaluated = evaluate_transform(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ mapping.value_transform,
+ flat,
+ errors=errors,
+ text_answers=text_answers,
+ )
+ if evaluated is None:
+ return []
+
+ if not _bounds_are_ordered(evaluated, spans):
+ return []
+
+ if _declined_for_reading_by_type(evaluated, text_answers, shape_errors):
+ return []
+
+ # Declining here is the last chance to decline at all: once these
+ # predicates are in the statement, a value the partition column cannot
+ # hold fails the whole chart rather than its pruning.
+ if reason := probed_value_type_error(partition_column, evaluated):
+ logger.warning(
+ "Partition transform returned a value the partition column cannot "
+ "hold; queries will not prune: %s",
+ reason,
+ )
+ if type_errors is not None:
+ type_errors.append(reason)
+ # Deliberately *not* recorded as a mirror verdict. The transform
+ # evaluated perfectly; what failed is the comparison against this
+ # dataset's partition column -- and `_mirror_verdict_cache_key` is
+ # keyed on database, catalog, schema and transform, with no partition
+ # column in it. Recorded, this dataset-specific outcome answered for
+ # every other dataset sharing the transform: `CAST(:value AS text)`
+ # mirroring happily onto a text key in dataset A was reported
+ # `evaluable: false` -- and its pruning indicator hidden -- because
+ # someone previewed the same transform against a numeric key in
+ # dataset B. A probe cache hit on A never rewrites the verdict, so it
+ # stayed wrong until the entry expired.
+ return []
+
+ sqla_col = datasource.convert_tbl_column_to_sqla_col(partition_column)
+ predicates = _predicates_from_probe(
+ sqla_col,
+ partition_column,
+ evaluated,
+ spans,
+ escaping_errors=escaping_errors,
+ )
+ if not predicates:
+ return []
+
+ # A comparison against a NULL partition value is NULL, so a row parked in a
+ # NULL partition is dropped by the mirror even when the real filter matches
+ # it -- Hive and Impala's default partition, or a transform that returns
+ # NULL for an input it cannot convert. The mirror only has to be no
+ # narrower than the filter it stands in for, so admitting NULL partitions
+ # keeps those rows. Engines still prune; they read one extra partition.
+ return [sa.or_(sa.and_(*predicates), sqla_col.is_(None))]
+
+
+def _predicates_from_probe(
+ sqla_col: ColumnElement[Any],
+ partition_column: TableColumn,
+ evaluated: list[Any],
+ spans: list[tuple[FilterOperator, int, int]],
+ *,
+ escaping_errors: list[str] | None = None,
+) -> list[ColumnElement[Any]]:
+ """
+ One predicate on the partition column per surviving mirror request.
+
+ A request whose probe answered `None` for any of its values is skipped
+ rather than emitted: `col = NULL` is `NULL`, so it would drop every row the
+ filter keeps. A strict bound is emitted non-strictly; see `mirror_operator`.
+
+ A request whose probe answered with a value the driver and the engine spell
+ differently is skipped for the same reason -- see `literal_round_trips`.
+ `evaluate_transform` asks that question of the probe's *inputs*; the answers
+ are the other end of the same round trip, because the chart query is
+ compiled with ``literal_binds`` and every one of them is rendered into its
+ SQL as a literal too. A transform of ``concat(:value, chr(92), 'b')`` maps
+ the unremarkable input ``a`` to the partition key ``a\\b``, which Hive reads
+ back as ``a`` followed by a backspace: the mirror then asks for a partition
+ no row is in, and because it is ``AND``-ed onto the query the chart loses
+ every row the filter keeps rather than losing its pruning.
+
+ A request whose probe answered with a date or a timestamp is emitted with
+ the engine's own temporal literal -- see `_temporal_literal_sql` -- and
+ skipped where the engine has none, as for `None`.
+
+ :param escaping_errors: optional sink; see `build_mirrored_predicates`.
+ """
+ database = partition_column.table.database
+ # Once for the whole call, not once per value: `_dialect_for` asks the
+ # `Database` for a dialect, and a 200-member `IN` would otherwise ask 200
+ # times. The same reading `evaluate_transform` takes on the way in.
+ dialect = _dialect_for(database)
+
+ predicates: list[ColumnElement[Any]] = []
+ for operator, start, length in spans:
+ chunk = evaluated[start : start + length]
+ if any(value is None for value in chunk):
+ continue
+ if not all(
+ literal_round_trips(value, dialect, database.backend) for value in chunk
+ ):
+ # One member is the whole request's problem, as for `None` above:
+ # mirroring the rest of an `IN` list would be narrower than the
+ # filter. Dropping this request alone is not, which is why the
+ # decline is per request rather than per query -- a range arrives as
+ # two of them, and keeping only the bound that survives the trip is
+ # a mirror wider than the filter, which is all the mirror has to be.
+ logger.warning(
+ "The partition transform answered with a value the driver and "
+ "the database do not write down the same way, so this filter "
+ "is not mirrored; the query will not prune for it"
+ )
+ if escaping_errors is not None:
+ escaping_errors.append(
+ _(
+ "The transform answered with a value the driver and the "
+ "database do not agree on how to write into a query, so "
+ "the mirrored predicate would ask for a partition key no "
+ "row holds. A transform whose result carries neither a "
+ "quote nor a backslash still mirrors."
+ )
+ )
+ continue
+ if any(isinstance(value, date) for value in chunk):
+ rendered = [_temporal_clause(partition_column, value) for value in chunk]
+ if any(clause is None for clause in rendered):
+ # `probed_value_type_error` refuses these before this point;
+ # this is the backstop for a column type it could not resolve.
+ continue
+ chunk = rendered
+ if operator == FilterOperator.IN:
+ # The probe answers per value, so a transform over a mixed-number
+ # filter can answer with a mixed-number partition key -- and
+ # `in_` infers the bind type from the first element it is handed.
+ # Without this, probe results of `[33, 29.02]` emit
+ # `IN (33, 29)` and prune away the partition holding `29.02`.
+ predicates.append(sqla_col.in_(normalize_mixed_numbers(chunk)))
+ else:
+ predicates.append(
+ database.db_engine_spec.handle_comparison_filter(
+ sqla_col, mirror_operator(operator), chunk[0]
+ )
+ )
+ return predicates
+
+
+#: Operators whose value is the lower end of a range, and whose upper-end twins.
+#:
+#: Shared with `ExploreMixin._mirror_probe_input`, which rounds a bound *outward*
+#: where the engine resolves it more coarsely than the filter carries -- backward
+#: for a lower bound, forward for an upper one. Which end an operator names is
+#: the only thing separating the two directions in either caller, so the two have
+#: to agree on it rather than each classify for itself.
+LOWER_BOUND_OPERATORS = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+}
+UPPER_BOUND_OPERATORS = {
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+#: What Python type a probe result may have, per generic type of the partition
+#: column it is about to be compared against.
+#:
+#: Only the types a mismatch can actually break a query with are listed. An
+#: unresolvable column type is absent because there is nothing to check
+#: against. ``MULTI_VALUE`` is absent because no entry here could express it:
+#: an array partition key cannot hold *any* scalar, so it is refused for the
+#: column rather than for a value, in `probed_value_type_error`'s own branch
+#: ahead of this table. It was absent without that branch for a while, and
+#: absence here reads as "nothing to check" -- so an ``Array(Int32)`` key took
+#: a scalar mirror and failed the chart.
+#: ``numbers.Number`` rather than ``(int, float)``: Postgres answers
+#: ``extract(epoch from ...)`` with a `Decimal`, which is the single commonest
+#: transform this feature has, and an engine is free to answer with any number
+#: type its driver prefers. What the check is for is a *string* where a number
+#: belongs, and every numeric type is equally not that.
+_PROBE_RESULT_TYPES: dict[utils.GenericDataType, tuple[type, ...]] = {
+ utils.GenericDataType.NUMERIC: (numbers.Number,),
+ utils.GenericDataType.BOOLEAN: (bool,),
+ # A day key such as ``to_char(:value, 'YYYYMMDD')`` is legitimately text,
+ # so ``str`` is admitted -- but only for text *this* engine reads as an
+ # instant. `_reads_as_temporal` is the second half of this entry.
+ utils.GenericDataType.TEMPORAL: (datetime, date, str),
+ # Text, and not a number rendered as one. Not every engine accepts a number
+ # in a text comparison: Postgres refuses ``character varying = integer``,
+ # Trino ``varchar = bigint`` and BigQuery ``STRING = INT64``, all of which
+ # fail the whole chart once the predicate is in the statement. SQLite is
+ # worse -- it raises nothing and compares across storage classes as never
+ # equal, so the mirror drops every row rather than losing pruning, which is
+ # the one outcome this feature may not have. An owner whose partition key
+ # really is text writes the cast into the transform.
+ utils.GenericDataType.STRING: (str,),
+}
+
+
+def _reads_as_temporal(value: str, db_engine_spec: type[BaseEngineSpec]) -> bool:
+ """
+ Whether this engine would read this text as a date or timestamp.
+
+ `_PROBE_RESULT_TYPES` admits ``str`` for a temporal partition column
+ because a day key such as ``to_char(:value, 'YYYYMMDD')`` is legitimately
+ text -- but it admitted *every* string, so a transform that answers with
+ ordinary text passed the gate and failed the chart instead. On PostgreSQL a
+ ``VARCHAR`` mapped column under ``lower(:value)`` probes ``'US'`` to
+ ``'us'`` and emits ``p = 'us'`` against a ``DATE`` key, which the engine
+ refuses once the predicate is already in the statement -- so a chart that
+ worked before the mapping returns an error rather than losing its pruning.
+
+ Which text counts is the engine's answer, in full: there is no universal
+ form. Comparing a temporal column against a text value is an implicit
+ coercion, and an engine is free not to have one -- Trino has no
+ VARCHAR-to-DATE comparison at all and BigQuery coerces only a canonical
+ ``YYYY-MM-DD`` *literal*, so even plain ISO text fails the whole chart on
+ those rather than merely losing its pruning. An earlier cut of this gate
+ admitted extended ISO everywhere and only asked the spec about the
+ unseparated forms; that is the hole. So every accepted form is declared in
+ `BaseEngineSpec.temporal_literal_formats`, which is empty by default --
+ an engine Superset has not confirmed declines, and declining costs only
+ the pruning.
+
+ Answered by parsing, not by asking the engine: the check runs on the
+ chart-query path, where a second round trip is the cost this module spends
+ its effort avoiding. Parsing is also the conservative direction -- anything
+ unrecognised declines.
+ """
+ for fmt in db_engine_spec.temporal_literal_formats:
+ try:
+ # Round-tripped, because `strptime` accepts unpadded fields: a bare
+ # epoch such as ``1767225600`` otherwise parses as
+ # ``%Y%m%d%H%M%S`` -- 1767-02-25 06:00 -- and is emitted as
+ # ``part_date = '1767225600'``, which is the bad-literal error this
+ # whole gate exists to stop. Re-rendering and comparing is what
+ # makes "parses" mean "is in this format" rather than "the parser
+ # found something in it".
+ if datetime.strptime(value, fmt).strftime(fmt) == value:
+ return True
+ except ValueError:
+ continue
+ return False
+
+
+#: The leading type name of a declared column type: ``DATE`` from ``DATE``,
+#: ``TIMESTAMP`` from ``TIMESTAMP(6) WITH TIME ZONE``.
+_TYPE_NAME_RE = re.compile(r"^\s*([A-Za-z_][A-Za-z0-9_]*)")
+
+
+def _holds_days_only(partition_column: TableColumn) -> bool:
+ """
+ Whether the column's values carry no time of day.
+
+ The engine spec's mapping is not the answer on its own: Superset maps
+ Oracle's ``DATE`` to `sa.Date`, but an Oracle ``DATE`` stores the time of
+ day, and its own SQLAlchemy dialect says so by making ``DATE`` a
+ `DateTime`. Exempting it from the precision check let
+ ``TO_DATE('2026-01-12', 'YYYY-MM-DD')`` stand in for 06:30, so a mirrored
+ range on a ``CAST(:value AS DATE)`` key asked for midnight and the chart
+ lost every row after it. So the database's own dialect has the last word
+ where it names the type.
+ """
+ spec_type = partition_column.db_engine_spec.get_sqla_column_type(
+ partition_column.type or ""
+ )
+ if not isinstance(spec_type, sa.Date):
+ return False
+ try:
+ match = _TYPE_NAME_RE.match(partition_column.type or "")
+ dialect = _dialect_for(partition_column.table.database)
+ names = getattr(dialect, "ischema_names", None)
+ # A `Mapping` only. `ischema_names` is not part of SQLAlchemy's dialect
+ # contract, and third-party dialects shape it as they like --
+ # clickhouse-connect 1.10/1.11 make it a list, and calling `.get` on that
+ # raised out of the chart query, so every chart filtering the mapped
+ # column failed rather than losing its pruning.
+ if match and isinstance(names, Mapping):
+ name = match.group(1)
+ dialect_type = (
+ names.get(name) or names.get(name.upper()) or names.get(name.lower())
+ )
+ if isinstance(dialect_type, type) and issubclass(dialect_type, sa.DateTime):
+ return False
+ except Exception: # pylint: disable=broad-except
+ # Not knowing is answered as "may hold a time of day": the precision
+ # check then runs, and at worst declines a mirror it could have kept.
+ logger.warning("Could not read the partition column's type", exc_info=True)
+ return False
+ return True
+
+
+def _temporal_literal_sql(partition_column: TableColumn, value: date) -> str | None:
+ """
+ A probed date or timestamp as the engine's own literal for the column.
+
+ The probe answers a temporal transform with a `date` or a `datetime`, and
+ SQLAlchemy's literal processor writes either one as plain quoted text --
+ ``part_date >= '2026-01-01'`` -- whatever the dialect. Trino and Presto
+ have no implicit coercion from ``varchar`` to ``date`` or ``timestamp``, so
+ they refuse that comparison outright, and because the mirror is ``AND``-ed
+ onto the chart query the whole chart fails rather than its pruning.
+
+ `BaseEngineSpec.convert_dttm` is how every other temporal bound in a chart
+ query is written (see `ExploreMixin.dttm_sql_literal`), so the mirror
+ writes its values the same way: ``DATE '2026-01-01'`` on Trino,
+ ``CAST('2026-01-01' AS DATE)`` on Hive.
+
+ `None` where that cannot be done faithfully, and the caller declines:
+
+ * The engine has no literal for the column's type. An engine Superset has
+ no rendering for is one it has not confirmed, the same answer
+ `_reads_as_temporal` gives for text.
+ * The literal throws part of the value away -- SQLite's, for one, stops at
+ the second. A bound floored past what the probe answered is a mirror
+ narrower than the filter, which drops rows. Detected the way
+ `ExploreMixin._engine_literal_resolution` detects it, by rendering a
+ second instant and comparing the text: a value one microsecond earlier
+ writes differently from this one exactly when nothing of it is lost.
+ A column holding only days is exempt, because flooring to the day is
+ the column's own resolution and every comparison against it reads the
+ same either way -- see `_holds_days_only` for what "only days" means.
+ """
+ instant = (
+ value if isinstance(value, datetime) else datetime.combine(value, time.min)
+ )
+ spec = partition_column.db_engine_spec
+ column_type = partition_column.type or ""
+ db_extra = partition_column.db_extra
+ rendered = spec.convert_dttm(column_type, instant, db_extra=db_extra)
+ if rendered is None:
+ return None
+ holds_days_only = _holds_days_only(partition_column)
+ if not holds_days_only and rendered == spec.convert_dttm(
+ column_type, instant - timedelta(microseconds=1), db_extra=db_extra
+ ):
+ return None
+ return rendered
+
+
+def _temporal_clause(partition_column: TableColumn, value: Any) -> Any:
+ """`_temporal_literal_sql` as a clause, or `None` where it declines."""
+ if not isinstance(value, date):
+ return value
+ if (rendered := _temporal_literal_sql(partition_column, value)) is None:
+ return None
+ # Not `get_text_clause`: a `TextClause` is not a column expression, so
+ # `in_` refuses it, and the literal has no bind parameter to parse.
+ return sa.literal_column(rendered)
+
+
+def probed_value_type_error(
+ partition_column: "TableColumn",
+ values: Sequence[Any],
+) -> str | None:
+ """
+ Why these probe results cannot be compared against the partition column.
+
+ A transform can evaluate perfectly and still answer with something the
+ partition column cannot hold: ``cast(:value as text) || 'x'`` against a
+ ``BIGINT`` partition key probes fine, passes the ordering check -- two
+ strings compare -- and then reaches `handle_comparison_filter`, which is
+ just ``col >= value``. SQLAlchemy takes the bind's type from the *value*
+ rather than from the column, so the engine is the first thing to object,
+ and it objects by failing the whole chart: by that point the predicate is
+ in the statement and there is nothing left to fail open.
+
+ So the mismatch is caught here, where declining still costs only the
+ pruning, and reported to the preview, where the owner can see it before
+ they save. Nothing else in this module looks at the partition column's own
+ type: every other gate is about the mapped column.
+
+ Fails open wherever it has no information -- an unresolvable column type,
+ a generic type with nothing a mismatch can break -- and closed only on a
+ clear mismatch. ``bool`` is excluded from ``NUMERIC`` on purpose: it
+ satisfies `isinstance(x, int)` -- and `numbers.Number` -- while rendering
+ as ``true``, which is not a number to any engine that cares.
+
+ The type asked for is the one the engine spec reads out of the column's
+ *native* type, not `TableColumn.type_generic`, which answers ``TEMPORAL``
+ for anything carrying ``is_dttm`` whatever the column physically stores.
+ What this gate is about is the comparison the engine will perform, and a
+ ``BIGINT`` partition key flagged temporal through ``python_date_format =
+ epoch_s`` compares as a number: asking the semantic flag refused the
+ integer such a transform correctly returns, and cost a working mapping its
+ mirror. Same source as `ExploreMixin._in_column_number_type` uses for the
+ same reason, with the flag kept as the fallback for a type the spec cannot
+ resolve.
+ """
+ generic_type = _native_generic_type(partition_column)
+
+ if generic_type == utils.GenericDataType.MULTI_VALUE or declares_array_type(
+ partition_column.type
+ ):
+ # Refused for the column rather than per value: an array holds no
+ # scalar, so there is no result a transform could return that would
+ # compare. `handle_comparison_filter` emits a bare ``col = value``, so
+ # an ``Array(Int32)`` partition key mirrors as ``region_keys = 5`` and
+ # a PostgreSQL ``text[]`` one as ``region_keys = 'us'`` -- neither of
+ # which is an operator the engine has, so the predicate fails the whole
+ # chart once it is in the statement.
+ #
+ # Knowable from the schema alone, unlike every other branch here, which
+ # needs a probe result to compare. It is still answered from this gate
+ # so the preview reports it the same way, and so the decline costs only
+ # the pruning.
+ return str(
+ _(
+ "%(column)s is an array column, which cannot be compared "
+ "against the single value a transform returns. Mirrored "
+ "filters on this mapping would fail at the database. Map a "
+ "scalar partition column instead.",
+ column=partition_column.column_name,
+ )
+ )
+
+ if generic_type is None:
+ return None
+
+ allowed = _PROBE_RESULT_TYPES.get(generic_type)
+ if allowed is None:
+ return None
+
+ for value in values:
+ if value is None:
+ # Handled by the caller's own NULL guard, which skips the request.
+ continue
+ # `bool` is checked separately because it satisfies every numeric
+ # `isinstance` there is while rendering as `true`.
+ held = isinstance(value, allowed) and (
Review Comment:
A probe result of `inf` or `nan` passes this type check, so a transform such as `CASE WHEN :value = 0 THEN CAST('Infinity' AS DOUBLE PRECISION) ELSE :value END` on a PostgreSQL double partition column returns `inf` for `n = 0`. The mirrored predicate is then rendered as `p = inf`, which the database rejects (`column "inf" does not exist`), while preview still reports the mapping as valid, so the chart fails instead of just losing pruning. Should a non-finite float be treated as not held here so the mirror declines?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "eschutho (via GitHub)" <gi...@apache.org>.
eschutho commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4253803176
##########
superset/config.py:
##########
@@ -2553,6 +2585,24 @@ def engine_context_manager( # pylint: disable=unused-argument
"getMacro",
"getSetting",
},
+ # Oracle functions that run a query handed to them as text. Same blind spot
+ # as PostgreSQL's XML and full-text families above: the statement they
+ # execute is a string, so the expression has no FROM clause and no
+ # sub-query of its own for a table-reference gate to see, and the rows come
+ # back without the dataset grants or row-level security the caller is
+ # subject to.
+ #
+ # Named bare rather than package-qualified: `DBMS_XMLGEN.GETXML(...)`
+ # parses as an anonymous function called `GETXML`, so the package prefix
+ # never reaches the matcher. `getclobval` and `extract` are deliberately
+ # absent -- they read an XMLType the caller already has rather than
+ # building one from a query.
+ "oracle": {
+ "getxml",
+ "getxmltype",
+ "newcontext",
+ "newcontextfromhierarchy",
Review Comment:
Replying on Hugh's behalf: Hugh fixed this in 571fc58493 (`fix(security): deny the Oracle function that reads a table by path string`). `dburitype` is now in the `oracle` set of `DISALLOWED_SQL_FUNCTIONS`, as you suggested, with a comment explaining why. I checked it at the current head: `stored_expression_error` rejects `DBURITYPE('/HR/EMPLOYEES/ROW[ID=1]/SALARY').getclob() || :value` (in either case) with "A partition value transform cannot call dburitype." and still accepts `lower(:value)`.
##########
superset/db_engine_specs/postgres.py:
##########
@@ -178,6 +178,15 @@ class PostgresBaseEngineSpec(BaseEngineSpec):
engine = ""
engine_name = "PostgreSQL"
+ # The engine's default text comparison is binary, so a mirrored
+ # ``partition_col = T(v)`` agrees with the ``col = v`` it stands in for.
+ binary_string_comparison = True
+
+ # PostgreSQL's date/time input reads the unseparated forms as well as the
+ # ISO ones -- ``'20260115'::date`` is 2026-01-15 -- so a ``YYYYMMDD``
+ # bucketing key mirrors here. Redshift inherits the same input parsing.
+ temporal_literal_formats = ("%Y%m%d", "%Y%m%d%H%M%S")
Review Comment:
Replying on Hugh's behalf: Hugh fixed this in 15cc6a83fd (`fix(datasets): let the engine say which text it reads as an instant`). `temporal_literal_formats = POSTGRES_TEMPORAL_LITERAL_FORMATS` is now declared on `PostgresEngineSpec` and `RedshiftEngineSpec` instead of the shared `PostgresBaseEngineSpec`. Snowflake, Vertica, HANA, Netezza and Hologres therefore fall back to the base `()` and decline the mirror rather than emitting `part_date = '20260115'`. I checked the resolved values at the current head. `test_a_postgres_relative_does_not_inherit_the_day_key` covers it.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4274813821
##########
superset/views/datasource/views.py:
##########
@@ -293,6 +425,74 @@ def save(self) -> FlaskResponse:
),
status=409,
)
+ # The mapping's one-transform invariant, against the columns this
+ # request is about to write. `update_from_object` sets every field in
+ # `update_from_object_fields` straight onto the column, so nothing
+ # between here and storage would notice a transform parked on a column
+ # the mapping does not mirror -- invisible in the editor, since no row
+ # but the mapped one renders a transform, and live the moment the mapped
+ # column resolves back to it. `DatasetDAO.update` runs a model-level
+ # pass for this; this endpoint bypasses that along with the rest of
+ # `UpdateDatasetCommand`.
+ #
+ # Corrected rather than refused, unlike the gates below. Those are about
+ # a value that may not be stored anywhere; this is about a value in the
+ # wrong place, and the payload a GET-then-POST client sends back carries
+ # whatever a previous writer left there -- so a 422 would punish the
+ # client that is merely echoing the state it was given.
+ #
+ # Which is also why it runs *first*. A parked transform that is not a
+ # storable expression would otherwise fail the gate below and 422 every
+ # save, leaving the dataset uneditable over a value nobody asked to
+ # keep; dropped here, there is nothing left for that gate to refuse.
+ # What it still guards is the transform this request actually stores,
+ # the one on the mapped column.
+ #
+ # Read from the payload alone, with no fallback to the model: every
+ # field here rides in on `update_from_object`, which writes
+ # `obj.get(attr)` for each one, so what this request says *is* what the
+ # mapping will be.
+ if cleared := drop_unmapped_value_transforms(
+ datasource_dict.get("columns"),
+ partition_column=datasource_dict.get("partition_column"),
+ partition_mapped_column=datasource_dict.get("partition_mapped_column"),
+ main_dttm_col=datasource_dict.get("main_dttm_col"),
+ # So an unchanged echo of stored configuration survives: this
+ # endpoint's own client does GET-then-POST, which is exactly the
+ # shape that looked like a value being parked.
+ stored_by_name=None
+ if is_feature_enabled("PARTITION_FILTER_MAPPING")
+ else {
Review Comment:
Nit: This now holds only with the flag off; with it on, the echo is dropped on purpose.
```suggestion
# With the flag off, an unchanged echo of stored configuration
# survives: this endpoint's own client does GET-then-POST. With it
# on nothing is exempt, since no model-level pass runs here to clear
# a transform the mapping no longer mirrors.
stored_by_name=None
if is_feature_enabled("PARTITION_FILTER_MAPPING")
else {
```
##########
superset/views/datasource/views.py:
##########
@@ -293,6 +425,74 @@ def save(self) -> FlaskResponse:
),
status=409,
)
+ # The mapping's one-transform invariant, against the columns this
+ # request is about to write. `update_from_object` sets every field in
+ # `update_from_object_fields` straight onto the column, so nothing
+ # between here and storage would notice a transform parked on a column
+ # the mapping does not mirror -- invisible in the editor, since no row
+ # but the mapped one renders a transform, and live the moment the mapped
+ # column resolves back to it. `DatasetDAO.update` runs a model-level
+ # pass for this; this endpoint bypasses that along with the rest of
+ # `UpdateDatasetCommand`.
+ #
+ # Corrected rather than refused, unlike the gates below. Those are about
+ # a value that may not be stored anywhere; this is about a value in the
+ # wrong place, and the payload a GET-then-POST client sends back carries
+ # whatever a previous writer left there -- so a 422 would punish the
+ # client that is merely echoing the state it was given.
+ #
+ # Which is also why it runs *first*. A parked transform that is not a
+ # storable expression would otherwise fail the gate below and 422 every
+ # save, leaving the dataset uneditable over a value nobody asked to
+ # keep; dropped here, there is nothing left for that gate to refuse.
+ # What it still guards is the transform this request actually stores,
+ # the one on the mapped column.
+ #
+ # Read from the payload alone, with no fallback to the model: every
+ # field here rides in on `update_from_object`, which writes
+ # `obj.get(attr)` for each one, so what this request says *is* what the
+ # mapping will be.
+ if cleared := drop_unmapped_value_transforms(
+ datasource_dict.get("columns"),
+ partition_column=datasource_dict.get("partition_column"),
+ partition_mapped_column=datasource_dict.get("partition_mapped_column"),
+ main_dttm_col=datasource_dict.get("main_dttm_col"),
+ # So an unchanged echo of stored configuration survives: this
+ # endpoint's own client does GET-then-POST, which is exactly the
+ # shape that looked like a value being parked.
+ stored_by_name=None
Review Comment:
No test pins this: reverted to the stored-columns dict, `views_test.py` stays green, since `_save_with_parked_transform` never stores `other_time`. A case storing `other_time` with the echoed transform fails on that revert with the flag on.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(explore): indicate when a filter is mirrored onto a partition column [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4129803967
##########
superset/daos/dataset.py:
##########
@@ -461,7 +464,12 @@ def update(
if force_update:
attributes["changed_on"] = datetime.now()
- return super().update(item, attributes)
+ updated = super().update(item, attributes)
+ # After the dataset-level attributes land, not before: the mapped column
+ # is `partition_mapped_column or main_dttm_col`, and either can be part
+ # of this very request.
+ cls.clear_unmapped_partition_transforms(updated)
Review Comment:
This runs on every `DatasetDAO.update()` call, including one that only changes an unrelated field like `description` -- there's no check that `attributes` actually touches partition/mapping state. Any dataset that already has a `partition_value_transform` stored on a column other than the current mapped one (a state the client editor alone couldn't fully prevent before this PR) will have that value silently and permanently cleared the next time anything about the dataset is saved, including a plain metadata edit or a client that GETs the dataset and PUTs it back unchanged. Could this run only when the request actually touches columns or the mapping fields, rather than on every save?
##########
superset/daos/dataset.py:
##########
@@ -475,6 +483,48 @@ def _validate_column_date_formats(
"python_date_format is an invalid date/timestamp format."
)
+ @staticmethod
+ def clear_unmapped_partition_transforms(model: SqlaTable) -> None:
+ """
+ Drop the value transform from every column the mapping does not mirror.
+
+ A mapping has exactly one mirrored column, so at most one column may
+ carry a transform. A transform parked on any other column is invisible
+ -- no row but the mapped one renders one -- yet it is still stored, and
+ it goes live the moment the mapped column resolves back to it. Clearing
+ an override is enough to do that: a null `partition_mapped_column` means
+ "follow `main_dttm_col`", so dropping a mapping would otherwise activate
+ whatever the default datetime column happened to be holding, turning a
+ request to remove a mapping into a request to add a different one.
+
+ Enforced here rather than in the editor alone because the editor is only
+ one writer: a PUT, an `override_columns=true` metadata sync and an
+ import all reach the columns directly. The same argument
+ `clear_dangling_partition_mapping` makes about dangling columns.
+
+ Gated on the feature flag, unlike its sibling, because this discards
+ stored configuration rather than repairing a broken reference. With the
+ flag off nothing mirrors, so there is no armed mapping to disarm and
+ clearing would be pure loss.
+ """
+ if not feature_flag_manager.is_feature_enabled(PARTITION_FILTER_MAPPING_FLAG):
+ return
+
+ mapped_column = (
+ (model.partition_mapped_column or model.main_dttm_col)
+ if model.partition_column
+ else None
+ )
+ for column in model.columns:
Review Comment:
`model.columns` here is whatever was already materialized earlier in this same `update()` call by `_upsert_columns`/`_override_columns`, which insert new rows via `db.session.add(TableColumn(..., table_id=model.id))` rather than appending to that relationship collection -- so a column added and given `partition_value_transform` in the same request as this call is invisible to this loop, and its transform is never cleared. Since that's exactly the "stray transform reactivates later" scenario this method exists to prevent, could this include newly-inserted columns before clearing?
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/types.ts:
##########
@@ -55,3 +55,22 @@ export interface PartitionMappingPreview {
* mapping rather than a source for one.
*/
export type PartitionRowState = 'mapped' | 'unmapped' | 'partition' | 'none';
+
+/**
+ * One problem with the mapping that stops the save.
+ *
+ * The client half of `MappingValidationIssue` in
+ * `superset/connectors/sqla/partition_mapping.py`, without its `blocking` flag:
+ * the backend reports two tiers because a half-written transform is allowed to
+ * save and sit inactive, and only the blocking tier is worth stopping the owner
+ * in the editor for. Everything this carries blocks, so the flag has nothing to
+ * distinguish. `field` names the input at fault, so the message can be shown
+ * there rather than only in the Save button's tooltip.
+ */
+export interface PartitionMappingIssue {
Review Comment:
`field` is asserted in the tests but neither production consumer reads it -- `DatasourceEditor`'s validation maps straight to `.message`, and `PartitionMappingSection` renders `.message` without checking `.field`. Could this wire `field` into error placement at the named input, or drop it so it isn't carrying metadata nothing uses?
##########
superset-frontend/packages/superset-ui-chart-controls/src/shared-controls/sharedControls.tsx:
##########
@@ -208,9 +208,68 @@ const time_grain_sqla: SharedControlConfig<'SelectControl'> = {
sortComparator: () => 0, // Disable frontend sorting to preserve backend order
};
+/**
+ * The mapping to hand the time control's partition-pruning indicator, or `null`
+ * when this time range is not mirrored.
+ *
+ * The control renders whatever mapping it is given, so the applicability check
+ * belongs here, where the selected temporal column and the range are both in
+ * scope. Unlike an ad-hoc filter chip the control names no column of its own:
+ * the query path mirrors the time range only when the *chart's* temporal column
+ * is the mapped one (`superset/models/helpers.py`, the `granularity` and
+ * `always_filter_main_dttm` branches), and only when the range resolves to at
+ * least one bound -- `No filter` resolves to neither.
+ */
+function timeRangePartitionMapping({
+ datasource,
+ form_data: formData,
+}: ControlPanelState) {
+ const dataset = datasource as Dataset | null;
+ const mapping = dataset?.partition_filter_mapping;
+ if (
+ !mapping?.active ||
+ !mapping.mirrorable_operators?.includes('TEMPORAL_RANGE')
+ ) {
+ return null;
+ }
+ if (formData?.time_range === NO_TIME_RANGE) {
+ return null;
+ }
+ const granularity = formData?.granularity_sqla;
+ const selectedColumn = isDefined(granularity)
+ ? getColumnLabel(granularity)
+ : undefined;
+ const mirrorsSelectedColumn = selectedColumn === mapping.mapped_column;
+ // `always_filter_main_dttm` adds a second time filter on the main datetime
+ // column even when the chart groups by another one, and that filter mirrors.
+ const mirrorsMainDttm = Boolean(
Review Comment:
`mirrorsMainDttm` doesn't check that a temporal column is even selected. The backend only collects this `always_filter_main_dttm` mirror inside the `if granularity:` branch (`models/helpers.py`), so with no granularity selected the query never adds it -- but here the glyph shows purely from `always_filter_main_dttm && main_dttm_col === mapping.mapped_column`, regardless of `formData.granularity_sqla`. Could this also require a selected granularity before mirroring the time range through this branch?
##########
superset-frontend/src/explore/components/PartitionPruningIndicator/index.tsx:
##########
@@ -0,0 +1,169 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { t } from '@apache-superset/core/translation';
+import { css, useTheme } from '@apache-superset/core/theme';
+import { NO_TIME_RANGE } from '@superset-ui/core';
+import { Icons, Tooltip } from '@superset-ui/core/components';
+import type { PartitionFilterMapping } from '@superset-ui/chart-controls';
+import { ExpressionTypes } from 'src/explore/components/controls/FilterControl/types';
+
+interface PartitionPruningIndicatorProps {
+ /** The dataset's mapping summary, straight off the datasource payload. */
+ mapping?: PartitionFilterMapping | null;
+}
+
+/**
+ * The parts of an ad-hoc filter that decide whether it is mirrored. Structural
+ * rather than the `AdhocFilter` class so native filters and cross-filters --
+ * which reach the query path in the same shape but are not that class -- can be
+ * checked with the same function.
+ */
+export interface MirrorCandidateFilter {
+ expressionType?: string;
+ subject?: string | { column_name?: string } | null;
+ operator?: string | null;
+ comparator?: unknown;
+}
+
+/**
+ * The glyph on a filter whose column is mirrored onto a partition column
+ * (wireframe 1d).
+ *
+ * Chart authors do not configure any of this and ideally never learn the word
+ * "partition"; the indicator exists only to explain why their query got faster,
+ * and to point at the generated SQL where the extra predicate is visible.
+ */
+export default function PartitionPruningIndicator({
+ mapping,
+}: PartitionPruningIndicatorProps) {
+ const theme = useTheme();
+
+ if (!mapping?.active) {
+ return null;
+ }
+
+ return (
+ <Tooltip
+ placement="top"
+ title={t(
+ 'This filter is also applied to a partition column for faster queries. See "View query" for the generated SQL.',
+ )}
+ >
+ <span data-test="partition-pruning-indicator">
+ <Icons.FilterOutlined
+ iconSize="s"
+ iconColor={theme.colorSuccess}
+ css={css`
+ margin-left: ${theme.sizeUnit}px;
+ vertical-align: middle;
+ `}
+ />
+ </span>
+ </Tooltip>
+ );
+}
+
+/**
+ * The filter's column name. `subject` is a bare string for simple filters and a
+ * column object when the filter was built from a dropped column.
+ */
+function subjectName(
+ subject: MirrorCandidateFilter['subject'],
+): string | undefined {
+ return typeof subject === 'string'
+ ? subject
+ : (subject?.column_name ?? undefined);
+}
+
+/**
+ * Whether `columnName` is the one column the mapping mirrors.
+ *
+ * Necessary but not sufficient for the glyph -- see `isMirroredFilter`.
+ */
+export function isMirroredColumn(
+ mapping: PartitionFilterMapping | null | undefined,
+ columnName: string | null | undefined,
+): boolean {
+ return Boolean(
+ mapping?.active && columnName && mapping.mapped_column === columnName,
+ );
+}
+
+/**
+ * Whether the comparator is one the mirrored predicate can be built from.
+ *
+ * A `NULL` inside an `IN` list widens the real predicate to
+ * `col IS NULL OR col IN (...)`, which the mirror cannot express, so the
+ * backend skips those lists outright.
+ */
+function hasMirrorableValue(operator: string, comparator: unknown): boolean {
+ if (operator === 'TEMPORAL_RANGE') {
+ // `No filter` resolves to neither bound, so no range is mirrored.
+ return typeof comparator === 'string' && comparator !== NO_TIME_RANGE;
+ }
+ if (operator === 'IN') {
+ return (
+ Array.isArray(comparator) &&
+ comparator.length > 0 &&
+ !comparator.some(value => value == null)
+ );
+ }
+ return comparator !== null && comparator !== undefined && comparator !== '';
+}
+
+/**
+ * Whether this filter actually produces a predicate on the partition column.
+ *
+ * Naming the mapped column is only the first of the query path's gates
+ * (`_collect_partition_mirror_filter` in `superset/models/helpers.py`): the
+ * operator has to be one the mapping can mirror, and the value has to be one
+ * the mirrored predicate can carry. A `country != 'US'` chip names the mapped
+ * column and mirrors nothing -- negations are never safe, because the transform
+ * need not be injective -- so labelling it would promise a speed-up the query
+ * does not deliver.
+ *
+ * The operator list is not restated here; it is computed server-side from the
+ * transform's declared monotonicity and shipped on the mapping.
+ */
+export function isMirroredFilter(
+ mapping: PartitionFilterMapping | null | undefined,
+ filter: MirrorCandidateFilter | null | undefined,
+): boolean {
+ if (!mapping?.active || !filter) {
+ return false;
+ }
+ // Free-form SQL filters are appended verbatim as `extras.where`; the backend
+ // never sees an (operator, value) pair to mirror.
+ if (
+ filter.expressionType &&
+ filter.expressionType !== ExpressionTypes.Simple
+ ) {
+ return false;
+ }
+ if (!isMirroredColumn(mapping, subjectName(filter.subject))) {
+ return false;
+ }
+ if (
+ !filter.operator ||
+ !mapping.mirrorable_operators?.includes(filter.operator)
+ ) {
+ return false;
+ }
+ return hasMirrorableValue(filter.operator, filter.comparator);
Review Comment:
This can show the pruning glyph on a filter the query path does not actually mirror. Two concrete cases: (1) a filter with an applied time grain (drill-to-detail) is explicitly excluded from mirroring in `models/helpers.py` ("Mirroring it raw would keep only the bucket's first instant"), but `MirrorCandidateFilter` carries no grain information, so a grained equality filter is always treated as mirrored here; (2) an `IN` filter containing the `<NULL>` sentinel (`superset/constants.py`'s `NULL_STRING`) is converted to a real `None` server-side and excluded from mirroring there, but `hasMirrorableValue`'s `value == null` check doesn't recognize the string sentinel, so the glyph appears while no partition predicate is emitted for that filter. Could the applicability check account for both?
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/useDebouncedCommit.ts:
##########
@@ -0,0 +1,85 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { debounce } from 'lodash-es';
+import { Constants } from '@superset-ui/core/components';
+
+/**
+ * Local text state that commits upward on a debounce.
+ *
+ * The dataset editor's commit path is asynchronous and snapshot-based: a value
+ * handed to `onChange` travels Field -> Fieldset -> CollectionTable ->
+ * DatasourceEditor -> DatasourceModal and arrives back on the `value` prop
+ * several renders later, and the callback that commits it was built during an
+ * earlier render. An input driven straight off that prop therefore loses any
+ * keystroke that lands while a commit is in flight -- which is why every other
+ * control in the editor types into local state and commits on a debounce, and
+ * why Fieldset's own comment says the editor assumes exactly that. This is
+ * TextControl's contract (src/explore/components/controls/TextControl), minus
+ * the ControlHeader and the number parsing this field does not want.
+ */
+export function useDebouncedCommit(
+ value: string | null | undefined,
+ commit: (next: string) => void,
+ delay: number = Constants.FAST_DEBOUNCE,
+) {
+ const [localValue, setLocalValue] = useState(value ?? '');
+ const [prevValue, setPrevValue] = useState(value);
+
+ // The commit fires from a timer, so the callback is handed in at call time
+ // rather than captured when the debounce was built -- otherwise it would
+ // close over whichever render happened to create it, and the commit reads
+ // props (the column's monotonic flag) to decide what to write.
+ const debouncedCommit = useRef(
+ debounce(
+ (next: string, commitFn: (value: string) => void) => commitFn(next),
+ delay,
+ ),
+ );
+
+ useEffect(() => () => debouncedCommit.current.cancel(), []);
+
+ const onChange = useCallback(
+ (next: string) => {
+ setLocalValue(next);
+ debouncedCommit.current(next, commit);
+ },
+ [commit],
+ );
+
+ /**
+ * Commit a pending edit now. lodash's `flush` is a no-op when nothing is
+ * pending, so a blur with no edit behind it costs nothing.
+ */
+ const flush = useCallback(() => {
+ debouncedCommit.current.flush();
+ }, []);
+
+ // Re-seed from the prop only when the prop itself changed. Adjusting state
+ // during render is React's documented pattern for this; deriving a display
+ // value without writing it back leaves `localValue` holding superseded text,
+ // so the next render that changes only an unrelated prop -- and so does not
+ // re-enter this branch -- puts the stale value back in the input.
+ if (prevValue !== value) {
Review Comment:
This can't tell an echo of its own last commit from a genuinely new external value, so it can still drop a keystroke: if `commit` fires and the resulting prop update (say "AB") arrives after the owner has already typed further ("ABC"), this resets `localValue` back to "AB", discarding the extra keystroke -- the next character then commits on top of the reverted text. The new round-trip test only re-syncs after typing has already finished, so this specific race (a commit firing while typing is still in progress) isn't covered. Could this skip the resync when the incoming `value` matches what was just committed?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "hughhhh (via GitHub)" <gi...@apache.org>.
hughhhh commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4319669911
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,1913 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate. Named so it cannot
+#: plausibly collide with a real column; a collision only makes the count
+#: disagree, which fails closed.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ return VALUE_PLACEHOLDER_RE.sub(standin, transform)
Review Comment:
Fixed. The rendered SQL is substituted literally rather than used as a regex replacement string, so escaped backslashes in an array literal survive into the probe.
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,1314 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` always -- ``T`` is a function
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import re
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLStatement
+from superset.utils import json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: Every entry point enforces it -- the typed column field, the import schema
+#: and the preview request -- because `is_transform_active` parses the stored
+#: value on each Explore load, and an unbounded string would make that parse
+#: the expensive part of rendering a chart.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+def mirrorable_operators(is_monotonic: bool) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ """
+ if is_monotonic:
+ return MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+ return set(MIRRORABLE_ALWAYS)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(self.is_monotonic)
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+ """
+ return VALUE_PLACEHOLDER_RE.sub(_PARSE_STANDIN, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(transform: str, engine: str) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def stored_expression_error(
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ The same subquery, function-denylist and RLS policy every other stored
+ expression goes through, applied to a value transform. It matters more
+ here than the name suggests: `build_probe_sql` binds only `:value` and
+ splices the rest of the transform in as SQL text, which the engine then
+ executes, so an ungated transform is arbitrary SQL. A dataset editor
+ without SQL Lab could store `(SELECT secret FROM protected_table LIMIT 1)
+ || :value` and read the answer back out of the emitted predicate.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+ """
+ selections = []
+ for index, value in enumerate(values):
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ compiled = clause.compile(
+ dialect=dialect,
+ compile_kwargs={"literal_binds": True},
Review Comment:
Fixed. `_compile_literal` compiles with inline literals and then undoes the paramstyle's percent doubling, guarded on the identifier preparer's `_double_percents` — the same normalization `Database.compile_sqla_query` applies, and for the same reason: the probe executes with no bound parameters, so nothing would undo it later.
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2264 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate. Named so it cannot
+#: plausibly collide with a real column; a collision only makes the count
+#: disagree, which fails closed.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+ """
+ if not transform:
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
Review Comment:
Fixed. A transform naming the stand-in is refused outright: `if _PLACEHOLDER_STANDIN in transform.lower(): return False`, case-insensitively, ahead of the count check. The compiled probe is also re-read by `probe_sql_is_evaluable`.
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,1314 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` always -- ``T`` is a function
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import re
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLStatement
+from superset.utils import json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: Every entry point enforces it -- the typed column field, the import schema
+#: and the preview request -- because `is_transform_active` parses the stored
+#: value on each Explore load, and an unbounded string would make that parse
+#: the expensive part of rendering a chart.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+def mirrorable_operators(is_monotonic: bool) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ """
+ if is_monotonic:
+ return MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+ return set(MIRRORABLE_ALWAYS)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(self.is_monotonic)
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+ """
+ return VALUE_PLACEHOLDER_RE.sub(_PARSE_STANDIN, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(transform: str, engine: str) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def stored_expression_error(
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ The same subquery, function-denylist and RLS policy every other stored
+ expression goes through, applied to a value transform. It matters more
+ here than the name suggests: `build_probe_sql` binds only `:value` and
+ splices the rest of the transform in as SQL text, which the engine then
+ executes, so an ungated transform is arbitrary SQL. A dataset editor
+ without SQL Lab could store `(SELECT secret FROM protected_table LIMIT 1)
+ || :value` and read the answer back out of the emitted predicate.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+ """
+ selections = []
+ for index, value in enumerate(values):
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ compiled = clause.compile(
+ dialect=dialect,
+ compile_kwargs={"literal_binds": True},
+ )
+ selections.append(f"{compiled} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ database.db_engine_spec.select_without_from_suffix,
+ )
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ row = frame.iloc[0]
Review Comment:
Fixed. The frame is read cell-wise with `frame.iat[0, index]` rather than through `frame.iloc[0]`, so a row mixing an exact int64 with a float no longer unifies to float64 and rounds an integer key above 2^53.
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,1613 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import re
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: Every entry point enforces it -- the typed column field, the import schema
+#: and the preview request -- because `is_transform_active` parses the stored
+#: value on each Explore load, and an unbounded string would make that parse
+#: the expensive part of rendering a chart.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+ """
+ return VALUE_PLACEHOLDER_RE.sub(_PARSE_STANDIN, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(transform: str, engine: str) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error(
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
Review Comment:
Fixed. The `schema_to_xml` / `query_to_xml` / `table_to_xml` family (and their `_xmlschema` and `_xml_and_xmlschema` spellings) are in the default `DISALLOWED_SQL_FUNCTIONS` for PostgreSQL, and the denylist is enforced on save rather than only at probe time.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4318321746
##########
superset/db_engine_specs/postgres.py:
##########
@@ -370,11 +373,33 @@ def blank_port_to_none(self, data: Any, **kwargs: Any) -> Any:
return data
+#: The text forms PostgreSQL's date/time input reads, which `RedshiftEngineSpec`
+#: shares. Both the ISO spellings and the unseparated ones --
+#: ``'20260115'::date`` is 2026-01-15 -- so a ``YYYYMMDD`` bucketing key
+#: mirrors on either.
+#:
+#: Declared on the concrete specs rather than on `PostgresBaseEngineSpec`,
+#: which Snowflake, Vertica, HANA, Netezza and Hologres also inherit.
+#: Snowflake's AUTO date input does not take ``YYYYMMDD`` and reads an
+#: all-digit string as epoch seconds, so inheriting this misread the mirror.
+POSTGRES_TEMPORAL_LITERAL_FORMATS = (
+ "%Y-%m-%d",
+ "%Y-%m-%d %H:%M:%S",
+ "%Y-%m-%dT%H:%M:%S",
+ "%Y-%m-%d %H:%M:%S.%f",
+ "%Y-%m-%dT%H:%M:%S.%f",
+ "%Y%m%d",
+ "%Y%m%d%H%M%S",
Review Comment:
PostgreSQL does not read an unseparated 14-digit string as a timestamp: `select '20260706100811'::timestamp` fails with `timestamp out of range`, since the digits are taken as a date. With a TIMESTAMP partition column and a transform like `to_char(CAST(:value AS timestamp), 'YYYYMMDDHH24MISS')`, this format lets the value pass the temporal literal gate, so the preview reports a valid mapping and the chart query then carries `partition_ts = '20260706100811'` and errors out instead of declining the mirror. Should `%Y%m%d%H%M%S` be dropped from the shared list (or the result converted to a supported literal) so the mirror is declined?
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/usePartitionMappingPreview.ts:
##########
@@ -0,0 +1,206 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { SupersetClient, getClientErrorObject } from '@superset-ui/core';
+import { t } from '@apache-superset/core/translation';
+import { useDebounceValue } from 'src/hooks/useDebounceValue';
+import type { PartitionMappingPreview } from './types';
+import { transformCanPreview } from './utils';
+
+interface PreviewRequest {
+ datasetId?: number;
+ mappedColumn: string;
+ partitionColumn: string;
+ valueTransform: string;
+ sampleValues: string[];
+ operator: string;
+ isMonotonic: boolean;
+ /**
+ * Whether both mapped and partition column exist in the *saved* dataset.
+ *
+ * The endpoint belongs to the saved dataset and resolves these names against
+ * its persisted columns, while the editor validates against its unsaved
+ * state. Mapping onto a column that has only been synced from source, not
+ * saved, therefore had the editor accept it while the preview reported that
+ * the column does not exist -- a valid candidate shown as broken.
+ */
+ columnsAreSaved: boolean;
+ /** Skip entirely when the section isn't showing a mapping. */
+ enabled: boolean;
+}
+
+/**
+ * Preview the predicate a transform would emit, debounced.
+ *
+ * The endpoint fires a real warehouse query, so the transform is debounced
+ * before it leaves the browser, and a transform that cannot work is not sent at
+ * all. Neither is a guard -- the server keeps a per-user, per-dataset budget of
+ * its own, and remains the authority on whether a transform is usable. The
+ * point is that a half-written transform should not spend that budget and leave
+ * none for the finished one.
+ */
+export function usePartitionMappingPreview({
+ datasetId,
+ mappedColumn,
+ partitionColumn,
+ valueTransform,
+ sampleValues,
+ operator,
+ isMonotonic,
+ enabled,
+ columnsAreSaved,
+}: PreviewRequest) {
+ const [preview, setPreview] = useState<PartitionMappingPreview | null>(null);
+ const [loading, setLoading] = useState(false);
+ // Which request the displayed state belongs to. `AbortController` alone is
+ // not enough: aborting settles nothing, so a handler still runs and has to
+ // ask whether it is still the current one. See the effect below.
+ const latestRequest = useRef(0);
+
+ const debouncedTransform = useDebounceValue(valueTransform, 500);
+ // `sampleValues` is a fresh array on every render, so depending on it
+ // directly would refire the effect -- and spend the preview budget -- on
+ // every keystroke elsewhere in the row. Depend on its serialized form and
+ // hand the effect a value whose identity tracks that same key.
+ const sampleKey = JSON.stringify(sampleValues);
+ const samples = useMemo<string[]>(() => JSON.parse(sampleKey), [sampleKey]);
+
+ useEffect(() => {
+ const transform = debouncedTransform?.trim();
+ // Claimed before the early return as well, so a request already in flight
+ // cannot come back and overwrite what this run decided.
+ latestRequest.current += 1;
+ const requestId = latestRequest.current;
+
+ if (
+ enabled &&
+ datasetId &&
+ mappedColumn &&
+ !columnsAreSaved &&
+ transformCanPreview(transform, mappedColumn, partitionColumn)
+ ) {
+ // Answered without asking: the endpoint would resolve these names
+ // against the saved dataset and report a column that does not exist
+ // there yet. Said plainly rather than guessed at -- sending the
+ // candidate columns instead would have the probe build SQL from
+ // whatever the client claims their types are.
+ setPreview({
+ valid: false,
+ reason: 'unsaved',
+ error: t(
+ 'Save the dataset to preview this mapping. The preview runs against the saved columns, and this mapping uses one that has not been saved yet.',
+ ),
+ });
+ setLoading(false);
+ return undefined;
+ }
+
+ if (
+ !enabled ||
+ !datasetId ||
+ !mappedColumn ||
+ !columnsAreSaved ||
+ !transformCanPreview(transform, mappedColumn, partitionColumn)
+ ) {
+ setPreview(null);
+ // The spinner belongs to a request this run has just superseded. Its own
+ // handlers see the abort and stop short of clearing it, so clearing it
+ // here is the only thing that does -- otherwise clearing the transform
+ // mid-flight left the panel spinning for good.
+ setLoading(false);
+ return undefined;
+ }
+
+ const controller = new AbortController();
+ setLoading(true);
+
+ SupersetClient.post({
+ endpoint: `/api/v1/dataset/${datasetId}/partition_mapping/preview/`,
+ jsonPayload: {
+ mapped_column: mappedColumn,
+ // The candidate, not the saved one: the owner is previewing a mapping
+ // they have not committed yet.
+ partition_column: partitionColumn,
+ value_transform: transform,
+ sample_values: samples,
+ operator,
+ is_monotonic: isMonotonic,
+ },
+ signal: controller.signal,
+ })
+ .then(({ json }) => {
+ // This hits a live warehouse query, so responses can arrive out of
+ // order. Without this an older one overwrites the current preview and
+ // reports "Valid" for a transform the input no longer holds.
+ if (requestId !== latestRequest.current) {
+ return;
+ }
+ setPreview(json.result as PartitionMappingPreview);
+ })
+ .catch(async error => {
+ if (requestId !== latestRequest.current) {
+ return;
+ }
+ const clientError = await getClientErrorObject(error);
+ // Asked again: normalizing the error reads the response body, so a
+ // newer request can resolve while this one is still in that await, and
+ // writing then put a stale error over a current valid preview -- the
+ // panel reporting a failure for the transform the box no longer holds.
+ if (requestId !== latestRequest.current) {
+ return;
+ }
+ setPreview({
+ valid: false,
Review Comment:
Every failed preview request, including a 429 from the documented per-minute preview budget or a network error, is stored as `valid: false`, and `PartitionMappingSection` publishes that as a negative verdict. After hitting the limit on a mapping that works, the panel and the dataset banner say filters will not be mirrored, although chart queries still mirror. Could a transport or rate-limit failure stay an unknown verdict (like `unsaved`) rather than `valid: false`, reserving `valid: false` for a response that actually evaluated the mapping?
##########
tests/unit_tests/commands/dataset/update_test.py:
##########
@@ -1831,3 +1841,294 @@ def test_update_dataset_rejects_malicious_fetch_values_predicate(
and "fetch_values_predicate" in (exc.field_name or "")
for exc in excinfo.value._exceptions
)
+
+
+def _mapping_command(
+ mocker: MockerFixture,
+ transform: str | None,
+ *,
+ partition_mapped_column: str | None = None,
+ main_dttm_col: str = "event_time",
+ database: Database | None = None,
+) -> UpdateDatasetCommand:
+ """
+ A command whose stored dataset maps `event_time` onto `dt_epoch`.
+
+ `database` takes a real one, for the gates that read more of it than
+ `backend` -- the function denylist is keyed on the engine spec's own name,
+ which a mock cannot supply.
+ """
+ mapped_column = mocker.MagicMock()
+ mapped_column.column_name = "event_time"
+ mapped_column.partition_value_transform = transform
+ partition_column = mocker.MagicMock()
+ partition_column.column_name = "dt_epoch"
+ # The partition column is the target of a mapping, never the source of one.
+ partition_column.partition_value_transform = None
+
+ mock_dataset = mocker.MagicMock(is_managed_externally=False)
+ if database is not None:
+ mock_dataset.database = database
+ else:
+ mock_dataset.database.backend = "sqlite"
+ mock_dataset.catalog = None
+ mock_dataset.schema = "main"
+ mock_dataset.columns = [mapped_column, partition_column]
+ mock_dataset.main_dttm_col = main_dttm_col
+ mock_dataset.partition_column = "dt_epoch"
+ mock_dataset.partition_mapped_column = partition_mapped_column
+
+ command = UpdateDatasetCommand(1, {})
+ command._model = mock_dataset
+ return command
+
+
+@with_feature_flags(PARTITION_FILTER_MAPPING=True)
+def test_an_unparseable_transform_does_not_block_the_save(
+ mocker: MockerFixture,
+) -> None:
+ """
+ An unparseable transform is a Tier-2 issue: the mapping saves and stays
+ inactive. `validate_stored_expression` rejects anything it cannot parse, so
+ running it here would turn that into a blocking error and cost the owner the
+ rest of their edits.
+ """
+ gate = mocker.patch("superset.commands.dataset.update.validate_stored_expression")
+ command = _mapping_command(mocker, "unix_timestamp(:value")
+
+ exceptions: list[ValidationError] = []
+ command._validate_partition_mapping(exceptions)
+
+ assert exceptions == []
+ gate.assert_not_called()
+
+
+@with_feature_flags(PARTITION_FILTER_MAPPING=True)
+def test_a_parseable_transform_still_goes_through_the_stored_expression_gate(
+ mocker: MockerFixture,
+) -> None:
+ """
+ The gate that governs every other stored expression still runs -- now the
+ same `stored_expression_error` preview, import and the legacy save path
+ use, so the function denylist applies here too.
+ """
+ gate = mocker.patch(
+ "superset.commands.dataset.update.stored_expression_error", return_value=None
+ )
+ command = _mapping_command(mocker, "unix_timestamp(:value)")
+
+ exceptions: list[ValidationError] = []
+ command._validate_partition_mapping(exceptions)
+
+ assert exceptions == []
+ gate.assert_called_once()
+ assert gate.call_args.args[-1] == "unix_timestamp(:value)"
+
+
+@with_feature_flags(PARTITION_FILTER_MAPPING=True)
+@pytest.mark.parametrize(
+ "transform",
+ [
+ "unix_timestamp(:value) UNION ALL SELECT password FROM ab_user",
+ "unix_timestamp(:value); DROP TABLE ab_user",
+ "password || :value FROM ab_user",
+ ],
+ ids=["set-operation", "multi-statement", "bare-from"],
+)
+def test_a_transform_that_is_the_wrong_sql_still_reaches_the_gate(
+ mocker: MockerFixture, transform: str
+) -> None:
+ """
+ The companion to the test above, and the reason the skip condition is "not
+ SQL yet" rather than "does not parse". All three of these fail to parse as
+ a single statement, exactly as a half-typed transform does -- so a skip
+ keyed on parseability would have waved them through. None of them is on the
+ way to a valid transform.
+ """
+ command = _mapping_command(mocker, transform)
+
+ exceptions: list[ValidationError] = []
+ command._validate_partition_mapping(exceptions)
+
+ # Reported rather than silently accepted the way an unfinished transform is.
+ assert exceptions
+
+
+@with_feature_flags(PARTITION_FILTER_MAPPING=True)
+def test_a_transform_calling_a_denied_function_is_refused_on_save(
+ mocker: MockerFixture,
+) -> None:
+ """
+ A normal PUT was the one door into this field that skipped the function
+ denylist: preview, import and the legacy save path all ran
+ `stored_expression_error`, while this ran only the narrower parser gate. So
+ an owner could store what preview had just refused, and the probe would run
+ it on the next chart load.
+ """
+ command = _mapping_command(
+ mocker,
+ "schema_to_xml('public') || :value",
+ database=Database(database_name="pfm_pg", sqlalchemy_uri="postgresql://u@h/d"),
+ )
+
+ exceptions: list[ValidationError] = []
+ command._validate_partition_mapping(exceptions)
+
+ assert [exc.field_name for exc in exceptions] == ["partition_value_transform"]
+ assert "schema_to_xml" in str(exceptions[0].messages)
+
+
+@with_feature_flags(PARTITION_FILTER_MAPPING=True)
+def test_a_jinja_transform_is_still_rejected(mocker: MockerFixture) -> None:
+ """
+ Skipping the gate for unparseable transforms is not a hole for templating:
+ Jinja is a blocking issue of its own, reported before the gate is reached.
+ """
+ mocker.patch("superset.commands.dataset.update.validate_stored_expression")
+ command = _mapping_command(mocker, "unix_timestamp({{ current_user_id() }})")
+
+ exceptions: list[ValidationError] = []
+ command._validate_partition_mapping(exceptions)
+
+ assert [exc.field_name for exc in exceptions] == ["partition_value_transform"]
+
+
+@with_feature_flags(PARTITION_FILTER_MAPPING=True)
+def test_a_description_only_put_survives_an_implicit_self_mapping(
+ mocker: MockerFixture,
+) -> None:
+ """
+ `fetch_metadata` could choose the partition column as the default datetime
+ column without anyone asking, and a blocking self-mapping error then made
+ the dataset unsaveable forever -- including by the very write that would
+ have set the override that fixes it, and including a write that changes
+ nothing but the description.
+
+ The mapping is inert in that state either way, since
+ `resolve_partition_mapping` bails out on it, so the issue is reported
+ rather than blocking.
+ """
+ mocker.patch("superset.commands.dataset.update.validate_stored_expression")
+ command = _mapping_command(
+ mocker, "unix_timestamp(:value)", main_dttm_col="dt_epoch"
+ )
+ command._properties["description"] = "a new description"
+
+ exceptions: list[ValidationError] = []
+ command._validate_partition_mapping(exceptions)
+
+ assert exceptions == []
+
+
+@with_feature_flags(PARTITION_FILTER_MAPPING=True)
+def test_a_self_mapping_is_rejected_while_the_feature_is_on(
Review Comment:
These mapping tests call `_validate_partition_mapping()` directly, so removing its call from `UpdateDatasetCommand.validate()` leaves them green while a PUT accepts an explicit self-mapping. Could one test drive `UpdateDatasetCommand(...).run()` with the flag on and both references set to `dt_epoch`, asserting a `DatasetInvalidError` on `partition_column` and that the stored mapping is unchanged?
##########
superset/commands/dataset/importers/v0.py:
##########
@@ -291,7 +319,154 @@ def run(self) -> None:
.one()
)
dataset["database_id"] = database.id
- SqlaTable.import_from_dict(dataset, sync=self.sync)
+ self._prepare_partition_mapping(dataset, database)
+ table = SqlaTable.import_from_dict(dataset, sync=self.sync)
+ if table is not None:
+ imported.append(table)
+
+ self._repair_partition_mappings(imported)
+
+ @classmethod
+ def _default_omitted_monotonic_declarations(cls, config: Any) -> None:
+ """
+ Materialize `partition_transform_is_monotonic` wherever a transform is
+ set, anywhere in a v0 config.
+
+ The v1 importer does this on its own raw config, and for the same
+ reason: an overwrite keeps whatever the bundle omits, including a
+ ``True`` left behind by the transform this bundle is replacing. A
+ non-monotonic transform declared monotonic enables range mirrors that
+ exclude rows the filter keeps -- ``abs(:value)`` inheriting a stored
+ ``True`` turns ``n >= -1`` into ``p >= 1`` and misses ``n = 0``.
+
+ Walked rather than addressed directly because a v0 bundle comes in two
+ shapes: a CLI export nests datasets under ``databases[].tables[]``,
+ while a UI export is a bare list of datasets. Only columns that supply
+ a transform are touched, so a re-import that says nothing about a
+ column stays idempotent.
+ """
+ if isinstance(config, list):
+ for entry in config:
+ cls._default_omitted_monotonic_declarations(entry)
+ return
+ if not isinstance(config, dict):
+ return
+ _default_omitted_monotonic_declarations(config.get("columns") or [])
+ for key in (DATABASES_KEY, "tables"):
+ for child in config.get(key) or []:
+ cls._default_omitted_monotonic_declarations(child)
+
+ @staticmethod
+ def _prepare_partition_mapping(
+ dataset: dict[str, Any], database: Optional[Database]
+ ) -> None:
+ """
+ Run the two repairs that have to happen *before* the bundle is applied.
+
+ `_repair_partition_mappings` below runs after `import_from_dict`, which
+ is too late for either of these.
+
+ Sanitizing the bundle. The v1 importer drops a transform the save path
+ would refuse (`drop_unusable_partition_transforms`) on its way in, and
+ v0 did not -- so a legacy bundle naming ``partition_mapped_column: n``
+ and a transform of ``random() + :value`` on ``n`` imported happily and
+ then failed *every* later save: a description-only
+ ``PUT /api/v1/dataset/<id>`` returns 422 on the stored expression, and
+ the mapping never mirrors anything. Applied to the config rather than
+ the model because that is where the transform still is.
+
+ Disarming the old mapping. `DatasetDAO.clear_unmapped_partition_transforms`
+ reads the mapping as it stands, so the post-import call can only enforce
+ the one-transform invariant against the *new* references. An overwrite
+ that re-points the mapping makes a previously unmapped column the
+ effective one, and a transform parked there -- which nothing in the
+ bundle authored -- is found already mapped by the later call and kept.
+ A dataset mapping ``a -> p`` with a parked ``:value + 100`` on ``b``,
+ overwritten by a bundle setting ``partition_mapped_column: b`` and
+ omitting the columns, would mirror ``b = 5`` as ``p = 105`` and drop the
+ row ``(a=1, b=5, p=1)``. The same pre-change call `DatasetDAO.update`
+ and the v1 importer both make, and for the same reason.
+
+ ``database`` is ``None`` only for a CLI bundle importing a connection
+ that does not exist yet, which by definition has no stored dataset to
+ disarm and no dialect to validate a transform against -- the same case
+ `drop_unusable_partition_transforms` already declines to act on.
+ """
+ if database is None:
+ return
+
+ # Deferred import: `daos.dataset` pulls in `views.base`, which
+ # circularly imports back into the commands package at app init.
+ from superset.daos.dataset import DatasetDAO # noqa: PLC0415
+
+ drop_unusable_partition_transforms(dataset, database)
+
+ if not (table_name := dataset.get("table_name")):
+ return
+ existing = (
+ db.session.query(SqlaTable)
+ .filter(
+ SqlaTable.table_name == table_name,
+ SqlaTable.schema == dataset.get("schema"),
+ SqlaTable.catalog == dataset["catalog"]
+ if dataset.get("catalog") is not None
+ else True,
+ SqlaTable.database_id == database.id,
+ )
+ .one_or_none()
+ )
+ if existing is not None:
+ DatasetDAO.clear_unmapped_partition_transforms(existing)
+
+ @staticmethod
+ def _repair_partition_mappings(datasets: list[SqlaTable]) -> None:
+ """
+ Keep the partition filter mapping honest across a v0 import.
+
+ The mapping's columns ride in `SqlaTable.export_fields`, so this path
+ carries them -- but it calls `SqlaTable.import_from_dict` directly and
+ goes through neither `DatasetDAO.update` nor the v1 importer, so
+ neither of the mapping's repairs ran. An older bundle imported with
+ ``--sync columns`` that omits the partition column deletes it and keeps
+ `partition_column` naming it: pruning silently stops, and every later
+ edit of that dataset fails the partition-column-not-found validation,
+ including a description-only PUT, which carries no columns payload and
+ so cannot reach the branch that forgives a stored-only dangle.
+
+ The same pair, in the same order, as `RefreshDatasetCommand` and the
+ v1 importer. Run after the import rather than around it because
+ ``import_from_dict`` is what discovers which datasets are involved.
+ """
+ if not datasets:
+ return
+ # Deferred import: `daos.dataset` pulls in `views.base`, which
+ # circularly imports back into the commands package at app init.
+ from superset.daos.dataset import DatasetDAO # noqa: PLC0415
+
+ db.session.flush()
+ for dataset in datasets:
+ DatasetDAO.clear_dangling_partition_mapping(
Review Comment:
`dataset.columns` was already loaded by `clear_unmapped_partition_transforms(existing)` in `_prepare_partition_mapping`, and a `--sync columns` import removes omitted columns with `session.delete`, which leaves a deleted member in a loaded collection until it is expired. So a bundle that omits the partition column `p` still sees `p` as surviving here, `clear_dangling_partition_mapping` keeps `partition_column = 'p'`, and every later save, including a description-only PUT, fails the partition-column-not-found validation. Could the collection be expired (as the v1 importer does) before computing the surviving column names?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "hughhhh (via GitHub)" <gi...@apache.org>.
hughhhh commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4162115360
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/useDebouncedCommit.ts:
##########
@@ -0,0 +1,85 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { debounce } from 'lodash-es';
+import { Constants } from '@superset-ui/core/components';
+
+/**
+ * Local text state that commits upward on a debounce.
+ *
+ * The dataset editor's commit path is asynchronous and snapshot-based: a value
+ * handed to `onChange` travels Field -> Fieldset -> CollectionTable ->
+ * DatasourceEditor -> DatasourceModal and arrives back on the `value` prop
+ * several renders later, and the callback that commits it was built during an
+ * earlier render. An input driven straight off that prop therefore loses any
+ * keystroke that lands while a commit is in flight -- which is why every other
+ * control in the editor types into local state and commits on a debounce, and
+ * why Fieldset's own comment says the editor assumes exactly that. This is
+ * TextControl's contract (src/explore/components/controls/TextControl), minus
+ * the ControlHeader and the number parsing this field does not want.
+ */
+export function useDebouncedCommit(
+ value: string | null | undefined,
+ commit: (next: string) => void,
+ delay: number = Constants.FAST_DEBOUNCE,
+) {
+ const [localValue, setLocalValue] = useState(value ?? '');
+ const [prevValue, setPrevValue] = useState(value);
+
+ // The commit fires from a timer, so the callback is handed in at call time
+ // rather than captured when the debounce was built -- otherwise it would
+ // close over whichever render happened to create it, and the commit reads
+ // props (the column's monotonic flag) to decide what to write.
+ const debouncedCommit = useRef(
+ debounce(
+ (next: string, commitFn: (value: string) => void) => commitFn(next),
+ delay,
+ ),
+ );
+
+ useEffect(() => () => debouncedCommit.current.cancel(), []);
+
+ const onChange = useCallback(
+ (next: string) => {
+ setLocalValue(next);
+ debouncedCommit.current(next, commit);
+ },
+ [commit],
+ );
+
+ /**
+ * Commit a pending edit now. lodash's `flush` is a no-op when nothing is
+ * pending, so a blur with no edit behind it costs nothing.
+ */
+ const flush = useCallback(() => {
+ debouncedCommit.current.flush();
+ }, []);
+
+ // Re-seed from the prop only when the prop itself changed. Adjusting state
+ // during render is React's documented pattern for this; deriving a display
+ // value without writing it back leaves `localValue` holding superseded text,
+ // so the next render that changes only an unrelated prop -- and so does not
+ // re-enter this branch -- puts the stale value back in the input.
+ if (prevValue !== value) {
Review Comment:
Fixed in `1e132aefc9`. The hook records what it last handed to `commit` and skips the re-seed for that one value, consuming it so a later genuine reset to the same text is still honoured. The new test flushes with Enter and keeps typing across the echo's arrival, which is the interleaving the debounce does not cover — it fails without the change.
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/types.ts:
##########
@@ -55,3 +55,22 @@ export interface PartitionMappingPreview {
* mapping rather than a source for one.
*/
export type PartitionRowState = 'mapped' | 'unmapped' | 'partition' | 'none';
+
+/**
+ * One problem with the mapping that stops the save.
+ *
+ * The client half of `MappingValidationIssue` in
+ * `superset/connectors/sqla/partition_mapping.py`, without its `blocking` flag:
+ * the backend reports two tiers because a half-written transform is allowed to
+ * save and sit inactive, and only the blocking tier is worth stopping the owner
+ * in the editor for. Everything this carries blocks, so the flag has nothing to
+ * distinguish. `field` names the input at fault, so the message can be shown
+ * there rather than only in the Save button's tooltip.
+ */
+export interface PartitionMappingIssue {
Review Comment:
Fixed in `1e132aefc9`. Wired in rather than dropped. `PartitionColumnFields` now renders the `partition_column` and `partition_mapped_column` messages under the select each is about, instead of leaving an owner to work out which of three inputs the Save tooltip means.
##########
superset-frontend/src/explore/components/PartitionPruningIndicator/index.tsx:
##########
@@ -0,0 +1,169 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { t } from '@apache-superset/core/translation';
+import { css, useTheme } from '@apache-superset/core/theme';
+import { NO_TIME_RANGE } from '@superset-ui/core';
+import { Icons, Tooltip } from '@superset-ui/core/components';
+import type { PartitionFilterMapping } from '@superset-ui/chart-controls';
+import { ExpressionTypes } from 'src/explore/components/controls/FilterControl/types';
+
+interface PartitionPruningIndicatorProps {
+ /** The dataset's mapping summary, straight off the datasource payload. */
+ mapping?: PartitionFilterMapping | null;
+}
+
+/**
+ * The parts of an ad-hoc filter that decide whether it is mirrored. Structural
+ * rather than the `AdhocFilter` class so native filters and cross-filters --
+ * which reach the query path in the same shape but are not that class -- can be
+ * checked with the same function.
+ */
+export interface MirrorCandidateFilter {
+ expressionType?: string;
+ subject?: string | { column_name?: string } | null;
+ operator?: string | null;
+ comparator?: unknown;
+}
+
+/**
+ * The glyph on a filter whose column is mirrored onto a partition column
+ * (wireframe 1d).
+ *
+ * Chart authors do not configure any of this and ideally never learn the word
+ * "partition"; the indicator exists only to explain why their query got faster,
+ * and to point at the generated SQL where the extra predicate is visible.
+ */
+export default function PartitionPruningIndicator({
+ mapping,
+}: PartitionPruningIndicatorProps) {
+ const theme = useTheme();
+
+ if (!mapping?.active) {
+ return null;
+ }
+
+ return (
+ <Tooltip
+ placement="top"
+ title={t(
+ 'This filter is also applied to a partition column for faster queries. See "View query" for the generated SQL.',
+ )}
+ >
+ <span data-test="partition-pruning-indicator">
+ <Icons.FilterOutlined
+ iconSize="s"
+ iconColor={theme.colorSuccess}
+ css={css`
+ margin-left: ${theme.sizeUnit}px;
+ vertical-align: middle;
+ `}
+ />
+ </span>
+ </Tooltip>
+ );
+}
+
+/**
+ * The filter's column name. `subject` is a bare string for simple filters and a
+ * column object when the filter was built from a dropped column.
+ */
+function subjectName(
+ subject: MirrorCandidateFilter['subject'],
+): string | undefined {
+ return typeof subject === 'string'
+ ? subject
+ : (subject?.column_name ?? undefined);
+}
+
+/**
+ * Whether `columnName` is the one column the mapping mirrors.
+ *
+ * Necessary but not sufficient for the glyph -- see `isMirroredFilter`.
+ */
+export function isMirroredColumn(
+ mapping: PartitionFilterMapping | null | undefined,
+ columnName: string | null | undefined,
+): boolean {
+ return Boolean(
+ mapping?.active && columnName && mapping.mapped_column === columnName,
+ );
+}
+
+/**
+ * Whether the comparator is one the mirrored predicate can be built from.
+ *
+ * A `NULL` inside an `IN` list widens the real predicate to
+ * `col IS NULL OR col IN (...)`, which the mirror cannot express, so the
+ * backend skips those lists outright.
+ */
+function hasMirrorableValue(operator: string, comparator: unknown): boolean {
+ if (operator === 'TEMPORAL_RANGE') {
+ // `No filter` resolves to neither bound, so no range is mirrored.
+ return typeof comparator === 'string' && comparator !== NO_TIME_RANGE;
+ }
+ if (operator === 'IN') {
+ return (
+ Array.isArray(comparator) &&
+ comparator.length > 0 &&
+ !comparator.some(value => value == null)
+ );
+ }
+ return comparator !== null && comparator !== undefined && comparator !== '';
Review Comment:
Fixed in `1e132aefc9`. Aligned with the backend — `_collect_partition_mirror_filter` excludes only `None`, so `col = ''` does mirror and the glyph belongs on it. The test that pinned the divergence the wrong way round is flipped, with `<NULL>` cases added alongside it.
##########
superset-frontend/src/explore/components/PartitionPruningIndicator/index.tsx:
##########
@@ -0,0 +1,169 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { t } from '@apache-superset/core/translation';
+import { css, useTheme } from '@apache-superset/core/theme';
+import { NO_TIME_RANGE } from '@superset-ui/core';
+import { Icons, Tooltip } from '@superset-ui/core/components';
+import type { PartitionFilterMapping } from '@superset-ui/chart-controls';
+import { ExpressionTypes } from 'src/explore/components/controls/FilterControl/types';
+
+interface PartitionPruningIndicatorProps {
+ /** The dataset's mapping summary, straight off the datasource payload. */
+ mapping?: PartitionFilterMapping | null;
+}
+
+/**
+ * The parts of an ad-hoc filter that decide whether it is mirrored. Structural
+ * rather than the `AdhocFilter` class so native filters and cross-filters --
+ * which reach the query path in the same shape but are not that class -- can be
+ * checked with the same function.
+ */
+export interface MirrorCandidateFilter {
+ expressionType?: string;
+ subject?: string | { column_name?: string } | null;
+ operator?: string | null;
+ comparator?: unknown;
+}
+
+/**
+ * The glyph on a filter whose column is mirrored onto a partition column
+ * (wireframe 1d).
+ *
+ * Chart authors do not configure any of this and ideally never learn the word
+ * "partition"; the indicator exists only to explain why their query got faster,
+ * and to point at the generated SQL where the extra predicate is visible.
+ */
+export default function PartitionPruningIndicator({
+ mapping,
+}: PartitionPruningIndicatorProps) {
+ const theme = useTheme();
+
+ if (!mapping?.active) {
+ return null;
+ }
+
+ return (
+ <Tooltip
+ placement="top"
+ title={t(
+ 'This filter is also applied to a partition column for faster queries. See "View query" for the generated SQL.',
+ )}
+ >
+ <span data-test="partition-pruning-indicator">
+ <Icons.FilterOutlined
+ iconSize="s"
+ iconColor={theme.colorSuccess}
+ css={css`
+ margin-left: ${theme.sizeUnit}px;
+ vertical-align: middle;
+ `}
+ />
+ </span>
+ </Tooltip>
+ );
+}
+
+/**
+ * The filter's column name. `subject` is a bare string for simple filters and a
+ * column object when the filter was built from a dropped column.
+ */
+function subjectName(
+ subject: MirrorCandidateFilter['subject'],
+): string | undefined {
+ return typeof subject === 'string'
+ ? subject
+ : (subject?.column_name ?? undefined);
+}
+
+/**
+ * Whether `columnName` is the one column the mapping mirrors.
+ *
+ * Necessary but not sufficient for the glyph -- see `isMirroredFilter`.
+ */
+export function isMirroredColumn(
+ mapping: PartitionFilterMapping | null | undefined,
+ columnName: string | null | undefined,
+): boolean {
+ return Boolean(
+ mapping?.active && columnName && mapping.mapped_column === columnName,
+ );
+}
+
+/**
+ * Whether the comparator is one the mirrored predicate can be built from.
+ *
+ * A `NULL` inside an `IN` list widens the real predicate to
+ * `col IS NULL OR col IN (...)`, which the mirror cannot express, so the
+ * backend skips those lists outright.
+ */
+function hasMirrorableValue(operator: string, comparator: unknown): boolean {
+ if (operator === 'TEMPORAL_RANGE') {
+ // `No filter` resolves to neither bound, so no range is mirrored.
+ return typeof comparator === 'string' && comparator !== NO_TIME_RANGE;
+ }
+ if (operator === 'IN') {
+ return (
+ Array.isArray(comparator) &&
+ comparator.length > 0 &&
+ !comparator.some(value => value == null)
+ );
+ }
+ return comparator !== null && comparator !== undefined && comparator !== '';
+}
+
+/**
+ * Whether this filter actually produces a predicate on the partition column.
+ *
+ * Naming the mapped column is only the first of the query path's gates
+ * (`_collect_partition_mirror_filter` in `superset/models/helpers.py`): the
+ * operator has to be one the mapping can mirror, and the value has to be one
+ * the mirrored predicate can carry. A `country != 'US'` chip names the mapped
+ * column and mirrors nothing -- negations are never safe, because the transform
+ * need not be injective -- so labelling it would promise a speed-up the query
+ * does not deliver.
+ *
+ * The operator list is not restated here; it is computed server-side from the
+ * transform's declared monotonicity and shipped on the mapping.
+ */
+export function isMirroredFilter(
Review Comment:
Out of scope for the indicator, and now written down where the check lives rather than left implicit. `removed_filters` is assembled while the query is generated and is not in `form_data`, so the only way for the browser to know would be to render the Jinja itself. The glyph is advisory; "View query" stays the authority.
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -416,7 +416,7 @@ def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
if not _transform_is_usable(transform, datasource.database.backend):
Review Comment:
Fixed in `7951536198`. `_transform_is_usable` is deleted. The query-time gate is `is_transform_active` — the same function the indicator reads, which is `validate_transform` with the messages discarded — so the two cannot drift again. That also closes the `now()`-via-import path you describe: it is blocking there, so the mapping no longer resolves at all.
##########
superset-frontend/packages/superset-ui-chart-controls/src/shared-controls/sharedControls.tsx:
##########
@@ -208,9 +208,68 @@ const time_grain_sqla: SharedControlConfig<'SelectControl'> = {
sortComparator: () => 0, // Disable frontend sorting to preserve backend order
};
+/**
+ * The mapping to hand the time control's partition-pruning indicator, or `null`
+ * when this time range is not mirrored.
+ *
+ * The control renders whatever mapping it is given, so the applicability check
+ * belongs here, where the selected temporal column and the range are both in
+ * scope. Unlike an ad-hoc filter chip the control names no column of its own:
+ * the query path mirrors the time range only when the *chart's* temporal column
+ * is the mapped one (`superset/models/helpers.py`, the `granularity` and
+ * `always_filter_main_dttm` branches), and only when the range resolves to at
+ * least one bound -- `No filter` resolves to neither.
+ */
+function timeRangePartitionMapping({
+ datasource,
+ form_data: formData,
+}: ControlPanelState) {
+ const dataset = datasource as Dataset | null;
+ const mapping = dataset?.partition_filter_mapping;
+ if (
+ !mapping?.active ||
+ !mapping.mirrorable_operators?.includes('TEMPORAL_RANGE')
+ ) {
+ return null;
+ }
+ if (formData?.time_range === NO_TIME_RANGE) {
Review Comment:
Fixed in `1e132aefc9`. `(formData?.time_range ?? NO_TIME_RANGE) === NO_TIME_RANGE`, so a legacy saved chart with no key at all is treated the same as the sentinel.
##########
superset-frontend/src/explore/components/PartitionPruningIndicator/index.tsx:
##########
@@ -0,0 +1,169 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { t } from '@apache-superset/core/translation';
+import { css, useTheme } from '@apache-superset/core/theme';
+import { NO_TIME_RANGE } from '@superset-ui/core';
+import { Icons, Tooltip } from '@superset-ui/core/components';
+import type { PartitionFilterMapping } from '@superset-ui/chart-controls';
+import { ExpressionTypes } from 'src/explore/components/controls/FilterControl/types';
+
+interface PartitionPruningIndicatorProps {
+ /** The dataset's mapping summary, straight off the datasource payload. */
+ mapping?: PartitionFilterMapping | null;
+}
+
+/**
+ * The parts of an ad-hoc filter that decide whether it is mirrored. Structural
+ * rather than the `AdhocFilter` class so native filters and cross-filters --
+ * which reach the query path in the same shape but are not that class -- can be
+ * checked with the same function.
+ */
+export interface MirrorCandidateFilter {
+ expressionType?: string;
+ subject?: string | { column_name?: string } | null;
+ operator?: string | null;
+ comparator?: unknown;
+}
+
+/**
+ * The glyph on a filter whose column is mirrored onto a partition column
+ * (wireframe 1d).
+ *
+ * Chart authors do not configure any of this and ideally never learn the word
+ * "partition"; the indicator exists only to explain why their query got faster,
+ * and to point at the generated SQL where the extra predicate is visible.
+ */
+export default function PartitionPruningIndicator({
+ mapping,
+}: PartitionPruningIndicatorProps) {
+ const theme = useTheme();
+
+ if (!mapping?.active) {
+ return null;
+ }
+
+ return (
+ <Tooltip
+ placement="top"
+ title={t(
+ 'This filter is also applied to a partition column for faster queries. See "View query" for the generated SQL.',
+ )}
+ >
+ <span data-test="partition-pruning-indicator">
Review Comment:
Fixed in `1e132aefc9`. It is a text-variant `Button` carrying the tooltip text as its `aria-label` now — the shape `InfoTooltip` already uses. A `span` with `tabIndex` was the first attempt and `jsx-a11y/no-noninteractive-tabindex` was right to reject it. The test tabs to it and asserts focus.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #43870:
URL: https://github.com/apache/superset/pull/43870#issuecomment-5973004888
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers an incremental AI Review.
- `/review full` - Manually triggers a full AI Review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #43870:
URL: https://github.com/apache/superset/pull/43870#issuecomment-5958887263
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers an incremental AI Review.
- `/review full` - Manually triggers a full AI Review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4185020733
##########
superset/models/helpers.py:
##########
@@ -5623,6 +6025,33 @@ def get_sqla_query( # pylint: disable=too-many-arguments,too-many-locals,too-ma
)
having_clause_and += [Grouping(self.text(having))]
+ # The mirrors go on last, so the snapshot taken here is everything the
+ # outer query and the series-limit ranking subquery agree about: row
+ # level security, the extras `where`, every filter. The two disagree
+ # about exactly the mirrors, and subtracting them again later is not an
+ # option -- `==` on a SQLAlchemy expression builds a new expression
+ # rather than answering a question, so the list cannot be filtered by
+ # identity.
+ where_clause_and_without_mirrors = list(where_clause_and)
+ inner_partition_mirror_predicates: list[Any] = []
+ if partition_mapping is not None:
+ partition_mirror_predicates = self._build_partition_mirror_predicates(
Review Comment:
On a mapped virtual dataset using `current_username()`, cache-key extraction calls `get_sqla_query()` before the chart-cache lookup, so a relative range such as Last 24 hours runs a new warehouse probe even when chart data is cached. Could extra-cache-key extraction skip these probes and leave them to SQL generation for a cache miss?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,1613 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import re
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: Every entry point enforces it -- the typed column field, the import schema
+#: and the preview request -- because `is_transform_active` parses the stored
+#: value on each Explore load, and an unbounded string would make that parse
+#: the expensive part of rendering a chart.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+ """
+ return VALUE_PLACEHOLDER_RE.sub(_PARSE_STANDIN, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(transform: str, engine: str) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error(
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
Review Comment:
A bare scalar can still read tables: PostgreSQL's `schema_to_xml` passes these checks and the default function denylist, then returns connection-user-readable schema contents through preview, bypassing the editor's dataset grants and Superset RLS ([function semantics](https://www.postgresql.org/docs/current/functions-xml.html#FUNCTIONS-XML-MAPPING)). Could read-capable functions be excluded before executing a transform, rather than assuming the absence of FROM/subqueries makes it read-free?
##########
superset/connectors/sqla/models.py:
##########
@@ -1689,6 +1726,8 @@ class SqlaTable(
"normalize_columns",
"always_filter_main_dttm",
"folders",
+ "partition_column",
Review Comment:
Duplicating a mapped virtual dataset copies these references through `table.override()`, but `DuplicateDatasetCommand` reconstructs its columns without `partition_value_transform` or `partition_transform_is_monotonic`, silently disabling the clone's mapping. Could duplication preserve the column-side configuration too?
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/DatasourceEditor.tsx:
##########
@@ -617,100 +674,160 @@ function ColumnCollectionTable({
/>
);
- return (
- <CollectionTable
- tableColumns={tableColumns}
- sortColumns={tableColumns}
- allowDeletes
- allowAddItem={allowAddItem}
- itemGenerator={itemGenerator}
- collection={columns}
- columnLabelTooltips={columnLabelTooltips}
- filterTerm={filterTerm}
- filterFields={filterFields}
- stickyHeader
- expandFieldset={
- <FormContainer>
- <Fieldset compact>
- {showExpression && (
- <Field
- fieldKey="expression"
- label={t('SQL expression')}
- control={
- <TextAreaControl
- language="sql"
- offerEditInModal={false}
- maxLines={25}
- debounceDelay={300}
- />
- }
- />
- )}
- <Field
- fieldKey="verbose_name"
- label={t('Label')}
- control={
- <TextControl
- controlId="verbose_name"
- placeholder={t('Label')}
- />
- }
+ const partitionMappingEnabled =
+ isFeatureEnabled(FeatureFlag.PartitionFilterMapping) && Boolean(datasource);
+ const partitionColumn = partitionMappingEnabled
+ ? datasource?.partition_column
+ : null;
+
+ // The two `itemRenderers` variants below differ only in which widget edits
+ // the name, so the certified badge and the PARTITION tag are shared here
+ // rather than written out four times.
+ const renderColumnName =
+ (EditControl: 'editableTitle' | 'textControl') =>
+ (
+ v: unknown,
+ onItemChange: (value: any) => void,
+ _: unknown,
+ record: Column,
+ ): ReactNode => (
+ <StyledLabelWrapper>
+ {record.is_certified && (
+ <CertifiedBadge
+ certifiedBy={record.certified_by}
+ details={record.certification_details}
+ />
+ )}
+ {editableColumnName ? (
+ EditControl === 'editableTitle' ? (
+ <EditableTitle
+ canEdit
+ title={v as string}
+ onSaveTitle={onItemChange}
/>
- <Field
- fieldKey="description"
- label={t('Description')}
- control={
- <TextControl
- controlId="description"
- placeholder={t('Description')}
+ ) : (
+ <TextControl value={v as string} onChange={onItemChange} />
+ )
+ ) : (
+ (v as ReactNode)
+ )}
+ {partitionColumn === record.column_name && (
+ <Tooltip
+ title={t(
+ 'Filters on the mapped column are mirrored onto this column so the engine can prune partitions.',
+ )}
+ >
+ <Label data-test="partition-tag">
+ <Icons.FilterOutlined iconSize="s" /> {t('PARTITION')}
+ </Label>
+ </Tooltip>
+ )}
+ </StyledLabelWrapper>
+ );
+
+ return (
+ <StyledColumnsTableWrapper>
+ <CollectionTable
+ tableColumns={tableColumns}
+ sortColumns={tableColumns}
+ allowDeletes
+ allowAddItem={allowAddItem}
+ itemGenerator={itemGenerator}
+ collection={columns}
+ columnLabelTooltips={columnLabelTooltips}
+ filterTerm={filterTerm}
+ filterFields={filterFields}
+ rowClassName={record =>
+ partitionColumn === record.column_name ? 'partition-column-row' : ''
+ }
+ expandItemWhere={
Review Comment:
Clicking Customize the value transform now filters to the mapped column but leaves its row collapsed: the current `CollectionTable` no longer consumes `expandItemWhere`, so the transform editor never opens. Could the expansion consumer be restored and the real editor navigation covered without manually expanding the row?
##########
docs/admin_docs/configuration/partition-filter-mapping.mdx:
##########
@@ -0,0 +1,204 @@
+---
+title: Partition Filter Mapping
+hide_title: true
+sidebar_position: 15
+version: 1
+---
+
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+
+# Partition Filter Mapping
+
+Tables on Hadoop-family engines are often partitioned on a *technical* column — an epoch
+integer, a lowercased region key — that no analyst would ever filter on. Unless a query
+carries a predicate on that column, the engine scans every partition.
+
+Partition filter mapping makes this a dataset setting instead of a per-chart chore. A
+dataset owner names the partition column, the business column whose filters should be
+mirrored onto it, and a value transform. Superset then appends an equivalent predicate on
+the partition column to every query. Chart authors change nothing; queries prune.
+
+:::caution Experimental
+This feature is behind the `PARTITION_FILTER_MAPPING` feature flag and is off by default.
+:::
+
+## Enabling it
+
+```python
+FEATURE_FLAGS = {
+ "PARTITION_FILTER_MAPPING": True,
+}
+```
+
+Configure it as a **static boolean**. `FEATURE_FLAGS` also accepts per-request callables,
+but a flag that resolves differently per user or tenant would let a user with the feature
+off read a cached chart result that was produced from pruned SQL by a user with it on.
+
+## Configuring a mapping
+
+In the dataset editor's **Columns** tab, under *Default Column Settings*, pick a
+**Partition column**. By default the mapping follows the dataset's default datetime column,
+so re-pointing that column moves the mapping with it; set an explicit override if you want it
+pinned to a different column.
+
+Expand the mapped column's row in *Column Settings* and set the **value transform**: a SQL
+expression containing a `:value` placeholder, which stands for the filter value being
+mirrored. The **Transform preserves ordering** checkbox sits directly beneath it.
+
+| Mapped column | Partition column | Transform |
+|---|---|---|
+| `event_time` (`TIMESTAMP`) | `dt_epoch` (`BIGINT`) | `unix_timestamp(:value)` |
+| `country` (`VARCHAR`) | `region_key` (`VARCHAR`) | `lower(:value)` |
+
+A filter of `event_time >= '2026-01-01'` then adds `dt_epoch >= 1767225600` to the query.
+The added predicate is an ordinary `WHERE` clause and shows up in **View query**.
+
+### Transform preserves ordering
+
+Range filters — including the Explore time range, the most important case — are only
+mirrored when you check **Transform preserves ordering**.
+
+Monotonicity is a property of the *transform*, not of the column's data type.
+`unix_timestamp(:value)` preserves ordering. `hour(:value)`,
+`date_format(:value, 'dd')` and `dayofweek(:value)` are all perfectly reasonable
+partition transforms on a `TIMESTAMP` column and none of them do: `hour('2026-01-01 23:00')`
+is greater than `hour('2026-01-02 01:00')` even though the first instant is earlier. Mirroring
+a range through one of those would silently return wrong numbers, so Superset asks you to
+declare it rather than guessing.
+
+When the box is unchecked, `=` and `IN` filters still mirror; ranges do not.
+
+## What is and isn't mirrored
+
+| Filter | Mirrored |
+|---|---|
+| `=`, `IN` | Always, except on a text column whose engine does not compare text exactly |
+| `>`, `>=`, `<`, `<=`, time ranges | Only when the transform preserves ordering |
+| `!=`, `NOT IN`, `LIKE`, `ILIKE`, `IS NULL`, `IS TRUE` | Never |
+
+Negations are never safe. A transform need not be injective: `lower(:value)` with
+`country != 'US'` would mirror to `region_key != 'us'`, which excludes rows whose `country`
+is already lowercase `'us'` — rows the original filter *keeps*.
+
+**Text comparison.** Mirroring `col = v` onto `partition_col = T(v)` assumes the engine
+compares `col` the way the transform was written against. Under a case-insensitive collation
+it does not: a stored `country` of `'us'` satisfies a filter for `'US'`, while the mirror is
+derived from `'US'` and excludes the row. So `=` and `IN` on a **text** mapped column only
+mirror on engines whose default text comparison is exact — Hive, Impala, Trino, Presto,
+Spark, Databricks, PostgreSQL, Snowflake, BigQuery and SQLite. On MySQL and SQL Server, whose
+default collations are case-insensitive, a text mapping is stored and shown but no `=` or
+`IN` filter mirrors through it; map a numeric or temporal column instead. Numeric and
+temporal comparison is exact everywhere, and ranges are unaffected either way — checking
+**Transform preserves ordering** is already a statement about the column's own ordering.
+
+One case Superset cannot check for you: a column that declares its own collation, such as
+`country COLLATE NOCASE`, on an engine that is otherwise exact. Nothing in the metadata
+exposes that, so it falls under the same pipeline assumption as the partition key itself.
+
+**Time grains.** A filter that carries a time grain — drill-to-detail, mostly — compares the
+*truncated* column, so the raw bounds it carries do not describe the rows it keeps: a row in
+the final partial bucket satisfies `DATE_TRUNC(...) < until` while `col < until` excludes it.
+Grained *ranges* still mirror, with both bounds widened by one bucket so the mirror stays no
+narrower than the real filter. A `P1D` drill therefore reads three days of partitions rather
+than one, instead of scanning the table. Grained `=` and `IN` filters do not mirror.
+
+Widening is only applied to grains whose bucket width Superset knows, which means the
+built-in ones. A grain you added through `TIME_GRAIN_ADDONS`, or a built-in grain whose SQL
+you replaced through `TIME_GRAIN_ADDON_EXPRESSIONS`, has no width Superset can rely on and
+simply does not mirror.
+
+Known gaps, all of which are out of scope rather than bugs:
+
+- **Filter-value dropdowns do not prune.** Populating a filter's value list runs its own
+ `SELECT DISTINCT`, which never goes through the chart query path. There is no filter to
+ mirror from.
+- **Row-level security predicates do not mirror.** They are stored as raw SQL and appended
+ downstream of the structured filters.
+- **Custom SQL `WHERE` clauses do not mirror**, for the same reason.
+- **Columns with an active advanced data type do not mirror.** Those build their own
+ predicate shape from translated values, so there is no operator/value pair to mirror.
+- Dashboard native filters and cross-filters *do* mirror — they arrive as ordinary filters —
+ they just carry no visual indicator in the filter bar.
+
+## The assumption this rests on
+
+Superset emits a predicate on the partition column that stands in for one on the mapped
+column. That substitution is only valid if, for every row in the table:
+
+```
+partition_column = <transform>(mapped_column)
+```
+
+**Superset cannot verify this.** It is a property of whatever ETL populates the partition
+column. If that job lags, backfills with different logic, or writes the partition key in a
+different timezone than the transform resolves, mirrored predicates silently drop real rows
+and charts show quietly wrong numbers. Confirm the invariant with whoever owns the pipeline
+before enabling a mapping on a production dataset.
+
+Rows in a `NULL` partition are the one case Superset *does* defend against. A predicate like
+`dt_epoch >= X` is `NULL` — and so drops the row — wherever `dt_epoch` is `NULL`, even when
+the original filter matches it. That is reachable: a dynamic-partition insert on Hive or
+Impala parks rows whose partition key was `NULL` in the default partition
+(`__HIVE_DEFAULT_PARTITION__`), and the column reads back as `NULL` when you query it. A
+transform that returns `NULL` for an input it cannot convert produces the same thing on any
+engine.
+
+The mirrored predicate is therefore emitted as:
+
+```sql
+(dt_epoch >= X AND dt_epoch < Y) OR dt_epoch IS NULL
+```
+
+The mirror only has to be *no narrower* than the filter it stands in for, so admitting the
+`NULL` partition costs one extra partition read and keeps those rows. Engines still prune
+everything else.
+
+## How the transform is evaluated
+
+The transform is evaluated against the engine — pinned to the dataset's database, catalog
+and schema — and the result is emitted as a literal constant. Results are cached
+(`PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT`, 24 hours by default), which matters because this
+adds a round trip to the chart query path. Day-aligned ranges like "Last month" hit the cache
+constantly; second-granularity relative ranges like "Last 24 hours" essentially never do.
+
+If the evaluation fails for any reason, no predicate is added: the query still runs and is
+still correct, it just scans more partitions.
+
+Because the evaluation happens in a **different session** from the chart query, transforms
+that call non-deterministic functions are rejected when you save. That includes `now()`,
+`current_date`, `current_timestamp`, `rand()` and the zero-argument `unix_timestamp()`, which
+means "now" on Hive and Impala. The one-argument `unix_timestamp(:value)` is fine.
+
+Session-dependent behaviour that Superset cannot detect is still your responsibility:
+`unix_timestamp(:value)` is timezone-dependent on Hive and Impala, so if the evaluating
+session and the query session resolve different timezones the emitted bounds will disagree
+with the timestamp bounds they mirror. Prefer explicitly-anchored transforms.
+
+Jinja templating is not supported in a transform. The template would render in a different
+context and at a different time from the chart query.
+
+## Related configuration
+
+| Setting | Default | Purpose |
+|---|---|---|
+| `PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT` | 24 hours | How long an evaluated transform stays cached |
+| `PARTITION_TRANSFORM_PREVIEW_RATE_LIMIT` | 30 | Per-user, per-dataset preview requests per minute; the editor's preview panel runs a real query |
Review Comment:
With the default `CACHE_CONFIG` (NullCache), enabling this feature leaves previews unthrottled and probe results uncached, despite the advertised request budget and timeout; configuring only `DATA_CACHE_CONFIG` does not provide either guard. Could this document the functioning shared `CACHE_CONFIG` backend prerequisite and the fail-open throttling behavior?
##########
superset/commands/dataset/update.py:
##########
@@ -416,6 +423,146 @@ def _validate_expressions(
)
)
+ def _validate_partition_mapping(self, exceptions: list[ValidationError]) -> None:
+ """
+ Validate the dataset's partition filter mapping.
+
+ Only the blocking (Tier 1) issues become validation errors. Tier 2
+ issues -- an unparseable transform, a transform missing `:value` --
+ deliberately let the save through and leave the mapping inactive, per
+ the PRD, so a half-written transform doesn't cost the owner the rest of
+ their edits. They are surfaced by the editor, not by rejecting the PUT.
+
+ The transform is authored by a dataset owner, the same principal and
+ trust level as a calculated-column expression, so it also goes through
+ `validate_stored_expression` -- the parser gate that already governs
+ stored expressions. That gate only applies to a transform that parses:
+ it rejects an unparseable expression outright, which would turn a Tier-2
+ issue into a blocking one and undo the paragraph above. Skipping it
+ there costs nothing -- an unparseable transform is never emitted into a
+ query -- and it is not a hole for templating, because Jinja in a
+ transform is already a Tier-1 blocking issue of its own.
+
+ Every path that *reads* a mapping is gated on the feature flag, so this
+ one is too: with the flag off nothing mirrors, and rejecting a save over
+ a mapping that can never be consumed would be a validation error the
+ owner has no way to act on.
+ """
+ if not is_feature_enabled("PARTITION_FILTER_MAPPING"):
+ return
+
+ self._model = cast(SqlaTable, self._model)
+
+ columns = self._properties.get("columns")
+ column_names = (
+ {column["column_name"] for column in columns}
+ if columns is not None
+ else {column.column_name for column in self._model.columns}
+ )
+
+ partition_column = self._properties.get(
+ "partition_column", self._model.partition_column
+ )
+ partition_mapped_column = self._properties.get(
+ "partition_mapped_column", self._model.partition_mapped_column
+ )
+ main_dttm_col = self._properties.get("main_dttm_col", self._model.main_dttm_col)
+ if not partition_column:
+ return
+
+ # A column payload drops every column it omits, and `update_columns`
+ # then runs `DatasetDAO.clear_dangling_partition_mapping` to drop a
+ # mapping whose columns went with them -- but that happens later, during
+ # `run()`. Validate the state that cleanup leaves behind, or a metadata
+ # sync that legitimately removes the mapped column is rejected before
+ # the cleanup meant to handle it ever runs, which is exactly the
+ # orphaned case the cleanup exists for.
+ #
+ # Only a *stored* reference is forgiven. Asking in this very request to
+ # map onto a column the same request does not define is a mistake worth
+ # reporting, not something to quietly clean up.
+ if columns is not None:
Review Comment:
After the dedicated metadata-refresh endpoint removes a dropped partition column, its stored mapping reference remains because that writer bypasses DAO cleanup; a later description-only PUT has no columns payload and fails this validation. Could refresh repair dangling mapping references as the columns-payload update path does?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4186147475
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,1913 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate. Named so it cannot
+#: plausibly collide with a real column; a collision only makes the count
+#: disagree, which fails closed.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ return VALUE_PLACEHOLDER_RE.sub(standin, transform)
Review Comment:
For an array filter whose rendered literal contains escaped backslashes, this regex replacement changes `array('a\\nb')` into `array('a\nb')`, so ClickHouse probes a newline instead of the literal backslash sequence and the resulting partition predicate can exclude matching rows. Could the rendered SQL be substituted literally rather than interpreted as a replacement string?
##########
superset/models/helpers.py:
##########
@@ -5317,6 +5717,74 @@ def get_sqla_query( # pylint: disable=too-many-arguments,too-many-locals,too-ma
db_extra=self.db_extra,
)
+ # Hoisted above the mirror collection below, which has to
+ # record the values the real predicate *binds*. SQLAlchemy
+ # infers an `IN` bind's type from the first element, so a mixed
+ # int/float list has to be widened before binding or every
+ # later float is truncated (see #33206). The `IN` branch did
+ # this itself, 100-odd lines down and by rebinding `eq` -- so
+ # the mirror had already copied the unwidened values and probed
+ # the transform at a number the query never compares.
+ #
+ # Scoped to the operators whose branch did it, so that moving
+ # the call changes when it runs and not what it applies to:
+ # `CONTAINS_ANY`/`CONTAINS_ALL` are list targets too and were
+ # never widened.
+ if (
+ target_generic_type == utils.GenericDataType.NUMERIC
+ and op in {utils.FilterOperator.IN, utils.FilterOperator.NOT_IN}
+ and isinstance(eq, (list, tuple))
+ ):
+ eq = normalize_mixed_numbers(eq)
+
+ # Mirror onto the partition column. This single site covers
+ # ad-hoc filters, dashboard native filters and cross-filters,
+ # because they all arrive as entries in `filter`. `eq` rather
+ # than the raw `val`: it is the value the real predicate binds,
+ # which is only true because the numeric widening above now
+ # runs before this rather than inside the `IN` branch below.
+ # `TEMPORAL_RANGE` is collected in its own branch below, where
+ # the range has been resolved into a pair of bounds.
+ #
+ # A grain makes the real predicate compare the *truncated*
+ # column, so the raw value no longer describes the rows it
+ # matches: drill-to-detail sends `==` on a bucket start, which
+ # every row in the bucket satisfies once truncated. Mirroring it
+ # raw would keep only the bucket's first instant.
+ #
+ # Grained ranges do mirror, by widening (see the TEMPORAL_RANGE
+ # branch below). The same trick is deferred rather than unsafe
+ # here: `==` on a bucket would have to become a two-sided range,
+ # which needs a monotonic transform -- `EQUALS` mirrors without
+ # one today -- and a parse back into a datetime; and a grained
+ # `IN` would need a union of buckets, which this sink cannot
+ # express because its entries are AND-ed.
+ if (
+ col_obj is not None
+ and op != utils.FilterOperator.TEMPORAL_RANGE
+ and not filter_grain
+ ):
+ mirror_value: Any = eq
Review Comment:
For TIMESTAMP equality/IN filters supplied as epoch milliseconds, the handler returns SQLAlchemy expressions, but these are forwarded as bind values: probe compilation fails and silently disables partition pruning, while preview wraps the same inputs as `RawProbeValue`. Could runtime normalize these SQL-valued inputs the same way before collecting the mirror?
##########
superset/commands/dataset/importers/v1/utils.py:
##########
@@ -582,6 +668,12 @@ def import_dataset( # noqa: C901
if dataset.id is None:
db.session.flush()
+ # A bundle can name a mapped column and still carry transforms on other
+ # columns; the editor's client-side guard never runs here. Left in place, a
+ # transform on an unmirrored column is invisible and still stored, ready to
+ # go live the moment the mapped column resolves back to it.
+ DatasetDAO.clear_unmapped_partition_transforms(dataset)
Review Comment:
An overwrite import that clears the mapped-column override can activate an old transform parked on the default datetime column: omitted column fields retain their stored values, and this post-import cleanup now treats that column as effective and skips it. Could import disarm parked transforms against the old mapping before applying the new references, as `DatasetDAO.update` does?
##########
superset/datasets/schemas.py:
##########
@@ -347,6 +373,18 @@ def fix_extra(self, data: dict[str, Any], **kwargs: Any) -> dict[str, Any]:
datetime_format = fields.String(
allow_none=True, validate=[Length(1, 100), validate_python_date_format]
)
+ partition_value_transform = fields.String(
+ allow_none=True, validate=Length(1, MAX_TRANSFORM_LENGTH)
+ )
+ # `load_default` so bundles predating the field do not claim their transform
+ # preserves ordering, which would silently enable range mirroring on import.
+ # `allow_none` because the column is nullable on purpose -- the legacy
+ # datasource editor writes NULL for any field its payload omits -- and export
+ # emits every field unconditionally, so an untouched export of such a dataset
+ # carries an explicit null that import would otherwise refuse outright.
+ partition_transform_is_monotonic = fields.Boolean(
+ allow_none=True, load_default=False
+ )
uuid = fields.UUID(allow_none=True)
Review Comment:
On overwrite import, replacing a declared-monotonic transform with `hour(:value)` while omitting this field retains the old `True`: the importer discards `schema.load()`'s output and updates only supplied keys, so this safe default never reaches storage. Could the omitted declaration become false before persistence, rather than enabling range mirrors that can exclude valid rows?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #43870:
URL: https://github.com/apache/superset/pull/43870#issuecomment-5998694249
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers an incremental AI Review.
- `/review full` - Manually triggers a full AI Review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4337086623
##########
superset/datasets/schemas.py:
##########
@@ -128,6 +133,23 @@ class DatasetColumnsPutSchema(ResolveIsCertifiedMixin, Schema):
datetime_format = fields.String(
allow_none=True, validate=[Length(1, 100), validate_python_date_format]
)
+ partition_value_transform = fields.String(
+ allow_none=True,
+ validate=Length(1, MAX_TRANSFORM_LENGTH),
+ metadata={
+ "description": (
+ "SQL expression containing a :value placeholder. Filters on "
+ "this column are mirrored onto the dataset's partition column "
+ "with the value passed through this transform."
+ )
+ },
+ )
+ # Deliberately no `load_default`: `DatasetDAO.update_columns` applies the
+ # loaded payload field by field onto the stored column, so a default here
+ # would let a partial column payload clear a monotonic flag the request
+ # never mentioned -- and silently stop mirroring range filters. Absent
+ # means "unchanged"; new columns fall back to the model's own default.
+ partition_transform_is_monotonic = fields.Boolean(allow_none=True)
Review Comment:
A PUT that replaces `partition_value_transform` but omits this field keeps the old stored `True`, so the new transform is silently treated as monotonic. For example, switching `p1 = n` / `:value` to `p2 = abs(n)` / `abs(:value)` and then filtering `n >= -1` adds `p2 >= 1`, which drops the `n = 0` rows with no error. The import path resets the declaration when it replaces a transform; should the REST update reset it to False (or require it) whenever the transform changes?
##########
superset/views/datasource/utils.py:
##########
@@ -217,12 +232,85 @@ def get_samples( # pylint: disable=too-many-arguments
sample_data["page"] = page
sample_data["per_page"] = per_page
- sample_data["total_count"] = count_star_data["data"][0]["COUNT(*)"]
+ if skip_count:
+ _set_lower_bound_total(
+ sample_data, row_offset, row_limit, probed=not via_cursor
+ )
+ else:
+ sample_data["total_count"] = count_star_data["data"][0]["COUNT(*)"]
+ sample_data["total_count_is_lower_bound"] = False
return sample_data
except (IndexError, KeyError) as exc:
raise DatasetSamplesFailedError from exc
+def _count_star_query_context(
+ datasource: Datasource,
+ payload: SamplesPayloadSchema | None,
+ form_data: dict[str, Any] | None,
+ force: bool,
+) -> QueryContext:
+ count_star_metric = {
+ "metrics": [
+ {
+ "expressionType": "SQL",
+ "sqlExpression": "COUNT(*)",
+ "label": "COUNT(*)",
+ }
+ ]
+ }
+ return QueryContextFactory().create(
+ datasource={
+ "type": datasource.type,
+ "id": datasource.id,
+ },
+ queries=[{**payload, **count_star_metric} if payload else count_star_metric],
+ form_data=form_data,
+ result_type=ChartDataResultType.FULL,
+ force=force,
+ )
+
+
+def _get_count_star_data(
+ count_star_instance: QueryContext | None,
+) -> dict[str, Any]:
+ """Run the count query, or return an empty payload when it was skipped."""
+ if count_star_instance is None:
+ return {}
+
+ count_star_instance.raise_for_access()
+ count_star_data = count_star_instance.get_payload()["queries"][0]
+ if count_star_data.get("status") == QueryStatus.FAILED:
+ raise DatasetSamplesFailedError(count_star_data.get("error"))
+ return count_star_data
+
+
+def _set_lower_bound_total(
+ sample_data: dict[str, Any], row_offset: int, row_limit: int, probed: bool
+) -> None:
+ """
+ Report the total as "the rows up to and including this page".
+
+ The rows query asked for one probe row past the page. If it came back there
+ is at least one more page, so the probe is trimmed and the total flagged as
+ a lower bound; if it did not, this page is the last one and the total is
+ exact. The cursor path pages with an exact page size and has no probe row
+ (``probed=False``), so a full page is taken to mean there may be more.
+ """
+ data = sample_data.get("data") or []
+ page_size = row_limit or app.config["SAMPLES_ROW_LIMIT"]
+ if probed:
+ has_more = len(data) > page_size
+ if has_more:
+ data = data[:page_size]
+ sample_data["data"] = data
+ sample_data["rowcount"] = len(data)
+ else:
+ has_more = len(data) >= page_size
+ sample_data["total_count"] = row_offset + len(data)
Review Comment:
When the requested page is past the end, `data` is empty, so this reports `total_count = row_offset` with `total_count_is_lower_bound = False`. For a 51-row dataset, requesting page 3 at 50 per page returns an exact total of 100. An empty page doesn't establish a count, and this can also happen when rows shrink mid-pagination. Should an empty page with a non-zero offset be reported as a lower bound instead?
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/DatasourceEditor.tsx:
##########
@@ -1257,6 +1386,178 @@ function DatasourceEditor({
[],
);
+ // Which column's row expand to open, for the "map a different column" links.
+ // Consumed by the Columns tab, which scrolls the row into view and expands it.
+ //
+ // Carries a nonce because the request is an event, not a state: clicking the
+ // same link twice -- after collapsing the row by hand in between -- asks for
+ // the same column name, and a bare string would make the second
+ // `setColumnToReveal` a no-op. React would bail out of the render, nothing
+ // downstream would see a change, and the row would stay shut.
+ const [columnToReveal, setColumnToReveal] = useState<{
+ name: string;
+ nonce: number;
+ } | null>(null);
+
+ // What the mapped column's own preview said, relayed up from its row expand
+ // so the dataset-level banner cannot claim a mirror that panel has already
+ // refused. Reported rather than lifted: the transform the preview judges is
+ // the debounced local one that panel owns. `null` means no verdict yet.
+ const [previewMirrors, setPreviewMirrors] = useState<boolean | null>(null);
Review Comment:
`previewMirrors` is only ever written by the mapped row's effect, and nothing resets it when the mapping moves. Preview a transform that fails against the current partition target (say `upper(:value)` on a numeric partition column), collapse the row, then pick a compatible partition column: the row is unmounted so no new verdict is reported, and the banner keeps saying filters won't mirror. Should `handlePartitionColumnChange` (and the other mapping moves) reset this to `null`?
##########
tests/unit_tests/datasets/partition_mapping_preview_test.py:
##########
@@ -0,0 +1,1342 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+The partition mapping preview endpoint.
+
+This route fires a real warehouse query from a text input in the dataset
+editor, so the order of its guards is the point: parse and denylist checks run
+*before* anything reaches the engine, which is what keeps a half-typed
+expression from costing a query at all.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+from unittest.mock import MagicMock, patch
+
+import pytest
+from flask import Flask
+from sqlalchemy.orm.session import Session
+
+from superset import db
+
+PROBE = "superset.connectors.sqla.partition_mapping.evaluate_transform"
+
+
+@pytest.fixture(autouse=True)
+def enable_partition_filter_mapping(app: Flask) -> Any:
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = True
+ yield
+ del app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"]
+
+
+@pytest.fixture(autouse=True)
+def real_cache(app: Flask) -> Any:
+ """
+ The test app runs a null cache, which would make the rate limiter a no-op.
+ """
+ from flask_caching import Cache
+
+ from superset.extensions import cache_manager
+
+ cache = Cache(config={"CACHE_TYPE": "SimpleCache", "CACHE_DEFAULT_TIMEOUT": 300})
+ cache.init_app(app)
+ original = cache_manager._cache # noqa: SLF001
+ cache_manager._cache = cache # noqa: SLF001
+ yield
+ cache_manager._cache = original # noqa: SLF001
+
+
+@pytest.fixture(autouse=True)
+def allow_editorship(mocker: Any) -> Any:
+ """
+ The route gates on per-object editorship on top of ``@protect()``. The unit
+ test app has no real roles, so grant it here rather than in every test.
+ """
+ mocker.patch(
+ "superset.datasets.api.security_manager.raise_for_editorship",
+ )
+
+
+@pytest.fixture
+def dataset(session: Session) -> Any:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.models.core import Database
+
+ SqlaTable.metadata.create_all(db.session.get_bind())
+ database = Database(database_name="my_db", sqlalchemy_uri="sqlite://")
+ table = SqlaTable(
+ table_name="web_events",
+ database=database,
+ main_dttm_col="event_time",
+ columns=[
+ TableColumn(column_name="event_time", is_dttm=True, type="TIMESTAMP"),
+ TableColumn(column_name="dt_epoch", type="BIGINT"),
+ # A second, text-typed partition key. A transform that answers with
+ # text cannot be previewed against `dt_epoch` -- the predicate it
+ # would emit is `dt_epoch = 'us'`, which the database refuses, and
+ # `probed_value_type_error` says so before the preview can call it
+ # valid. Tests whose transform answers with text point here.
+ TableColumn(column_name="region_key", type="VARCHAR"),
+ # And a temporal one, for a transform that answers with a date or a
+ # timestamp. `region_key` will not do: the type gate holds a text
+ # key to text results, because not every engine accepts anything
+ # else in a text comparison and one of them compares it as never
+ # equal rather than refusing it.
+ TableColumn(column_name="part_ts", type="TIMESTAMP"),
+ # A text *mapped* column. A temporal one will not stand in for it:
+ # a sample that is not an ISO instant declines on a column the
+ # engine compares more coarsely than the value carries, which is
+ # the right answer there and noise in a test about anything else.
+ TableColumn(column_name="country", type="VARCHAR"),
+ ],
+ )
+ table.partition_column = "dt_epoch"
+ db.session.add(table)
+ db.session.flush()
+ return table
+
+
+def test_preview_returns_the_emitted_predicate(
+ client: Any, full_api_access: None, dataset: Any
+) -> None:
+ with patch(PROBE, return_value=[1768435200]):
+ response = client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={
+ "mapped_column": "event_time",
+ "value_transform": "unix_timestamp(:value)",
+ "sample_values": ["2026-01-15 00:00:00"],
+ },
+ )
+
+ assert response.status_code == 200
+ assert response.json["result"] == {
+ "valid": True,
+ "sample_input": "event_time == '2026-01-15 00:00:00'",
+ "emitted_predicate": "dt_epoch = 1768435200 OR dt_epoch IS NULL",
+ }
+
+
+def test_preview_mirrors_a_range_when_the_transform_is_monotonic(
+ client: Any, full_api_access: None, dataset: Any
+) -> None:
+ """
+ The case the whole feature exists for: an Explore time range bound.
+ """
+ with patch(PROBE, return_value=[1768435200]):
+ response = client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={
+ "mapped_column": "event_time",
+ "value_transform": "unix_timestamp(:value)",
+ "sample_values": ["2026-01-15 00:00:00"],
+ "operator": ">=",
+ "is_monotonic": True,
+ },
+ )
+
+ assert response.json["result"] == {
+ "valid": True,
+ "sample_input": "event_time >= '2026-01-15 00:00:00'",
+ "emitted_predicate": "dt_epoch >= 1768435200 OR dt_epoch IS NULL",
+ }
+
+
+def test_preview_shows_a_strict_bound_mirroring_non_strictly(
+ client: Any, full_api_access: None, dataset: Any
+) -> None:
+ """
+ The preview and the query path agree only because both go through
+ `build_mirrored_predicates`. A preview rendering `<` while the chart emitted
+ `<=` would be the editor claiming something the SQL does not do.
+
+ `sample_input` describes the owner's filter and `emitted_predicate` the
+ mirror, so the two carrying different operators is the behaviour under test
+ rather than a defect.
+ """
+ with patch(PROBE, return_value=[1768435200]):
+ response = client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={
+ "mapped_column": "event_time",
+ "value_transform": "unix_timestamp(:value)",
+ "sample_values": ["2026-01-15 00:00:00"],
+ "operator": "<",
+ "is_monotonic": True,
+ },
+ )
+
+ assert response.json["result"] == {
+ "valid": True,
+ "sample_input": "event_time < '2026-01-15 00:00:00'",
+ "emitted_predicate": "dt_epoch <= 1768435200 OR dt_epoch IS NULL",
+ }
+
+
+def test_preview_refuses_a_range_when_the_transform_is_not_monotonic(
+ client: Any, full_api_access: None, dataset: Any
+) -> None:
+ """
+ Refusing here rather than showing a predicate is the point: the query path
+ would not mirror this filter either, and a preview that implied otherwise
+ would be the one thing worse than no preview.
+ """
+ with patch(PROBE, side_effect=AssertionError("probe must not run")):
+ response = client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={
+ "mapped_column": "event_time",
+ "value_transform": "unix_timestamp(:value)",
+ "sample_values": ["2026-01-15 00:00:00"],
+ "operator": ">=",
+ "is_monotonic": False,
+ },
+ )
+
+ result = response.json["result"]
+ assert result["valid"] is False
+ assert "preserves ordering" in result["error"]
+
+
+def test_preview_names_the_comparison_when_text_equality_cannot_mirror(
+ client: Any, full_api_access: None, dataset: Any
+) -> None:
+ """
+ On an engine whose string comparison is not byte-exact, `=` and `IN` on a
+ text column are withdrawn whatever the owner declares about ordering. The
+ reason has to say so, or it sends them to a checkbox that changes nothing.
+ """
+ with patch.object(
+ dataset.database.db_engine_spec, "binary_string_comparison", False
+ ):
+ with patch(PROBE, side_effect=AssertionError("probe must not run")):
+ response = client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={
+ "mapped_column": "country",
+ "partition_column": "region_key",
+ "value_transform": "lower(:value)",
+ "sample_values": ["US"],
+ "operator": "IN",
+ "is_monotonic": True,
+ },
+ )
+
+ result = response.json["result"]
+ assert result["valid"] is False
+ assert result["reason"] == "operator"
+ assert "preserves ordering" not in result["error"]
+ assert "case or trailing spaces" in result["error"]
+
+
+def test_preview_mirrors_in_element_wise(
+ client: Any, full_api_access: None, dataset: Any
+) -> None:
+ """
+ Wireframe 1h: a non-temporal mapping previews as an `IN`, not as a `>=`
+ against the first value.
+ """
+ with patch(PROBE, return_value=["us", "ca"]):
+ response = client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={
+ "mapped_column": "country",
+ "partition_column": "region_key",
+ "value_transform": "lower(:value)",
+ "sample_values": ["US", "CA"],
+ "operator": "IN",
+ },
+ )
+
+ assert response.json["result"] == {
+ "valid": True,
+ "sample_input": "country IN ('US', 'CA')",
+ "emitted_predicate": "region_key IN ('us', 'ca') OR region_key IS NULL",
+ }
+
+
+def test_preview_rejects_an_operator_that_can_never_mirror(
+ client: Any, full_api_access: None, dataset: Any
+) -> None:
+ response = client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={
+ "mapped_column": "event_time",
+ "value_transform": "unix_timestamp(:value)",
+ "sample_values": ["2026-01-15 00:00:00"],
+ "operator": "NOT IN",
+ },
+ )
+
+ assert response.status_code == 400
+
+
+def test_preview_reports_a_parse_error_without_touching_the_engine(
+ client: Any, full_api_access: None, dataset: Any
+) -> None:
+ """
+ Validate first, probe second. A half-typed transform is by definition
+ unparseable, which is most of the traffic a debounced text input produces.
+ """
+ with patch(PROBE, side_effect=AssertionError("probe must not run")):
+ response = client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={
+ "mapped_column": "event_time",
+ "value_transform": "unix_timestamp(:value",
+ "sample_values": ["2026-01-15 00:00:00"],
+ },
+ )
+
+ assert response.status_code == 200
+ assert response.json["result"]["valid"] is False
+ assert response.json["result"]["error"]
+
+
+def test_preview_rejects_a_non_deterministic_transform(
+ client: Any, full_api_access: None, dataset: Any
+) -> None:
+ with patch(PROBE, side_effect=AssertionError("probe must not run")):
+ response = client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={
+ "mapped_column": "event_time",
+ "value_transform": "unix_timestamp()",
+ "sample_values": ["2026-01-15 00:00:00"],
+ },
+ )
+
+ assert response.json["result"]["valid"] is False
+
+
+def test_preview_reports_an_unknown_mapped_column(
+ client: Any, full_api_access: None, dataset: Any
+) -> None:
+ with patch(PROBE, side_effect=AssertionError("probe must not run")):
+ response = client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={
+ "mapped_column": "nope",
+ "value_transform": "unix_timestamp(:value)",
+ "sample_values": ["2026-01-15 00:00:00"],
+ },
+ )
+
+ assert response.json["result"]["valid"] is False
+
+
+def test_preview_refuses_a_transform_whose_result_the_key_cannot_hold(
+ client: Any, full_api_access: None, dataset: Any
+) -> None:
+ """
+ The one verdict a preview must never give: "Valid" for a mapping that makes
+ every chart fail. `cast(:value as text) || 'x'` evaluates perfectly, so the
+ probe succeeds -- and the preview went on to render the predicate the chart
+ would carry, `dt_epoch >= '2026-01-15 00:00:00x'` against a BIGINT, which
+ Postgres answers with a 400.
+
+ Its own `reason`, because "the database would not evaluate this" and "it
+ evaluated and answered with the wrong kind of thing" are different problems
+ and only the owner can say which transform they meant.
+ """
+ with patch(PROBE, return_value=["2026-01-15 00:00:00x"]):
+ response = client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={
+ "mapped_column": "event_time",
+ "value_transform": "cast(:value as text) || 'x'",
+ "sample_values": ["2026-01-15 00:00:00"],
+ },
+ )
+
+ assert response.status_code == 200
+ result = response.json["result"]
+ assert result["valid"] is False
+ assert result["reason"] == "type"
+ assert "dt_epoch" in result["error"]
+ assert result["sample_input"] == "event_time == '2026-01-15 00:00:00'"
+
+
+def test_preview_refuses_a_number_against_a_text_partition_key(
+ client: Any, full_api_access: None, dataset: Any
+) -> None:
+ """
+ The mirror image, and the one that used to be exempt. A text partition key
+ was held to no type at all, on the belief that every engine takes a number
+ in a text comparison -- but Postgres refuses `character varying = integer`,
+ Trino `varchar = bigint` and BigQuery `STRING = INT64`, so the preview said
+ "Valid" for a mapping whose every chart 400s.
+
+ SQLite is the reason this is a decline rather than a coercion: it raises
+ nothing and compares a number against text as never equal, so the mirror
+ would silently drop every row the filter keeps.
+ """
+ with patch(PROBE, return_value=[1768435200]):
+ response = client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={
+ "mapped_column": "event_time",
+ "partition_column": "region_key",
+ "value_transform": "unix_timestamp(:value)",
+ "sample_values": ["2026-01-15 00:00:00"],
+ },
+ )
+
+ assert response.status_code == 200
+ result = response.json["result"]
+ assert result["valid"] is False
+ assert result["reason"] == "type"
+ assert "region_key" in result["error"]
+ assert "string" in result["error"]
+
+
+def test_preview_mirrors_text_against_a_text_partition_key(
+ client: Any, full_api_access: None, dataset: Any
+) -> None:
+ """The other half: a text key still takes a transform that answers text."""
+ with patch(PROBE, return_value=["20260115"]):
+ response = client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={
+ "mapped_column": "event_time",
+ "partition_column": "region_key",
+ "value_transform": "to_char(:value, 'YYYYMMDD')",
+ "sample_values": ["2026-01-15 00:00:00"],
+ },
+ )
+
+ assert response.status_code == 200
+ result = response.json["result"]
+ assert result["valid"] is True
+ assert "'20260115'" in result["emitted_predicate"]
+
+
+def test_preview_reports_a_failed_probe_rather_than_erroring(
+ client: Any, full_api_access: None, dataset: Any
+) -> None:
+ with patch(PROBE, return_value=None):
+ response = client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={
+ "mapped_column": "event_time",
+ "value_transform": "unix_timestamp(:value)",
+ "sample_values": ["2026-01-15 00:00:00"],
+ },
+ )
+
+ assert response.status_code == 200
+ assert response.json["result"]["valid"] is False
+
+
+def test_preview_404s_for_an_unknown_dataset(
+ client: Any, full_api_access: None, dataset: Any
+) -> None:
+ response = client.post(
+ "/api/v1/dataset/99999/partition_mapping/preview/",
+ json={
+ "mapped_column": "event_time",
+ "value_transform": "unix_timestamp(:value)",
+ "sample_values": ["2026-01-15"],
+ },
+ )
+ assert response.status_code == 404
+
+
+def test_preview_is_gated_on_the_feature_flag(
+ app: Flask, client: Any, full_api_access: None, dataset: Any
+) -> None:
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = False
+
+ response = client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={
+ "mapped_column": "event_time",
+ "value_transform": "unix_timestamp(:value)",
+ "sample_values": ["2026-01-15"],
+ },
+ )
+ assert response.status_code == 404
+
+
+def test_preview_rejects_an_invalid_payload(
+ client: Any, full_api_access: None, dataset: Any
+) -> None:
+ response = client.post(
+ f"/api/v1/dataset/{dataset.id}/partition_mapping/preview/",
+ json={"nonsense": True},
+ )
+ assert response.status_code == 400
+
+
+def test_preview_is_rate_limited_per_user_and_dataset(
Review Comment:
This test is named per user and dataset, but it uses a single caller and one dataset, so removing either part of the limiter key keeps it green. If the key dropped the user, one owner exhausting the budget would 429 every other owner's editor on that dataset. Could it exhaust user A / dataset X, then assert user B on X and user A on another dataset still get 200 while A on X gets 429?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #43870:
URL: https://github.com/apache/superset/pull/43870#issuecomment-6307974558
### ⚠️ Possible DB migration conflict
@hughhhh the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
To check and, if needed, fix this:
1. Rebase this branch onto the latest `master`.
2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4343421680
##########
superset-frontend/src/dashboard/components/nativeFilters/FiltersConfigModal/FiltersConfigForm/FiltersConfigForm.tsx:
##########
@@ -1029,6 +1034,41 @@ const FiltersConfigForm = (
};
}, [datasetId, datasourceType]);
+ // A partition-mapped dataset can be large enough that listing a filter's
+ // values without a time range -- a scan of every partition -- times out, so
+ // a new filter starts with a time range on the mapped column, which is
+ // mirrored onto the partition column (see `partitionedTimeRangeColumn` for
+ // when). Applied once per dataset, so an owner who clears it is not
+ // overruled.
+ const partitionDefaultAppliedFor = useRef<number | undefined>();
+ const [partitionTimeRangeDefaulted, setPartitionTimeRangeDefaulted] =
+ useState(false);
+ useEffect(() => {
Review Comment:
The "Last week" seeding is only covered through `partitionedTimeRangeColumn`; nothing renders the form to exercise this effect. If the `filterToEdit` guard were dropped, opening an existing all-time filter on a mapped dataset would quietly add a Last week pre-filter and narrow its values, and every current test would still pass. Could a form-level test render an existing filter against an eligible mapped dataset and assert no `time_range`/`granularity_sqla` is introduced, plus a new-filter case asserting both are seeded?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,3583 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Writing the value into the probe
+--------------------------------
+The probe evaluates the transform at a *literal*, because it runs with no bound
+parameters at all -- so every value is written into SQL text by the driver's
+literal renderer and read back by the engine's lexer, and the two do not always
+agree. SQLAlchemy's default renderer doubles apostrophes and leaves backslashes
+alone; Hive honours backslash escapes and not doubling, so ``'O''Brien'`` is
+read there as two adjacent literals and ``'x\\''`` ends four characters into a
+value the filter carries whole. A disagreement is either a mirror built from a
+value nobody filtered on -- dropping rows the filter keeps -- or, where the
+value closes its own quote, an expression of the filterer's choosing running in
+the probe.
+
+Which side is right is not knowable from the driver: it is a per-session server
+setting (``standard_conforming_strings``, ``NO_BACKSLASH_ESCAPES``,
+``spark.sql.parser.escapedStringLiterals``), and SQLAlchemy's own view of it is
+only correct on a dialect that has connected. So escaping is not what makes
+this safe. `literal_round_trips` renders the literal and reads it back in the
+engine's own dialect instead, and a value that does not survive the trip is not
+mirrored -- the usual trade, pruning for correctness. `probe_sql_is_evaluable`
+re-reads the finished statement behind it.
+
+The probe's *answers* make the same trip, in the other direction. The chart
+query is compiled with ``literal_binds``, so a probed partition key is rendered
+into its SQL by the same renderer and read by the same lexer -- and
+``concat(:value, chr(92), 'b')`` turns the unremarkable input ``a`` into the key
+``a\\b``, which Hive reads back as ``a`` followed by a backspace. So
+`_predicates_from_probe` asks `literal_round_trips` about each result too, and
+declines the request rather than emitting a predicate no row can satisfy: the
+mirror is ``AND``-ed onto the query, so a mirror that matches nothing costs the
+chart its rows rather than its pruning.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: The opening and closing delimiters of each kind of Jinja block. The probe
+#: would render these in a different context at a different time from the chart
+#: query, so a transform holding one is rejected at save time.
+JINJA_BLOCK_DELIMITERS = (("{{", "}}"), ("{%", "%}"), ("{#", "#}"))
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: A PostgreSQL Unicode-escaped identifier, ``U&"..."``.
+#:
+#: The second construct that breaks the premise above, and in the same way:
+#: ``U&"\\0071uery_to_xml"(...)`` parses as an anonymous function whose name is
+#: the *literal* ``\\0071uery_to_xml``, so the function denylist is matching a
+#: name the engine never sees -- PostgreSQL decodes the escape and runs
+#: ``query_to_xml``, handing a dataset owner rows from outside their RLS scope
+#: through the preview's ``emitted_predicate``.
+#:
+#: Normalizing the escapes and re-checking would be the other repair, and is
+#: worse: it means reimplementing one engine's identifier decoding well enough
+#: to be a security boundary. Refusing the construct is exact, and costs
+#: nothing real -- a transform is a scalar function of ``:value``, and there is
+#: no reason to name a function or column through an escape sequence.
+#:
+#: Refused on every engine, like the executable comment, so a transform stored
+#: on SQLite cannot detonate when the dataset is re-pointed at PostgreSQL. The
+#: ``&`` may be separated from the ``U`` by nothing at all, but whitespace or a
+#: comment between the prefix and the string is not accepted by PostgreSQL
+#: either, so the strict form is the whole surface.
+#:
+#: Matched in raw text, so the prefix is refused inside a string literal too.
+#: That is the same trade the executable comment makes and has the same
+#: justification: a gate whose contract is to fire *before* the parse cannot
+#: ask the parse whether the text was quoted. ``concat(:value, 'u&"x"')`` is
+#: refused, which costs an owner nothing anyone writes.
+UNICODE_ESCAPED_IDENTIFIER_RE = re.compile(r'\bU&"', re.IGNORECASE)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate: a transform such as
+#: ``datediff(day, :value, LOCALTIMESTAMP)`` for a relative partition key is
+#: evaluated once and then keeps emitting yesterday's answer, so the chart
+#: silently drops rows after midnight.
+#:
+#: Matched by SQL function name, so every engine's spelling of "now" has to be
+#: named -- the ANSI four were not enough. Listed rather than delegated to the
+#: engine specs because the risk is the same everywhere and a spec that had not
+#: got round to declaring its own would fail open; a name no engine has is
+#: inert, so over-listing costs nothing.
+NON_DETERMINISTIC_FUNCTIONS = {
+ # ANSI, and the engines that spell it this way.
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "LOCALTIME",
+ "LOCALTIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+ # PostgreSQL. `now()` is statement-stable; these two are not even that.
+ "CLOCK_TIMESTAMP",
+ "STATEMENT_TIMESTAMP",
+ "TIMEOFDAY",
+ # MySQL and MariaDB.
+ "CURDATE",
+ "CURTIME",
+ "SYSDATE",
+ "UTC_DATE",
+ "UTC_TIME",
+ "UTC_TIMESTAMP",
+ "UUID_SHORT",
+ # Oracle.
+ "SYSTIMESTAMP",
+ "SYS_GUID",
+ # SQL Server.
+ "GETDATE",
+ "GETUTCDATE",
+ "SYSDATETIME",
+ "SYSUTCDATETIME",
+ "SYSDATETIMEOFFSET",
+ "NEWID",
+ # BigQuery.
+ "CURRENT_DATETIME",
+ "GENERATE_UUID",
+ # Snowflake.
+ "RANDSTR",
+ "UUID_STRING",
+ # ClickHouse.
+ "NOW64",
+ "RANDCANONICAL",
+ "GENERATEUUIDV4",
+ # H2 and Derby, which the test fixtures use.
+ "RANDOM_UUID",
+}
+
+#: The wall-clock names an engine evaluates with no parentheses at all.
+#:
+#: These parse as *column references*, not functions, so the name-based walk
+#: below cannot see them: `datediff(UTC_DATE, :value)` on MySQL and
+#: `:value - SYSDATE` on Oracle both cleared the gate and froze probe time into
+#: a cached mirror.
+#:
+#: A subset of `NON_DETERMINISTIC_FUNCTIONS` rather than the whole of it,
+#: because refusing a bare name costs an owner a column genuinely called that.
+#: Only the names SQL lets you write without ``()`` are listed -- the datetime
+#: keywords -- so `rand`, `uuid` and `newid`, which always need parentheses and
+#: are plausible column names, stay out.
+BARE_WALL_CLOCK_KEYWORDS = frozenset(
+ {
+ "current_date",
+ "current_time",
+ "current_timestamp",
+ "localtime",
+ "localtimestamp",
+ "utc_date",
+ "utc_time",
+ "utc_timestamp",
+ "sysdate",
+ "systimestamp",
+ }
+)
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+class Unmirrorable:
+ """
+ A filter no mirror can stand in for, and why.
+
+ Returned by `ExploreMixin.mirror_probe_request` for a value the engine
+ compares more coarsely than the filter carries, one it cannot render as a
+ literal, one whose rendered literal the engine would not read back as the
+ same value, one in a time frame the transform would discard, or an ``IN``
+ list with a member of any of those kinds. An object rather than `None`,
+ because `None` is a filter value in its own right.
+
+ The reason rides along because the preview has to explain the decline to
+ the owner, and the two declines want different advice: "the engine compares
+ less of this value than you typed, so map a column it compares in full" is
+ sound guidance for a `DATE` column and actively misleading for an
+ offset-bearing bound on a `TIMESTAMP` one, which already is such a column.
+ Carried rather than re-derived so the preview's explanation cannot come
+ apart from the chart path's decision.
+
+ Lives here rather than beside that method so the preview can read it too:
+ `superset.models.helpers` imports this module, so these can only cross the
+ boundary in this direction. Both callers recognise the same instances -- a
+ preview that answered "valid" for a request the chart path declines is the
+ drift this is here to prevent.
+ """
+
+ __slots__ = ("reason",)
+
+ def __init__(self, reason: str) -> None:
+ self.reason = reason
+
+ def __repr__(self) -> str:
+ return f"<Unmirrorable {self.reason}>"
+
+
+#: The ordinary decline: whatever the mirror cannot be built from, with the
+#: engine's own comparison resolution as the reason an owner can act on.
+UNMIRRORABLE = Unmirrorable("resolution")
+
+#: A value carrying a UTC offset, declined whatever the column's resolution.
+#: A transform such as ``CAST(:value AS TIMESTAMP)`` drops the offset, so even
+#: an engine that compares the whole instant would be probed in the wrong
+#: frame -- which is not something mapping a different column fixes.
+UNMIRRORABLE_OFFSET = Unmirrorable("offset")
+
+#: A value the driver and the engine would not spell the same way, declined
+#: whatever the column's resolution and whatever the operator. Nothing about
+#: the column or the transform fixes it -- see `literal_round_trips` -- so the
+#: advice the resolution reason carries would send an owner after the wrong
+#: thing entirely.
+UNMIRRORABLE_ESCAPING = Unmirrorable("escaping")
+
+
+def is_unmirrorable(value: Any) -> bool:
+ """Whether `mirror_probe_request` declined this request."""
+ return isinstance(value, Unmirrorable)
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def _native_generic_type(
+ column: "TableColumn",
+) -> utils.GenericDataType | None:
+ """
+ What the engine spec makes of ``column``'s declared type.
+
+ `TableColumn.type_generic` answers ``TEMPORAL`` for every column carrying
+ ``is_dttm``, which is the right answer for a chart's time axis and the
+ wrong one for a comparison: an epoch ``BIGINT`` is a number to the engine
+ however it is labelled here. Falls back to the flag where the spec has no
+ answer, so a type Superset cannot resolve is no worse off than before.
+ """
+ try:
+ column_spec = column.db_engine_spec.get_column_spec(
+ column.type, db_extra=column.db_extra
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ column_spec = None
+ if column_spec is not None and column_spec.generic_type is not None:
+ return column_spec.generic_type
+ try:
+ return column.type_generic
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+#: A declared type naming an array: PostgreSQL's ``TEXT[]`` / ``INTEGER[][]``
+#: / ``int[3]``, and the ``ARRAY<...>`` / ``ARRAY(...)`` / ``Array(...)``
+#: spellings of Hive, Spark, Trino, BigQuery and ClickHouse.
+#: The bracket body is written so no two runs can match the same blanks:
+#: ``\s*\d*\s*`` backtracks polynomially on a long run of spaces.
+_ARRAY_TYPE_RE = re.compile(r"(?:\[\s*(?:\d+\s*)?\])+\s*$|^\s*ARRAY\b", re.IGNORECASE)
+
+
+def declares_array_type(column_type: str | None) -> bool:
+ """
+ Whether a declared column type is an array, whatever the engine spec says.
+
+ The engine spec only reports ``MULTI_VALUE`` where it has opted into
+ ``supports_multivalue_columns``; PostgreSQL has not, and resolves ``TEXT[]``
+ to ``STRING`` and ``INTEGER[]`` to ``NUMERIC``. So an array partition column
+ there cleared the array refusal, previewed valid, and every equality chart
+ on the mapping failed with ``malformed array literal``. The declared type
+ is what the engine will compare, so it is read directly as well.
+ """
+ return bool(column_type and _ARRAY_TYPE_RE.search(column_type))
+
+
+#: Declared types whose comparison ignores trailing blanks.
+#:
+#: The fixed-width character types, which the SQL standard has compare as
+#: though both sides were padded to the same length -- so ``'US'`` and
+#: ``'US '`` are equal in a ``CHARACTER(3)``, while ``lower()`` of the two is
+#: not. Spelled out rather than matched by prefix because the variable-width
+#: names start with the same letters: ``VARCHAR`` and ``CHARACTER VARYING``
+#: compare the blanks and must not land here.
+PADDED_CHARACTER_TYPES = frozenset(
+ {
+ "CHAR",
+ "NCHAR",
+ # PostgreSQL's own name for ``CHARACTER``, which is what reflection
+ # reports for a ``CHAR(n)`` column there.
+ "BPCHAR",
+ "CHARACTER",
+ "NATIONAL CHAR",
+ "NATIONAL CHARACTER",
+ }
+)
+
+
+def _is_padded_character_type(column: TableColumn) -> bool:
+ """
+ Whether ``column``'s declared type compares without its trailing blanks.
+
+ Read off the declared type rather than the engine spec's resolved one: the
+ specs map ``CHAR`` and ``VARCHAR`` onto the same `sqlalchemy.String`, so
+ the distinction this needs is gone by then. The length suffix is dropped
+ and the name matched against `PADDED_CHARACTER_TYPES`, so an unfamiliar
+ spelling answers ``False`` and the engine-level flag decides as before --
+ this gate adds a decline rather than lifting one. A column with no
+ declared type has nothing to read, and answers the same way.
+ """
+ if not isinstance(column.type, str):
+ return False
+ native = re.sub(r"\s+", " ", column.type.strip().upper())
+ return native.split("(")[0].strip() in PADDED_CHARACTER_TYPES
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ Padding is asked about per column, because it is a property of the *type*
+ rather than of the engine. ``binary_string_comparison`` speaks for an
+ engine's default text comparison, and on PostgreSQL -- which declares it
+ -- a ``CHAR(2)`` still matches a filter for ``'US '`` against a stored
+ ``'US'``, because the standard says a padded character type compares
+ without its trailing blanks. The mirror ``region_key = lower('US ')`` then
+ excludes the row. So a fixed-width character type declines whatever the
+ engine says, and an engine that ignores trailing blanks on its *variable*
+ types says so by not declaring the flag at all (see `RedshiftEngineSpec`).
+
+ The type asked for is the engine spec's reading of the column's declared
+ type, not `TableColumn.type_generic`, which answers ``TEMPORAL`` for
+ anything carrying ``is_dttm``. A ``VARCHAR`` flagged temporal is still text
+ to the engine: on MySQL a filter for ``'2026-01-01T00:00:00'`` matches a
+ stored ``'...t00:00:00'``, while the mirror ``p = hex('...T...')`` excludes
+ it -- and asking the semantic flag skipped the check entirely.
+
+ A type the spec cannot classify declines, which is what the paragraph above
+ promises and what only the exception branch used to do. PostgreSQL's
+ ``citext`` matches no type pattern, so it answered ``None`` -- neither
+ string nor not-string -- and was waved through, which is precisely wrong
+ for a type whose whole purpose is case-insensitive comparison. Declining
+ costs the pruning; admitting it costs rows.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ # Ahead of the generic-type question, which a padded type can lose: the
+ # specs map ``CHARACTER`` onto no generic type at all on some engines, and
+ # a fixed-width character type is a string whether or not Superset can say
+ # so from the name.
+ if _is_padded_character_type(column):
+ return False
+ generic_type = _native_generic_type(column)
+ if generic_type is None:
+ return False
+ if generic_type != utils.GenericDataType.STRING:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_unicode_escaped_identifier(transform: str | None) -> bool:
+ """Whether the transform names something through a ``U&"..."`` escape.
+
+ See `UNICODE_ESCAPED_IDENTIFIER_RE`. Answered on raw text for the same
+ reason as the comment above: the parse reports a name the engine does not
+ use, which is exactly what makes the denylist blind to it.
+ """
+ return (
+ bool(transform)
+ and UNICODE_ESCAPED_IDENTIFIER_RE.search(transform or "") is not None
+ )
+
+
+#: Sequence pseudo-columns, which advance a sequence when they are *read*.
+#:
+#: ``orders_seq.NEXTVAL`` parses as a qualified column reference, not a
+#: function call, so neither `SQLStatement.is_mutating` -- which walks function
+#: names -- nor the function denylist can see it. The probe would then run
+#: ``SELECT orders_seq.NEXTVAL + 1 FROM DUAL`` and advance the sequence, again
+#: on every cache expiry, for a dataset editor holding neither SQL Lab nor a
+#: DML grant. Reading one is a write however the parser classifies it.
+#:
+#: The function spelling (``nextval('s')`` on PostgreSQL) is a different shape
+#: and is caught as a function; this is only about the suffix form.
+SEQUENCE_PSEUDO_COLUMNS = frozenset({"nextval", "currval"})
+
+#: The same thing written as a call.
+#:
+#: Only the suffix form parses as a column; `nextval('s')` on PostgreSQL and
+#: DuckDB, `NEXTVAL(s)`/`SETVAL(s, 1)` on MySQL and MariaDB, and SQL Server's
+#: `NEXT VALUE FOR s` all parse as functions. `SQLStatement.is_mutating` walks
+#: function names on PostgreSQL alone -- deliberately, since the same names are
+#: read-only elsewhere -- so every other engine let these through.
+#:
+#: Matched on the name whatever the engine, because advancing a sequence is a
+#: write wherever it happens and a transform has no reason to call one.
+SEQUENCE_FUNCTIONS = frozenset(
+ {"nextval", "setval", "next_value_for", "nextvalfor", "prevval", "lastval"}
+)
+
+
+def references_sequence(statement: SQLStatement) -> bool:
+ """Whether the statement reads or advances a sequence.
+
+ Both spellings: the pseudo-column suffix, which parses as a column (see
+ `SEQUENCE_PSEUDO_COLUMNS`), and the call, which parses as a function (see
+ `SEQUENCE_FUNCTIONS`).
+
+ Answered on the parse rather than on raw text, because position is what
+ makes it the construct: a column or alias merely *called* ``nextval`` is
+ an ordinary column, and a string literal holding the word is text.
+ """
+ return bool(
+ statement.get_column_names() & SEQUENCE_PSEUDO_COLUMNS
+ or statement.get_disallowed_functions(set(SEQUENCE_FUNCTIONS))
+ )
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """
+ Whether the transform contains a balanced Jinja block.
+
+ A block is an opening delimiter followed, anywhere later, by its closing
+ one -- the same thing ``{{.*?}}`` and its two siblings match under
+ ``re.DOTALL``. Scanned with `str.find` rather than that pattern, because a
+ lazy match retried from every opening delimiter is quadratic in a run of
+ them, and this runs on stored transforms with no length bound of its own:
+ `is_transform_active` reads whatever the column holds. The earliest opening
+ delimiter is the only one worth trying, since any closing delimiter after a
+ later one is also after it.
+ """
+ if not transform:
+ return False
+ for opening, closing in JINJA_BLOCK_DELIMITERS:
+ start = transform.find(opening)
+ if start != -1 and transform.find(closing, start + len(opening)) != -1:
+ return True
+ return False
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+
+ Three spellings have to be looked for, because one name reaches the parse
+ three ways: as a function call, as a zero-argument call a dialect resolves
+ itself, and -- for the datetime keywords -- as a bare word that parses as a
+ column reference.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ # The parenthesis-free spellings, which parse as columns rather than
+ # functions and so are invisible to the walk above. See
+ # `BARE_WALL_CLOCK_KEYWORDS`.
+ found |= {
+ name.upper() for name in BARE_WALL_CLOCK_KEYWORDS & statement.get_column_names()
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ # An array holds no scalar a transform could return, so no mirror onto it
+ # can ever compare. Refused for the mapping rather than only per value, so
+ # the Explore glyph stops promising one: a probe of ``:value`` succeeds and
+ # records a working transform, and only the later type gate declined.
+ if declares_array_type(columns_by_name[partition_column].type):
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error( # noqa: C901
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ And it must be a *read*. Shape is a separate question from effect: a bare
+ scalar expression can still write, so `SQLStatement.is_mutating` is asked
+ too -- the same question SQL Lab and the chart executor ask before letting
+ SQL run. See the gate itself for what that reaches and what it does not.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ # Also ahead of the parse, and for a stronger reason than cost: every gate
+ # below reasons about the parse tree, and this is the one construct that
+ # makes the parse tree describe a different statement from the one the
+ # engine runs. Checked here as well as in `validate_transform` because this
+ # is the door a row written by an earlier release still comes through.
+ if contains_executable_comment(transform):
+ return str(
+ _(
+ "A partition value transform cannot contain a MySQL "
+ "executable comment, which the database executes and every "
+ "validator reads as a comment."
+ )
+ )
+
+ if contains_unicode_escaped_identifier(transform):
+ return str(
+ _(
+ "A partition value transform cannot name anything through a "
+ 'U&"..." escape sequence, which the database decodes and '
+ "every validator reads literally."
+ )
+ )
+
+ # Same door, same reason: the name the denylist below would match is not
+ # the name the engine resolves. See `UNICODE_ESCAPED_IDENTIFIER_RE`.
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The read-only gate, which nothing above implies. The shape gates ask what
+ # the transform *selects*; this asks what evaluating it *does*, and a bare
+ # scalar expression can still write. `nextval(:value)` on PostgreSQL
+ # advances a sequence: one function call, no clause, no sub-query, and not
+ # in the default `DISALLOWED_SQL_FUNCTIONS` either -- so every gate above
+ # passes it and the probe then runs it. `setval` is the same shape, and
+ # `exp.Execute` and the opaque-`exp.Command` forms arrive the same way.
+ #
+ # The large-object writers (`lo_export`, `lowrite`, `lo_from_bytea`, ...)
+ # are caught here too, and the shipped denylist happens to name them as
+ # well -- but that is config an operator can replace, while this is not.
+ #
+ # `is_mutating` is the same question SQL Lab, `get_virtual_table_metadata`
+ # and the chart executor ask before letting SQL run, so a transform is held
+ # to the bar the rest of Superset already sets rather than to one invented
+ # here. Unconditional rather than gated on `Database.allow_dml`: a transform
+ # is a scalar function of `:value` by definition, so there is no legitimate
+ # mutating one, and the probe runs on a cache schedule nobody chose -- a
+ # write would repeat every time the entry expired.
+ #
+ # It bears saying what this does not reach. A user-defined function whose
+ # body writes is a plain call no parser can tell from `lower(:value)`, and
+ # `is_mutating`'s function-name walk is PostgreSQL-only by design, since the
+ # same names are read-only elsewhere. Neither residual is specific to this
+ # feature -- a dataset editor can already have the engine evaluate an
+ # arbitrary expression through a calculated column or a virtual dataset's
+ # SQL -- and closing them means authorizing the preview against the
+ # database, not parsing harder.
+ if statement.is_mutating():
+ return str(
+ _(
+ "A partition value transform cannot change data. It is "
+ "evaluated against the database to check that it mirrors, so "
+ "it has to be a read."
+ )
+ )
+
+ # Not reached by the walk above, which is why it is its own gate: a
+ # sequence pseudo-column is a *column* to the parser and a write to the
+ # engine. See `SEQUENCE_PSEUDO_COLUMNS`.
+ if references_sequence(statement):
+ return str(
+ _(
+ "A partition value transform cannot read a sequence. "
+ "NEXTVAL advances the sequence every time it is evaluated, "
+ "and the transform is evaluated on a cache schedule."
+ )
+ )
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the
+ probe uninspected. Rendering is not what makes that true: a string element
+ is checked by `literal_round_trips` before it is rendered -- the dialect's
+ literal processor and the engine's lexer do not always agree about what a
+ rendered literal says -- and `probe_sql_is_evaluable` re-reads the finished
+ query, which is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def _placeholder_is_bindable(transform: str) -> bool:
+ """
+ Whether SQLAlchemy's ``text()`` can see ``:value`` as a bound parameter.
+
+ `VALUE_PLACEHOLDER_RE` is ``:value\b``, which matches the placeholder in a
+ Postgres cast such as ``:value::bigint``. SQLAlchemy's own bind scan is
+ ``(?<![:\\w$]):([\\w$]+)(?![:\\w$])`` -- note the trailing exclusion -- so a
+ following colon stops it: ``text(":value::bigint")`` reports a parameter
+ named ``valu``, and ``.bindparams(bindparam("value"))`` then raises
+ ``ArgumentError``.
+
+ `_probe` swallows that, so the only symptom was a perfectly valid transform
+ whose mapping silently never pruned, and a preview reporting an engine
+ failure for SQL that was never sent. Every write-side gate passes the
+ transform: it parses, it is a bare expression, and the placeholder *is* in
+ an executable position.
+
+ Answered by attempting the bind itself rather than by pattern-matching
+ ``::`` or reading ``text()``'s private parameter map, so this cannot
+ disagree with what `build_probe_sql` is about to do -- on any dialect, or on
+ a SQLAlchemy whose scan changes.
+ """
+ try:
+ sa.text(transform).bindparams(sa.bindparam("value", value=None))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return False
+ return True
+
+
+def escape_foreign_colons(transform: str) -> str:
+ """
+ ``transform`` with every colon but the ``:value`` placeholder escaped.
+
+ `sqlalchemy.text` reads any ``:word`` as a bind parameter, including one
+ inside a string literal, and an unbound parameter renders as ``NULL``
+ under literal binds rather than raising. So ``:value || \':suffix\'``
+ compiled to ``'us' || 'NULL'``: the mirror asked for a partition value no
+ row holds and the chart dropped rows, with no error for `_probe` to
+ swallow and nothing on screen to say so.
+
+ Escaped rather than refused, because a colon in a literal is ordinary --
+ ``concat(:value, \':\', region)`` builds a composite key -- and the
+ placeholder is the only colon this module means to interpret. `text()`
+ reads ``\\:`` as a literal colon.
+
+ Only the bound path needs this. A `RawProbeValue` or an unbindable
+ placeholder is substituted as text by `parse_skeleton`, which never hands
+ the transform to `text()` at all.
+ """
+ pieces: list[str] = []
+ cursor = 0
+ for match in VALUE_PLACEHOLDER_RE.finditer(transform):
+ pieces.append(transform[cursor : match.start()].replace(":", r"\:"))
+ pieces.append(match.group(0))
+ cursor = match.end()
+ pieces.append(transform[cursor:].replace(":", r"\:"))
+ return "".join(pieces)
+
+
+def literal_round_trips(value: Any, dialect: Dialect | None, engine: str) -> bool:
+ """
+ Whether the engine reads a rendered ``value`` back as that same value.
+
+ The probe runs with no bound parameters, so every value reaches the engine
+ as literal text the driver wrote (see `build_probe_sql`). Whether that text
+ says what the value says is a question about two independent spellings: the
+ driver's escaping, and the engine's lexer. SQLAlchemy's default renderer
+ doubles apostrophes and passes backslashes through; Hive and Spark honour
+ the backslash and not the doubling, so ``'O''Brien'`` is read there as two
+ adjacent literals -- the transform is evaluated at ``OBrien``, and the
+ mirror asks for a partition key that holds none of the rows the filter
+ keeps. The same gap in the other direction lets a value close its own quote
+ and have the rest of it read as SQL.
+
+ Escaping is not the repair. Whether a backslash introduces an escape is a
+ per-session server setting -- ``standard_conforming_strings`` on Postgres,
+ ``NO_BACKSLASH_ESCAPES`` on MySQL, ``escapedStringLiterals`` on Spark -- and
+ nothing in the engine specs exposes it. SQLAlchemy reads it off the server
+ into ``_backslash_escapes`` during ``initialize(connection)``, which the
+ probe's dialect never reaches: `_dialect_for` asks the ``Database`` for a
+ dialect, not for a connection, so Postgres renders ``a\\b`` as
+ ``'a\\\\b'`` and a server with the standard setting reads four
+ characters. An engine-spec flag would have to be defaulted, and either
+ default is wrong for a dozen engines: one leaves the hole open, the other
+ corrupts the probed value.
+
+ So the premise is verified rather than declared, the way
+ `probe_sql_is_evaluable` verifies the finished statement. A value that does
+ not survive the round trip is not mirrored, which costs the query its
+ pruning and nothing else.
+
+ The short-circuit is a proof, not a guess, and it matters for cost: a
+ 200-member ``IN`` list would otherwise parse 200 times on the chart path.
+ If the renderer emitted the value between two quotes and changed nothing in
+ it, and the value carries neither a quote nor a backslash, then no lexer in
+ play can read it as anything but itself. Both exclusions are load-bearing:
+ on Hive ``a\\b`` renders verbatim and reads as ``a`` followed by a
+ backspace.
+
+ :param value: a filter value about to be rendered into the probe
+ :param dialect: the dialect that will render it, as `_dialect_for` reports
+ :param engine: ``database.backend``, whose lexer reads the result
+ :return: whether the two agree about what the literal says
+ """
+ if isinstance(value, RawProbeValue):
+ # Already SQL, with no single value for a parse to be compared against:
+ # its elements are checked before they are rendered, by
+ # `ExploreMixin._array_mirror_probe_value`. A backslash surviving into
+ # the finished text is refused here all the same, as the backstop for a
+ # renderer this module does not own.
+ return "\\" not in value.sql
+ if not isinstance(value, str):
+ # Numbers and instants are not written between delimiters, so there is
+ # no escaping for the two sides to disagree about.
+ return True
+
+ rendered = _compile_literal(sa.literal(value), dialect)
+ if rendered == f"'{value}'" and "'" not in value and "\\" not in value:
+ return True
+
+ try:
+ return (
+ SQLStatement(f"SELECT {rendered}", engine).get_select_literal_value()
+ == value
+ )
+ except SupersetParseError:
+ # A rendered literal the engine's own dialect will not parse is the
+ # strongest form of disagreement there is.
+ return False
+
+
+def value_round_trips(database: Database, value: Any) -> bool:
+ """
+ `literal_round_trips` for a caller holding a database, not a dialect.
+
+ Which renderer and which lexer apply is this module's business, so the two
+ callers outside it -- the chart path's own gate in
+ `ExploreMixin.mirror_probe_request` and the mapping summary Explore reads
+ -- ask in these terms and stay out of it.
+
+ :param database: the database whose driver renders and whose engine reads
+ :param value: a filter value about to be rendered into the probe
+ :return: whether the two agree about what the literal says
+ """
+ return literal_round_trips(value, _dialect_for(database), database.backend)
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text. That is not itself a boundary:
+ the processor's escaping is not always the escaping the engine honours, and
+ a value can close its own quote through the gap. The boundary is
+ `literal_round_trips` on the way in -- which callers must have run, like
+ `stored_expression_error` below -- and `probe_sql_is_evaluable` on the way
+ out.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ bindable = _placeholder_is_bindable(transform)
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ elif bindable:
+ # Every other colon escaped first: `text()` would read one inside a
+ # string literal as a second bind parameter and render it `NULL`.
+ # See `escape_foreign_colons`.
+ clause = sa.text(escape_foreign_colons(transform)).bindparams(
+ sa.bindparam("value", value=value)
+ )
+ rendered = _compile_literal(clause, dialect)
+ else:
+ # `text()` cannot see the placeholder (see
+ # `_placeholder_is_bindable`), so the value is rendered by the
+ # dialect's own literal processor first and substituted as SQL
+ # text. The same two steps in the other order: binding exists to
+ # get the value through that processor, and `_compile_literal`
+ # inlines the result either way, so this is the same string by a
+ # different route -- not a loosening of the "never interpolate a
+ # raw value" rule. `parse_skeleton` substitutes literally, so the
+ # rendered literal arrives here exactly as it was rendered, which
+ # is what makes `literal_round_trips`' verdict on it good for this
+ # branch as much as for the bound one.
+ rendered = parse_skeleton(
+ transform, _compile_literal(sa.literal(value), dialect)
+ )
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Five things have to hold, and all five are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+ * No comment, anywhere. A value that closes its own quote has to hide the
+ text `build_probe_sql` appended after it, and a comment is the only way
+ to do that and still balance the quotes -- so this is what makes the
+ alias check above sufficient rather than merely necessary. Read off the
+ parse rather than the text, so a comment *inside* a literal is data and
+ costs no pruning, and so the question is asked in the engine's own
+ dialect. A transform has no legitimate reason to carry one either; see
+ `EXECUTABLE_COMMENT_RE`.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ # Before the parse, because this gate's whole contract is that what the
+ # parse describes is what the engine will run, and an executable comment is
+ # precisely the text where that stops being true. The transform is already
+ # refused for carrying one; this covers the compiled statement, so no later
+ # change to how values are rendered can reintroduce it behind the gates
+ # below.
+ if contains_executable_comment(sql) or contains_unicode_escaped_identifier(sql):
+ return False
+
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if not isinstance(statement, SQLStatement):
+ # A dialect whose statements this gate cannot take apart -- KQL -- gets
+ # no probe rather than an unchecked one. It never had one: the clause
+ # inspection below is implemented for SQL statements only, and the
+ # alternative to declining here is an `AttributeError` that `_probe`
+ # swallows into the same outcome, less legibly.
+ return False
+ if statement.has_comment():
+ return False
+ if statement.has_subquery():
+ return False
+ if statement.get_clause_names() - {"from"}:
+ return False
+ if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+ """
+ The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+ Parsed rather than string-compared so that the comparison in
+ `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+ not parse answers ``None``, which no statement carrying a FROM can match --
+ the probe then declines, which is the right way for an unreadable engine
+ constant to fail.
+ """
+ if not from_suffix.strip():
+ return None
+ try:
+ return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+ except SupersetParseError:
+ return None
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ # The value side of the premise `probe_sql_is_evaluable` checks on the
+ # finished statement: a value the driver and the engine would spell
+ # differently is not probed at all -- see `literal_round_trips`.
+ #
+ # `ExploreMixin.mirror_probe_request` declines one earlier, with a reason
+ # the preview can explain, and that is the gate an owner sees. This is the
+ # one that cannot be walked around. `_collect_partition_mirror_range`
+ # appends its bounds into the sink without passing through that method at
+ # all, and both paths can hand back a value the gate never saw: on a column
+ # carrying a `python_date_format`, what is probed is
+ # `strftime(that format)` -- text no mapping gate has ever read.
+ #
+ # Above `_run_probe` on purpose. This is a property of one input, not of
+ # the transform, and a verdict recorded here would withdraw the mirror for
+ # every later value of a transform the engine evaluates perfectly well.
+ dialect = _dialect_for(database)
+ if not all(
+ literal_round_trips(value, dialect, database.backend) for value in distinct
+ ):
+ logger.warning(
+ "A filter value is not written the same way by the driver and the "
+ "database, so the partition transform is not probed at it; this "
+ "query will not prune"
+ )
+ return None
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+
+ The verdict is about the *transform*: whether the engine evaluated it at
+ all. A ``NULL`` among the results is not that -- it is this input's answer,
+ and `NULLIF(:value, 0)` returning ``NULL`` for ``n = 0`` says nothing about
+ the same transform on ``n = 2``. Counting it withdrew the promise for the
+ whole transform, and nothing restored it: a *failed* probe is deliberately
+ not cached, so the next chart re-probes and re-records, but a ``NULL`` is a
+ successful probe and *is* cached -- so the false verdict outlived every
+ later hit, and the editor reported a working mapping as not mirroring
+ while the query went on pruning. The per-input skip still happens where it
+ belongs, in the caller's own ``NULL`` guard.
+
+ A probe where *every* input answers ``NULL`` is different only when it is
+ all the evidence there is. ``trunc(..., 'HH')`` on Hive returns ``NULL`` for
+ any input, and recording that as a working transform left Explore's glyph
+ promising a partition predicate no query carried. So an all-``NULL`` probe
+ records ``False`` -- but never over a stored ``True``, which some other
+ input earned and the ``NULLIF`` case above must keep. A later probe that
+ answers anything restores ``True`` the ordinary way: a fresh input misses
+ the probe cache, so it re-records.
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ if values is None:
+ mirrors = False
+ elif any(value is not None for value in values):
+ mirrors = True
+ elif known_mirror_verdict(database, catalog, schema, transform) is not True:
+ mirrors = False
+ else:
+ return values
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=mirrors,
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ from_suffix = database.db_engine_spec.select_without_from_suffix
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ from_suffix,
+ )
+ if not probe_sql_is_evaluable(
+ sql, database.backend, len(distinct), from_suffix
+ ):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
Review Comment:
On a cold probe cache this `get_df` runs inside the chart task's cancellation capture, which only keeps the first cursor it is handed. On PostgreSQL that first cursor is the probe's backend session, so aborting or timing out the chart task cancels an already-finished probe connection while the actual chart query keeps running on the warehouse. Could the probe run outside the task's cancel-id sink (or restore it afterwards) so the chart query's cursor is the one captured?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "hughhhh (via GitHub)" <gi...@apache.org>.
hughhhh commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4319674560
##########
superset/models/helpers.py:
##########
@@ -5317,6 +5633,43 @@ def get_sqla_query( # pylint: disable=too-many-arguments,too-many-locals,too-ma
db_extra=self.db_extra,
)
+ # Mirror onto the partition column. This single site covers
+ # ad-hoc filters, dashboard native filters and cross-filters,
+ # because they all arrive as entries in `filter`. `eq` rather
+ # than the raw `val`: it is the value the real predicate uses.
+ # `TEMPORAL_RANGE` is collected in its own branch below, where
+ # the range has been resolved into a pair of bounds.
+ #
+ # A grain makes the real predicate compare the *truncated*
+ # column, so the raw value no longer describes the rows it
+ # matches: drill-to-detail sends `==` on a bucket start, which
+ # every row in the bucket satisfies once truncated. Mirroring it
+ # raw would keep only the bucket's first instant.
+ #
+ # Grained ranges do mirror, by widening (see the TEMPORAL_RANGE
+ # branch below). The same trick is deferred rather than unsafe
+ # here: `==` on a bucket would have to become a two-sided range,
+ # which needs a monotonic transform -- `EQUALS` mirrors without
+ # one today -- and a parse back into a datetime; and a grained
+ # `IN` would need a union of buckets, which this sink cannot
+ # express because its entries are AND-ed.
+ if (
+ col_obj is not None
+ and op != utils.FilterOperator.TEMPORAL_RANGE
+ and not filter_grain
+ ):
+ # Window-independent, so both sinks get it. The subquery
+ # filters a different time window but the same everything
+ # else, and this filter is in `where_clause_and` for both.
+ for sink in (partition_mirror, partition_mirror_inner):
+ self._collect_partition_mirror_filter(
Review Comment:
Fixed. `_in_column_number_type` probes at the value the column would hold rather than the value as submitted, so the mirror is taken at the same comparator the original predicate normalizes to.
##########
superset/models/helpers.py:
##########
@@ -5041,6 +5688,26 @@ def get_sqla_query( # pylint: disable=too-many-arguments,too-many-locals,too-ma
)
if _main_dttm_filter is not None:
time_filters.append(_main_dttm_filter)
+ # This block filters `main_dttm_col`, a *different* column
+ # from `dttm_col`. Checking only `dttm_col` below would miss
+ # it when the mapping tracks the main datetime column.
+ self._collect_partition_mirror_range(
+ partition_mapping,
+ partition_mirror,
+ self.main_dttm_col,
+ from_dttm,
+ to_dttm,
+ )
+ if not db_engine_spec.time_groupby_inline:
+ # Only where the subquery actually gets a time filter
+ # -- see the longer note on the `dttm_col` mirror below.
+ self._collect_partition_mirror_range(
+ partition_mapping,
+ partition_mirror_inner,
Review Comment:
Fixed. The `main_dttm_col` mirror is collected for the outer query only, with no inner counterpart — the subquery's time predicate is built on `dttm_col`, which that branch has already established is a different column, so there is no inner time predicate for a mirror to stand in for.
##########
superset/models/helpers.py:
##########
@@ -5317,6 +5717,74 @@ def get_sqla_query( # pylint: disable=too-many-arguments,too-many-locals,too-ma
db_extra=self.db_extra,
)
+ # Hoisted above the mirror collection below, which has to
+ # record the values the real predicate *binds*. SQLAlchemy
+ # infers an `IN` bind's type from the first element, so a mixed
+ # int/float list has to be widened before binding or every
+ # later float is truncated (see #33206). The `IN` branch did
+ # this itself, 100-odd lines down and by rebinding `eq` -- so
+ # the mirror had already copied the unwidened values and probed
+ # the transform at a number the query never compares.
+ #
+ # Scoped to the operators whose branch did it, so that moving
+ # the call changes when it runs and not what it applies to:
+ # `CONTAINS_ANY`/`CONTAINS_ALL` are list targets too and were
+ # never widened.
+ if (
+ target_generic_type == utils.GenericDataType.NUMERIC
+ and op in {utils.FilterOperator.IN, utils.FilterOperator.NOT_IN}
+ and isinstance(eq, (list, tuple))
+ ):
+ eq = normalize_mixed_numbers(eq)
+
+ # Mirror onto the partition column. This single site covers
+ # ad-hoc filters, dashboard native filters and cross-filters,
+ # because they all arrive as entries in `filter`. `eq` rather
+ # than the raw `val`: it is the value the real predicate binds,
+ # which is only true because the numeric widening above now
+ # runs before this rather than inside the `IN` branch below.
+ # `TEMPORAL_RANGE` is collected in its own branch below, where
+ # the range has been resolved into a pair of bounds.
+ #
+ # A grain makes the real predicate compare the *truncated*
+ # column, so the raw value no longer describes the rows it
+ # matches: drill-to-detail sends `==` on a bucket start, which
+ # every row in the bucket satisfies once truncated. Mirroring it
+ # raw would keep only the bucket's first instant.
+ #
+ # Grained ranges do mirror, by widening (see the TEMPORAL_RANGE
+ # branch below). The same trick is deferred rather than unsafe
+ # here: `==` on a bucket would have to become a two-sided range,
+ # which needs a monotonic transform -- `EQUALS` mirrors without
+ # one today -- and a parse back into a datetime; and a grained
+ # `IN` would need a union of buckets, which this sink cannot
+ # express because its entries are AND-ed.
+ if (
+ col_obj is not None
+ and op != utils.FilterOperator.TEMPORAL_RANGE
+ and not filter_grain
+ ):
+ mirror_value: Any = eq
Review Comment:
Fixed. `_as_probe_input` runs first, so engine SQL from `filter_values_handler` arrives as a `RawProbeValue` that `build_probe_sql` substitutes rather than binds — the same wrapping preview applies.
##########
superset/models/helpers.py:
##########
@@ -5602,6 +5831,11 @@ def get_sqla_query( # pylint: disable=too-many-arguments,too-many-locals,too-ma
# col_obj is None and sqla_col is None - column not found!
# Silently skip - this can happen for removed columns or invalid filters
pass
+ if partition_mapping is not None:
+ where_clause_and += self._build_partition_mirror_predicates(
Review Comment:
Fixed. Each window builds its own bounds: the inner sink is collected with `inner_from_dttm or from_dttm` and `inner_to_dttm or to_dttm`, so a relative-comparison subquery no longer ranks one window's rows against another window's partition keys.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(explore): indicate when a filter is mirrored onto a partition column [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r3939838584
##########
superset-frontend/src/explore/components/PartitionPruningIndicator/index.tsx:
##########
@@ -0,0 +1,80 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { t } from '@apache-superset/core/translation';
+import { css, useTheme } from '@apache-superset/core/theme';
+import { Icons, Tooltip } from '@superset-ui/core/components';
+import type { PartitionFilterMapping } from '@superset-ui/chart-controls';
+
+interface PartitionPruningIndicatorProps {
+ /** The dataset's mapping summary, straight off the datasource payload. */
+ mapping?: PartitionFilterMapping | null;
+}
+
+/**
+ * The glyph on a filter whose column is mirrored onto a partition column
+ * (wireframe 1d).
+ *
+ * Chart authors do not configure any of this and ideally never learn the word
+ * "partition"; the indicator exists only to explain why their query got faster,
+ * and to point at the generated SQL where the extra predicate is visible.
+ */
+export default function PartitionPruningIndicator({
+ mapping,
+}: PartitionPruningIndicatorProps) {
+ const theme = useTheme();
+
+ if (!mapping?.active) {
+ return null;
+ }
+
+ return (
+ <Tooltip
+ placement="top"
+ title={t(
+ 'This filter is also applied to a partition column for faster queries. See "View query" for the generated SQL.',
+ )}
+ >
+ <span data-test="partition-pruning-indicator">
+ <Icons.FilterOutlined
+ iconSize="s"
+ iconColor={theme.colorSuccess}
+ css={css`
+ margin-left: ${theme.sizeUnit}px;
+ vertical-align: middle;
+ `}
+ />
+ </span>
+ </Tooltip>
+ );
+}
+
+/**
+ * Whether a filter on `columnName` is the one being mirrored.
+ *
+ * The mapping names exactly one mapped column, so anything else on the chart --
+ * including other filters on the same dataset -- gets no indicator.
+ */
+export function isMirroredColumn(
+ mapping: PartitionFilterMapping | null | undefined,
+ columnName: string | null | undefined,
+): boolean {
+ return Boolean(
+ mapping?.active && columnName && mapping.mapped_column === columnName,
+ );
Review Comment:
This labels every active mapped-column filter as mirrored, but the query path also rejects unsupported operators (and range filters for non-monotonic transforms). For example, a `country != 'US'` chip gets the glyph even though no partition predicate is emitted. Could this consume an applicability contract that includes the operator and monotonicity?
##########
superset-frontend/src/explore/components/controls/DateFilterControl/DateFilterLabel.tsx:
##########
@@ -406,7 +408,12 @@ export default function DateFilterLabel(props: DateFilterControlProps) {
{...props}
onDescriptionHoverChange={setIsDescriptionHovered}
/>
- {popoverContent}
+ {/* The glyph sits outside the popover trigger so clicking it opens the
+ tooltip rather than the time-range editor. */}
+ <Flex align="center" gap={theme.sizeUnit}>
+ {popoverContent}
+ <PartitionPruningIndicator mapping={props.partitionMapping} />
Review Comment:
Agreed—the standalone time control renders any active mapping even for `No filter` or a different temporal column, so the query has no matching partition predicate. Could this gate the glyph on an actual mapped time range?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4202688638
##########
superset/models/helpers.py:
##########
@@ -4292,36 +4389,621 @@ def dttm_sql_literal(self, dttm: datetime, col: "TableColumn") -> str:
return f"""'{dttm.strftime("%Y-%m-%d %H:%M:%S.%f")}'"""
- def get_time_filter( # pylint: disable=too-many-arguments # noqa: C901
+ def _mirror_probe_value(self, dttm: datetime, col: Optional["TableColumn"]) -> Any:
+ """
+ ``dttm`` in the mapped column's own stored representation.
+
+ The predicate this mirror stands in for compares the column against
+ `dttm_sql_literal(dttm, col)`, so the transform has to be probed with
+ the same value. On a column stored as an epoch integer, ``T`` is a
+ function of an integer: probing it with a `datetime` either returns
+ something unrelated to the partition keys or raises, and a raise costs
+ the dataset its pruning silently.
+
+ Only the ``python_date_format`` branches of `dttm_sql_literal` are
+ reproduced, because only those produce a *value*. `convert_dttm` yields
+ engine-specific SQL text, which cannot be bound as a parameter; its own
+ divergence from the probe is handled by widening the bounds instead.
+ """
+ if col is None:
+ return dttm
+
+ tf = col.python_date_format
Review Comment:
The mirror is probed with `dttm.strftime(tf)` whenever a `python_date_format` is set, but `dttm_sql_literal` hands the filter's own bound to `convert_dttm` first and only falls back to the format when the engine returns nothing. For a TIMESTAMP mapped column that also carries a `%Y%m%d` format (via the column or `python_date_format_by_column_name`), `event_time >= '2026-01-01 00:00:00'` is mirrored as `partition_col >= '20260101'`, so a January 15 row whose key is `2026-01-15` compares below it and is dropped from a chart the filter would keep. Should this use the same precedence as `dttm_sql_literal`, so the format is applied only when `convert_dttm` yields nothing?
##########
tests/unit_tests/connectors/sqla/partition_mapping_test.py:
##########
@@ -0,0 +1,1973 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Unit tests for ``superset.connectors.sqla.partition_mapping``."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from decimal import Decimal
+from importlib import import_module
+from typing import Any, cast
+from unittest.mock import MagicMock, patch, PropertyMock
+
+import pandas as pd
+import pytest
+from dateutil.relativedelta import relativedelta
+from flask import Flask
+from sqlalchemy.dialects import mysql, postgresql
+
+from superset.config import DISALLOWED_SQL_FUNCTIONS
+from superset.connectors.sqla.models import SqlaTable, TableColumn
+from superset.connectors.sqla.partition_mapping import (
+ _probe_cache_key,
+ _render_literal,
+ build_probe_sql,
+ contains_jinja,
+ contains_value_placeholder,
+ equality_mirrors_safely,
+ evaluate_transform,
+ find_non_deterministic_functions,
+ grain_bucket_width,
+ GRAIN_BUCKET_WIDTHS,
+ is_bare_expression,
+ is_parseable,
+ is_transform_active,
+ is_unfinished,
+ known_mirror_verdict,
+ MappingValidationIssue,
+ mirror_operator,
+ MIRRORABLE_ALWAYS,
+ MIRRORABLE_IF_MONOTONIC,
+ mirrorable_operators,
+ parse_error_detail,
+ placeholder_is_executable,
+ probe_sql_is_evaluable,
+ probed_value_type_error,
+ RawProbeValue,
+ resolve_partition_mapping,
+ stored_expression_error,
+ validate_partition_mapping,
+ validate_transform,
+)
+from superset.constants import TimeGrain
+from superset.db_engine_specs.base import BaseEngineSpec
+from superset.db_engine_specs.oracle import OracleEngineSpec
+from superset.models.core import Database
+from superset.utils.core import FilterOperator
+
+
+@pytest.fixture(autouse=True)
+def real_probe_cache(app: Flask) -> Any:
+ """
+ The test app runs a null cache, which would make every cache assertion here
+ vacuously pass. Swap in a real in-memory one for the duration.
+ """
+ from flask_caching import Cache
+
+ from superset.extensions import cache_manager
+
+ cache = Cache(config={"CACHE_TYPE": "SimpleCache", "CACHE_DEFAULT_TIMEOUT": 300})
+ cache.init_app(app)
+ original = cache_manager._cache # noqa: SLF001
+ cache_manager._cache = cache # noqa: SLF001
+ yield
+ cache_manager._cache = original # noqa: SLF001
+
+
+@pytest.fixture(autouse=True)
+def enable_partition_filter_mapping(app: Flask) -> Any:
+ """The feature ships off; every test here exercises it on."""
+ original = app.config["DEFAULT_FEATURE_FLAGS"].get("PARTITION_FILTER_MAPPING")
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = True
+ yield
+ if original is None:
+ del app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"]
+ else:
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = original
+
+
+def _table(**kwargs: Any) -> SqlaTable:
+ database = Database(database_name="test_db", sqlalchemy_uri="sqlite://")
+ defaults: dict[str, Any] = {
+ "table_name": "web_events",
+ "database": database,
+ "main_dttm_col": "event_time",
+ "columns": [
+ TableColumn(column_name="event_time", is_dttm=True, type="TIMESTAMP"),
+ TableColumn(
+ column_name="dt_epoch",
+ type="BIGINT",
+ partition_value_transform=None,
+ ),
+ TableColumn(column_name="country", type="VARCHAR"),
+ TableColumn(column_name="region_key", type="VARCHAR"),
+ ],
+ }
+ defaults.update(kwargs)
+ return SqlaTable(**defaults)
+
+
+def _mapped_table(
+ *,
+ partition_column: str = "dt_epoch",
+ mapped_column: str = "event_time",
+ transform: str | None = "unix_timestamp(:value)",
+ monotonic: bool = True,
+ partition_mapped_column: str | None = None,
+ main_dttm_col: str | None = "event_time",
+) -> SqlaTable:
+ table = _table(main_dttm_col=main_dttm_col)
+ table.partition_column = partition_column
+ table.partition_mapped_column = partition_mapped_column
+ for column in table.columns:
+ if column.column_name == mapped_column:
+ column.partition_value_transform = transform
+ column.partition_transform_is_monotonic = monotonic
+ return table
+
+
+# ---------------------------------------------------------------------------
+# §2 — operator safety matrix
+# ---------------------------------------------------------------------------
+
+
+def test_equality_and_in_are_always_mirrorable() -> None:
+ """``=`` and ``IN`` are safe for any function ``T``."""
+ assert MIRRORABLE_ALWAYS == {FilterOperator.EQUALS, FilterOperator.IN}
+
+
+def test_range_operators_require_a_monotonic_transform() -> None:
+ assert MIRRORABLE_IF_MONOTONIC == {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+ }
+
+
+def test_mirrorable_operators_excludes_ranges_when_not_monotonic() -> None:
+ assert mirrorable_operators(is_monotonic=False) == MIRRORABLE_ALWAYS
+
+
+def test_mirrorable_operators_includes_ranges_when_monotonic() -> None:
+ assert mirrorable_operators(is_monotonic=True) == (
+ MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+ )
+
+
+@pytest.mark.parametrize(
+ "operator",
+ [
+ FilterOperator.NOT_EQUALS,
+ FilterOperator.NOT_IN,
+ FilterOperator.LIKE,
+ FilterOperator.ILIKE,
+ FilterOperator.NOT_LIKE,
+ FilterOperator.NOT_ILIKE,
+ FilterOperator.IS_NULL,
+ FilterOperator.IS_NOT_NULL,
+ FilterOperator.IS_TRUE,
+ FilterOperator.IS_FALSE,
+ ],
+)
+def test_negations_and_pattern_matches_are_never_mirrorable(
+ operator: FilterOperator,
+) -> None:
+ """
+ ``T`` is not injective, so ``col != v`` does **not** imply ``T(col) != T(v)``:
+ mirroring it would drop rows the original filter keeps.
+ """
+ assert operator not in mirrorable_operators(is_monotonic=True)
+
+
+def test_equality_is_dropped_when_the_engine_does_not_compare_byte_exactly() -> None:
+ """
+ "Safe for any function ``T``" reasons about value equality: ``T`` is a
+ function, so ``col = v`` gives ``T(col) = T(v)``. The engine reasons about
+ *SQL* equality, and the two part company under a case-insensitive
+ collation -- a stored ``'us'`` satisfies a filter for ``'US'`` while the
+ mirror ``hex('US')`` excludes the row, and the chart loses it silently.
+ """
+ assert mirrorable_operators(is_monotonic=False, equality_is_safe=False) == set()
+
+
+def test_ranges_survive_an_unsafe_equality() -> None:
+ """
+ Range mirroring already rests on the owner declaring ``T``
+ order-preserving with respect to the column's own order -- an assertion
+ about the very comparison semantics this gate checks for. Equality has no
+ such declaration behind it, which is why only equality is withdrawn.
+ """
+ assert (
+ mirrorable_operators(is_monotonic=True, equality_is_safe=False)
+ == MIRRORABLE_IF_MONOTONIC
+ )
+
+
+@pytest.mark.parametrize(
+ "operator,expected",
+ [
+ (FilterOperator.GREATER_THAN, FilterOperator.GREATER_THAN_OR_EQUALS),
+ (FilterOperator.LESS_THAN, FilterOperator.LESS_THAN_OR_EQUALS),
+ (
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ ),
+ (FilterOperator.LESS_THAN_OR_EQUALS, FilterOperator.LESS_THAN_OR_EQUALS),
+ (FilterOperator.EQUALS, FilterOperator.EQUALS),
+ (FilterOperator.IN, FilterOperator.IN),
+ ],
+)
+def test_a_strict_bound_mirrors_non_strictly(
+ operator: FilterOperator, expected: FilterOperator
+) -> None:
+ """
+ Order-preserving means non-decreasing, not injective, so ``col < v``
+ implies only ``T(col) <= T(v)``. A day-key transform maps a whole day onto
+ one value and a strict mirror drops the boundary bucket. The non-strict
+ cases are already safe and pass through, which is what makes applying this
+ twice harmless.
+ """
+ assert mirror_operator(operator) == expected
+
+
+def test_relaxing_a_bound_stays_inside_the_mirrorable_set() -> None:
+ """
+ The substitution is about strictness, not about which filters mirror. The
+ Explore indicator reads `mirrorable_operators`, so leaving that set alone is
+ what keeps the glyph from promising pruning the SQL does not do -- and it is
+ also what guarantees `handle_comparison_filter` is never handed an operator
+ it has no case for.
+ """
+ assert {
+ mirror_operator(operator) for operator in MIRRORABLE_IF_MONOTONIC
+ } <= MIRRORABLE_IF_MONOTONIC
+
+
+def _column(type_: str) -> TableColumn:
+ database = Database(database_name="t", sqlalchemy_uri="sqlite://")
+ table = SqlaTable(table_name="t", database=database)
+ return TableColumn(column_name="c", type=type_, table=table)
+
+
+@pytest.mark.parametrize(
+ "type_, binary, expected",
+ [
+ ("VARCHAR", True, True),
+ ("VARCHAR", False, False),
+ # Numeric and temporal comparison is exact everywhere.
+ ("BIGINT", False, True),
+ ("TIMESTAMP", False, True),
+ ("DOUBLE", False, True),
+ ],
+)
+def test_equality_mirrors_safely_only_guards_string_columns(
+ app: Flask, type_: str, binary: bool, expected: bool
+) -> None:
+ class _Spec(BaseEngineSpec):
+ binary_string_comparison = binary
+
+ with app.app_context():
+ assert equality_mirrors_safely(_column(type_), _Spec) is expected
+
+
+def test_equality_mirrors_safely_fails_closed_on_an_unresolvable_type(
+ app: Flask,
+) -> None:
+ """
+ The gate exists to stop a silent wrong answer, so a column whose type it
+ cannot read is treated as the risky case rather than waved through.
+ """
+ column = MagicMock()
+ type(column).type_generic = PropertyMock(side_effect=ValueError("no type"))
+
+ with app.app_context():
+ assert equality_mirrors_safely(column, BaseEngineSpec) is False
+
+
+def test_no_mapped_column_leaves_the_matrix_alone(app: Flask) -> None:
+ """Nothing to reason about, and the resolver bails out on it anyway."""
+ with app.app_context():
+ assert equality_mirrors_safely(None, BaseEngineSpec) is True
+
+
+@pytest.mark.parametrize(
+ "module, spec_name",
+ [
+ ("presto", "PrestoEngineSpec"),
+ ("hive", "HiveEngineSpec"),
+ ("trino", "TrinoEngineSpec"),
+ ("impala", "ImpalaEngineSpec"),
+ ("postgres", "PostgresEngineSpec"),
+ ("bigquery", "BigQueryEngineSpec"),
+ ("sqlite", "SqliteEngineSpec"),
+ ],
+)
+def test_the_byte_exact_engines_opt_in(module: str, spec_name: str) -> None:
+ """
+ The engines this feature targets compare text byte-exactly, so the gate
+ must not cost them the second canonical mapping (`lower(:value)` onto a
+ lowercased key).
+ """
+ spec = getattr(import_module(f"superset.db_engine_specs.{module}"), spec_name)
+ assert spec.binary_string_comparison is True
+
+
+@pytest.mark.parametrize("module, spec_name", [("mysql", "MySQLEngineSpec")])
+def test_a_case_insensitive_engine_does_not_opt_in(module: str, spec_name: str) -> None:
+ """
+ MySQL's default collation is `utf8mb4_0900_ai_ci`, which is exactly the
+ case the reviewer raised.
+ """
+ spec = getattr(import_module(f"superset.db_engine_specs.{module}"), spec_name)
+ assert spec.binary_string_comparison is False
+
+
+def test_the_base_spec_does_not_opt_in() -> None:
+ """A spec that has not said so does not mirror string equality."""
+ assert BaseEngineSpec.binary_string_comparison is False
+
+
+# ---------------------------------------------------------------------------
+# Time grain bucket widths
+# ---------------------------------------------------------------------------
+
+
+@pytest.mark.parametrize("grain", list(TimeGrain))
+def test_every_builtin_grain_has_a_known_bucket_width(
+ app: Flask, grain: TimeGrain
+) -> None:
+ """
+ The widening is only sound for a grain whose bucket width we know, so a
+ grain added upstream without a width here would silently stop mirroring.
+ This is the test that notices.
+ """
+ with app.app_context():
+ assert grain_bucket_width(grain.value, "sqlite") is not None
+
+
+def test_a_calendar_grain_widens_by_a_calendar_month(app: Flask) -> None:
+ """A month is not thirty days, and the month it lands in decides its width."""
+ with app.app_context():
+ width = grain_bucket_width(TimeGrain.MONTH.value, "sqlite")
+
+ assert width is not None
+ assert datetime(2026, 1, 31) + width == datetime(2026, 2, 28)
+ assert datetime(2026, 2, 1) + width == datetime(2026, 3, 1)
+
+
+def test_a_fractional_grain_has_a_width(app: Flask) -> None:
+ """
+ ``PT0.5H`` and ``P0.25Y`` are why the widths are written out rather than
+ parsed -- and the anchored week grains are intervals ``parse_duration``
+ rejects outright.
+ """
+ with app.app_context():
+ assert grain_bucket_width(TimeGrain.HALF_HOUR.value, "sqlite") == relativedelta(
+ minutes=30
+ )
+ assert grain_bucket_width(
+ TimeGrain.WEEK_ENDING_SATURDAY.value, "sqlite"
+ ) == relativedelta(days=7)
+
+
+def test_an_unknown_grain_has_no_known_width(app: Flask) -> None:
+ with app.app_context():
+ assert grain_bucket_width("P13X", "sqlite") is None
+ assert grain_bucket_width(None, "sqlite") is None
+
+
+def test_an_addon_grain_has_no_known_width(app: Flask) -> None:
+ """An operator-declared grain carries whatever duration string they typed."""
+ with app.app_context():
+ app.config["TIME_GRAIN_ADDONS"] = {"PT2S": "2 second"}
+ try:
+ assert grain_bucket_width("PT2S", "sqlite") is None
+ finally:
+ app.config["TIME_GRAIN_ADDONS"] = {}
+
+
+def test_a_builtin_grain_an_operator_redefined_has_no_known_width(
+ app: Flask,
+) -> None:
+ """
+ ``TIME_GRAIN_ADDON_EXPRESSIONS`` replaces a built-in grain's SQL for one
+ engine, so its duration no longer bounds the displacement *there* -- but it
+ still does on every other engine.
+ """
+ with app.app_context():
+ app.config["TIME_GRAIN_ADDON_EXPRESSIONS"] = {
+ "sqlite": {"P1D": "DATETIME({col}, 'start of year')"}
+ }
+ try:
+ assert grain_bucket_width(TimeGrain.DAY.value, "sqlite") is None
+ assert grain_bucket_width(TimeGrain.DAY.value, "hive") is not None
+ finally:
+ app.config["TIME_GRAIN_ADDON_EXPRESSIONS"] = {}
+
+
+def test_the_width_table_is_keyed_on_grain_durations(app: Flask) -> None:
+ """Keys are the ISO duration a filter carries, not the enum member name."""
+ assert GRAIN_BUCKET_WIDTHS[TimeGrain.DAY] == relativedelta(days=1)
+ assert set(GRAIN_BUCKET_WIDTHS) == {grain.value for grain in TimeGrain}
+
+
+# ---------------------------------------------------------------------------
+# §4.1 — resolving the effective mapping, and the defensive bail-outs
+# ---------------------------------------------------------------------------
+
+
+def test_resolve_returns_the_mapping_when_everything_lines_up(app: Flask) -> None:
+ with app.app_context():
+ mapping = resolve_partition_mapping(_mapped_table())
+
+ assert mapping is not None
+ assert mapping.partition_column == "dt_epoch"
+ assert mapping.mapped_column == "event_time"
+ assert mapping.value_transform == "unix_timestamp(:value)"
+ assert mapping.is_monotonic is True
+
+
+def test_effective_mapped_column_follows_main_dttm_col(app: Flask) -> None:
+ """No explicit override: the mapping follows the default datetime column."""
+ with app.app_context():
+ mapping = resolve_partition_mapping(_mapped_table())
+
+ assert mapping is not None
+ assert mapping.mapped_column == "event_time"
+
+
+def test_explicit_override_wins_over_main_dttm_col(app: Flask) -> None:
+ table = _mapped_table(
+ mapped_column="country",
+ transform="lower(:value)",
+ monotonic=False,
+ partition_mapped_column="country",
+ )
+ table.partition_column = "region_key"
+
+ with app.app_context():
+ mapping = resolve_partition_mapping(table)
+
+ assert mapping is not None
+ assert mapping.mapped_column == "country"
+ assert mapping.partition_column == "region_key"
+ assert mapping.is_monotonic is False
+
+
+def test_resolve_returns_none_when_the_feature_flag_is_off(app: Flask) -> None:
+ table = _mapped_table()
+ with app.app_context():
+ with patch(
+ "superset.connectors.sqla.partition_mapping.feature_flag_manager."
+ "is_feature_enabled",
+ return_value=False,
+ ):
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_without_a_partition_column(app: Flask) -> None:
+ table = _mapped_table()
+ table.partition_column = None
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_partition_column_no_longer_exists(
+ app: Flask,
+) -> None:
+ """A column sync can drop the physical partition column out from under us."""
+ table = _mapped_table()
+ table.partition_column = "dt_epoch_gone"
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_the_mapped_column_no_longer_exists(
+ app: Flask,
+) -> None:
+ table = _mapped_table(main_dttm_col="vanished")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_on_self_mapping(app: Flask) -> None:
+ """
+ ``partition_column == effective mapped column`` mirrors a column onto itself.
+ Save-time validation rejects it, but rows predating that validation exist.
+ """
+ table = _mapped_table(
+ partition_column="event_time",
+ mapped_column="event_time",
+ )
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+@pytest.mark.parametrize("transform", [None, "", " "])
+def test_resolve_returns_none_without_a_transform(
+ app: Flask, transform: str | None
+) -> None:
+ table = _mapped_table(transform=transform)
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_the_transform_lacks_the_placeholder(
+ app: Flask,
+) -> None:
+ table = _mapped_table(transform="unix_timestamp(event_time)")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_for_a_non_deterministic_transform(app: Flask) -> None:
+ """
+ The query-time gate is `is_transform_active`, the same one the Explore
+ indicator reads. Anything narrower would let a transform that reached
+ storage without passing `UpdateDatasetCommand` -- through import, or a
+ hand-written bundle -- mirror a filter with a value frozen at probe time,
+ while the editor reported the mapping as inactive and nothing on screen
+ said otherwise.
+ """
+ table = _mapped_table(transform="unix_timestamp(:value) + rand()")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_for_a_multi_expression_transform(app: Flask) -> None:
+ """A select list is not an expression; the probe cannot align its columns."""
+ table = _mapped_table(transform="lower(:value), 'x'")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_for_an_unparseable_transform(app: Flask) -> None:
+ table = _mapped_table(transform="unix_timestamp(:value")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_the_mapped_column_has_an_advanced_data_type(
+ app: Flask,
+) -> None:
+ """
+ ``translate_filter`` builds its own predicate shape from *translated* values,
+ so the ``(operator, value)`` pair the operator matrix reasons about does not
+ exist. Mirroring anyway would silently apply the wrong values (§4.1).
+ """
+ table = _mapped_table()
+ for column in table.columns:
+ if column.column_name == "event_time":
+ column.advanced_data_type = "port"
+
+ with app.app_context():
+ with patch.dict(app.config["ADVANCED_DATA_TYPES"], {"port": MagicMock()}):
+ with patch(
+ "superset.connectors.sqla.partition_mapping.feature_flag_manager."
+ "is_feature_enabled",
+ side_effect=lambda flag: (
+ flag in {"PARTITION_FILTER_MAPPING", "ENABLE_ADVANCED_DATA_TYPES"}
+ ),
+ ):
+ assert resolve_partition_mapping(table) is None
+
+
+def test_advanced_data_type_does_not_block_when_the_flag_is_off(app: Flask) -> None:
+ """An inert ``advanced_data_type`` is not a reason to skip mirroring."""
+ table = _mapped_table()
+ for column in table.columns:
+ if column.column_name == "event_time":
+ column.advanced_data_type = "port"
+
+ with app.app_context():
+ with patch(
+ "superset.connectors.sqla.partition_mapping.feature_flag_manager."
+ "is_feature_enabled",
+ side_effect=lambda flag: flag == "PARTITION_FILTER_MAPPING",
+ ):
+ assert resolve_partition_mapping(table) is not None
+
+
+# ---------------------------------------------------------------------------
+# §5 — transform inspection helpers
+# ---------------------------------------------------------------------------
+
+
+@pytest.mark.parametrize(
+ "transform,expected",
+ [
+ ("unix_timestamp(:value)", True),
+ ("lower(:value)", True),
+ ("CAST(:value AS BIGINT)", True),
+ ("unix_timestamp(event_time)", False),
+ (":values", False),
+ ("", False),
+ (None, False),
+ ],
+)
+def test_contains_value_placeholder(transform: str | None, expected: bool) -> None:
+ assert contains_value_placeholder(transform) is expected
+
+
+@pytest.mark.parametrize(
+ "transform,expected",
+ [
+ ("unix_timestamp(:value)", False),
+ ("{{ current_username() }}", True),
+ ("lower({% if x %}:value{% endif %})", True),
+ ("lower(:value) -- {# comment #}", True),
+ ],
+)
+def test_contains_jinja(transform: str, expected: bool) -> None:
+ assert contains_jinja(transform) is expected
+
+
+@pytest.mark.parametrize(
+ "transform",
+ [
+ "unix_timestamp(:value)",
+ "lower(:value)",
+ "CAST(:value AS BIGINT)",
+ "date_format(:value, 'yyyyMMdd')",
+ ],
+)
+def test_pure_transforms_report_no_non_deterministic_functions(
+ transform: str,
+) -> None:
+ assert find_non_deterministic_functions(transform, "hive") == set()
+
+
+@pytest.mark.parametrize(
+ "transform,expected_name",
+ [
+ ("date_diff(:value, now())", "NOW"),
+ ("CAST(:value AS BIGINT) + rand()", "RAND"),
+ ("CAST(:value AS DATE) - current_date", "CURRENT_DATE"),
+ ],
+)
+def test_non_deterministic_functions_are_reported(
+ transform: str, expected_name: str
+) -> None:
+ """
+ The probe runs at a different moment and in a different session from the
+ chart query, and its result is cached, so anything time- or
+ randomness-dependent freezes a snapshot of probe time into the predicate.
+ """
+ assert expected_name in find_non_deterministic_functions(transform, "hive")
+
+
+def test_niladic_unix_timestamp_is_rejected_but_the_unary_form_is_not() -> None:
+ """
+ On Hive/Impala ``unix_timestamp()`` means "now" while ``unix_timestamp(x)``
+ -- the canonical temporal transform -- is pure. The distinction is the whole
+ reason this check inspects arity rather than just the name.
+ """
+ assert find_non_deterministic_functions("unix_timestamp(:value)", "hive") == set()
+ assert find_non_deterministic_functions(
+ "unix_timestamp(:value) - unix_timestamp()", "hive"
+ )
+
+
+# ---------------------------------------------------------------------------
+# §4.2 — probe evaluation
+# ---------------------------------------------------------------------------
+
+
+def _database_returning(values: list[Any]) -> Database:
+ """A real ``Database`` (so the dialect is real) with only ``get_df`` stubbed."""
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ return_value=pd.DataFrame(
+ [values], columns=[f"v{i}" for i in range(len(values))]
+ )
+ )
+ return database
+
+
+def _database_returning_frame(frame: pd.DataFrame) -> Database:
+ """
+ ``_database_returning`` for a probe result whose column dtypes matter.
+
+ The flat-list sibling builds its frame from one Python list, so pandas
+ infers a single dtype and the row-versus-cell distinction cannot be seen.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ return_value=frame
+ )
+ return database
+
+
+def _probe(database: Database) -> MagicMock:
+ """
+ The stubbed ``get_df``, typed for call assertions.
+
+ ``Database.get_df`` is a real method, so mypy reads its declared signature
+ rather than the mock that replaced it and rejects ``.call_args`` and
+ friends.
+ """
+ return cast(MagicMock, database.get_df)
+
+
+def test_evaluate_transform_returns_one_value_per_input(app: Flask) -> None:
+ database = _database_returning([1767225600, 1769904000])
+
+ with app.app_context():
+ result = evaluate_transform(
+ database,
+ None,
+ "default",
+ "unix_timestamp(:value)",
+ ["2026-01-01 00:00:00", "2026-02-01 00:00:00"],
+ )
+
+ assert result == [1767225600, 1769904000]
+ _probe(database).assert_called_once()
+
+
+def test_evaluate_transform_binds_values_rather_than_interpolating(
+ app: Flask,
+) -> None:
+ """
+ Filter values are attacker-controlled (a Gamma user picks them), so they must
+ be bound and escaped, never pasted into the probe SQL.
+ """
+ database = _database_returning(["o''brien"])
+
+ with app.app_context():
+ evaluate_transform(database, None, None, "lower(:value)", ["O'Brien"])
+
+ sql = _probe(database).call_args.kwargs["sql"]
+ assert "O'Brien" not in sql
+ assert "O''Brien" in sql
+
+
+def test_evaluate_transform_dedupes_repeated_values(app: Flask) -> None:
+ """Three inputs, two distinct: the probe evaluates the transform twice."""
+ database = _database_returning(["us", "us"])
+
+ with app.app_context():
+ result = evaluate_transform(
+ database, None, None, "lower(:value)", ["US", "US", "us"]
+ )
+
+ assert result == ["us", "us", "us"]
+ sql = _probe(database).call_args.kwargs["sql"]
+ assert sql.count("lower") == 2
+
+
+def test_evaluate_transform_fails_open_on_a_short_result_row(app: Flask) -> None:
+ """A row narrower than the probe asked for means the results cannot be
+ aligned back to their inputs; pruning is skipped rather than guessed at."""
+ database = _database_returning(["us"])
+
+ with app.app_context():
+ assert (
+ evaluate_transform(database, None, None, "lower(:value)", ["US", "CA"])
+ is None
+ )
+
+
+def test_evaluate_transform_fails_open_on_a_wide_result_row(app: Flask) -> None:
+ """
+ Too many columns is the dangerous direction. A transform whose select list
+ holds two expressions returns 2N columns for N inputs, and reading the first
+ N interleaves the expressions instead of taking one per value -- a predicate
+ built from the wrong values rather than one that is merely short. Here
+ `lower('US'), 'x', lower('CA'), 'x'` would have yielded `('us', 'x')` and
+ dropped every CA row.
+ """
+ database = _database_returning(["us", "x", "ca", "x"])
+
+ with app.app_context():
+ assert (
+ evaluate_transform(database, None, None, "lower(:value), 'x'", ["US", "CA"])
Review Comment:
`lower(:value), 'x'` is refused by `stored_expression_error` (not a single expression) before `get_df` is ever called, so the four-column frame this mock returns is never consumed and `None` comes back for a different reason. Changing the width guard in `_probe` from `!=` to `<` would leave this test green, even though that is the interleaving case the docstring describes. Could this use a valid transform such as `lower(:value)` with the same oversized frame, and assert that `get_df` ran once and the result is `None`?
##########
superset/views/datasource/views.py:
##########
@@ -157,6 +203,18 @@ def save(self) -> FlaskResponse:
),
status=409,
)
+ # `partition_value_transform` rides in on `update_from_object`, which
+ # writes every field in `update_from_object_fields` straight onto the
+ # column. That bypasses `UpdateDatasetCommand`, and with it the gate
+ # the REST PUT and the mapping preview both apply -- so without this
+ # the deprecated endpoint is a way to store arbitrary SQL that the
+ # partition probe later runs. Refused rather than dropped, unlike the
+ # importer: this is one interactive edit whose author is present to
+ # correct it, not a bundle where failing the whole dataset over one
+ # expression is the worse trade.
+ if error := _partition_transform_error(orm_datasource, datasource_dict):
Review Comment:
The legacy save now refuses an unsafe transform, but `partition_column` and `partition_mapped_column` ride in through `update_from_object` with no reference check. With the flag on, a payload carrying `partition_column: "missing_column"` is stored and returns 200, and every later `PUT /api/v1/dataset/<pk>` (even a description-only one) then fails `_validate_partition_mapping` with a column-not-found error until someone repairs the reference. Should this endpoint run the same mapping-reference validation as `UpdateDatasetCommand` before writing?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4198455452
##########
superset/commands/dataset/refresh.py:
##########
@@ -72,6 +72,22 @@ def run(self) -> Model:
ex.message,
)
+ # `fetch_metadata` writes the columns itself rather than going through
+ # `DatasetDAO.update`, so neither of the mapping's own repairs runs. It
+ # can drop the column `partition_column` names -- leaving a reference
+ # that fails `UpdateDatasetCommand`'s validation on every later edit,
+ # including a description-only PUT, which carries no columns payload and
+ # so cannot reach the branch that forgives a stored-only dangle -- and
+ # it can *set* `main_dttm_col`, which moves the effective mapped column
+ # and can bring a parked transform live.
+ #
+ # No flush needed to read the columns: `fetch_metadata` reassigns the
+ # relationship, so the surviving set is already correct in memory.
+ DatasetDAO.clear_dangling_partition_mapping(
+ self._model, {column.column_name for column in self._model.columns}
+ )
+ DatasetDAO.clear_unmapped_partition_transforms(self._model)
Review Comment:
A metadata refresh can switch on a transform nobody chose: if `fetch_metadata` or the dangling-reference repair above changes which column is mapped, this cleanup runs against the new mapping only, so a transform parked on the newly mapped column survives while the previously mapped column's real transform is erased (`DatasetDAO.update` runs the cleanup against both resolutions for this reason). For example, a dropped `partition_mapped_column` falls back to `main_dttm_col`, and an epoch transform parked there starts adding `dt_epoch >= …` to its filters, dropping rows that don't match. `test_refresh_disarms_a_transform_the_new_default_datetime_column_holds` asserts that survival. Could the cleanup run before the metadata change as well, so it also applies to the old mapping?
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/PartitionColumnFields.tsx:
##########
@@ -0,0 +1,319 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { useMemo } from 'react';
+import { t } from '@apache-superset/core/translation';
+import { css, useTheme } from '@apache-superset/core/theme';
+import { Alert } from '@apache-superset/core/components';
+import {
+ Button,
+ Flex,
+ Icons,
+ InfoTooltip,
+ Label,
+ Select,
+ Tooltip,
+ Typography,
+} from '@superset-ui/core/components';
+import {
+ mappedColumnIsImplicit,
+ mappingIsActive,
+ partitionMappingErrors,
+ resolveMappedColumn,
+ suggestedMappedColumn,
+} from './utils';
+import type {
+ PartitionMappingColumn,
+ PartitionMappingDatasource,
+ PartitionMappingIssue,
+} from './types';
+
+interface PartitionColumnFieldsProps {
+ datasource: PartitionMappingDatasource;
+ /**
+ * Physical columns: what the partition-column dropdown may offer, and where
+ * a replacement mapped column may be suggested from. A calculated column
+ * belongs in neither -- the engine cannot partition on an expression, and
+ * the mapping picker only renders on a physical column's row.
+ */
+ columns: PartitionMappingColumn[];
+ /**
+ * Every column on the dataset, physical and calculated. What *exists* is a
+ * different question from what may be picked, and validation asks the first:
+ * the backend accepts a calculated column as the mapped-column override, so
+ * checking existence against the physical columns alone reported a column
+ * that is really there as missing -- and blocked Save with no way out, since
+ * the dropdown cannot offer it back.
+ */
+ allColumns: PartitionMappingColumn[];
+ onPartitionColumnChange: (columnName: string | null) => void;
+ /** Open the given column's row expand in the Columns table. */
+ onNavigateToColumn: (columnName: string) => void;
+ /**
+ * Whether the mapped column's own preview says the transform mirrors, or
+ * `null`/undefined when no verdict is in yet. The checks this section can
+ * make are all static -- a transform the database rejects clears every one
+ * of them -- so without the preview's answer the banner claimed a speed-up
+ * the query never delivers.
+ */
+ previewMirrors?: boolean | null;
+}
+
+/**
+ * "Partition column" and the computed "Maps to partition" (wireframes 1a, 1g).
+ *
+ * "Maps to partition" is deliberately read-only. It reflects
+ * `partition_mapped_column ?? main_dttm_col`, and a peer dropdown would let it
+ * drift from the default datetime column silently. The only way to override it
+ * is from the target column's own row, where a transform has to be supplied
+ * alongside.
+ */
+export default function PartitionColumnFields({
+ datasource,
+ columns,
+ allColumns,
+ onPartitionColumnChange,
+ onNavigateToColumn,
+ previewMirrors,
+}: PartitionColumnFieldsProps) {
+ const theme = useTheme();
+
+ const options = useMemo(
+ () =>
+ columns.map(column => ({
+ value: column.column_name,
+ label: column.column_name,
+ customLabel: (
+ <Flex align="center" gap={theme.sizeUnit}>
+ <span>{column.column_name}</span>
+ {column.type && <Label>{column.type}</Label>}
+ </Flex>
+ ),
+ })),
+ [columns, theme.sizeUnit],
+ );
+
+ const mappedColumn = resolveMappedColumn(datasource);
+ const isImplicit = mappedColumnIsImplicit(datasource);
+ // The static checks are necessary, not sufficient: an unparseable expression
+ // or a function the database does not have needs the engine to spot, and the
+ // mapped column's row already asks it. Deferring to that answer where there
+ // is one is what keeps this banner and that panel from contradicting each
+ // other. A stored transform whose last probe failed says the same thing
+ // through the datasource's own summary, which is what an owner sees on
+ // reopening the editor.
+ const isActive =
+ mappingIsActive(datasource, allColumns) &&
+ previewMirrors !== false &&
Review Comment:
`datasource.partition_filter_mapping?.evaluable !== false` is the summary from when the editor opened, so it vetoes a successful edit: reopen a dataset whose stored `no_such_fn(:value)` has `evaluable: false`, replace it with `unix_timestamp(:value)`, get `preview.valid: true`, and the banner still says nothing will mirror (and the copy at line 267 reads "No value transform is set" for a transform that is set but failed). Could the stored verdict only apply while the transform is unchanged from the stored one?
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/DatasourceEditor.tsx:
##########
@@ -1250,6 +1373,143 @@ function DatasourceEditor({
[],
);
+ // Which column's row expand to open, for the "map a different column" links.
+ // Consumed by the Columns tab, which scrolls the row into view and expands it.
+ //
+ // Carries a nonce because the request is an event, not a state: clicking the
+ // same link twice -- after collapsing the row by hand in between -- asks for
+ // the same column name, and a bare string would make the second
+ // `setColumnToReveal` a no-op. React would bail out of the render, nothing
+ // downstream would see a change, and the row would stay shut.
+ const [columnToReveal, setColumnToReveal] = useState<{
+ name: string;
+ nonce: number;
+ } | null>(null);
+
+ // What the mapped column's own preview said, relayed up from its row expand
+ // so the dataset-level banner cannot claim a mirror that panel has already
+ // refused. Reported rather than lifted: the transform the preview judges is
+ // the debounced local one that panel owns. `null` means no verdict yet.
+ const [previewMirrors, setPreviewMirrors] = useState<boolean | null>(null);
+
+ const handlePartitionColumnChange = useCallback(
+ (columnName: string | null) => {
+ setDatasource(prev => ({
+ ...prev,
+ partition_column: columnName,
+ partition_mapped_column: nextMappedColumnOverride(
+ prev.partition_mapped_column,
+ columnName,
+ ),
+ }));
+ if (columnName) {
+ setDatabaseColumns(prev =>
+ applyPartitionColumnDefaults(prev, columnName),
+ );
+ }
+ },
+ [],
+ );
+
+ const handleNavigateToColumn = useCallback((columnName: string) => {
+ setActiveTabKey(TABS_KEYS.COLUMNS);
Review Comment:
`handleNavigateToColumn` sets `activeTabKey`, but the tabs only receive `defaultActiveKey`, which antd ignores after mount, so clicking *Customize the value transform* from the Calculated columns tab leaves the user on that tab while the hidden Columns table's search and reveal state change. The regression test clicks from the Columns tab, so it can't see this. Could the tabs be controlled with `activeKey={activeTabKey}`?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2338 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error(
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the probe
+ uninspected -- string elements are escaped by the dialect's own literal
+ processor. `probe_sql_is_evaluable` then re-reads the finished query, which
+ is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ else:
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
Review Comment:
A transform such as `:value::bigint` passes validation (`:value\b` matches) but never binds here: SQLAlchemy's `text()` does not treat a name followed by `::` as a bind parameter, so `.bindparams(sa.bindparam("value", ...))` raises, `_probe` swallows it, and a filter on the mapped column never gets a mirror. Preview also reports an engine failure for that transform before any SQL is sent. Should the placeholder be substituted the same way validation finds it (or `::` casts be rejected with a clear message)?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2338 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error(
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the probe
+ uninspected -- string elements are escaped by the dialect's own literal
+ processor. `probe_sql_is_evaluable` then re-reads the finished query, which
+ is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ else:
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ rendered = _compile_literal(clause, dialect)
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Four things have to hold, and all four are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if not isinstance(statement, SQLStatement):
+ # A dialect whose statements this gate cannot take apart -- KQL -- gets
+ # no probe rather than an unchecked one. It never had one: the clause
+ # inspection below is implemented for SQL statements only, and the
+ # alternative to declining here is an `AttributeError` that `_probe`
+ # swallows into the same outcome, less legibly.
+ return False
+ if statement.has_subquery():
+ return False
+ if statement.get_clause_names() - {"from"}:
+ return False
+ if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+ """
+ The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+ Parsed rather than string-compared so that the comparison in
+ `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+ not parse answers ``None``, which no statement carrying a FROM can match --
+ the probe then declines, which is the right way for an unreadable engine
+ constant to fail.
+ """
+ if not from_suffix.strip():
+ return None
+ try:
+ return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+ except SupersetParseError:
+ return None
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=values is not None and not any(value is None for value in values),
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ from_suffix = database.db_engine_spec.select_without_from_suffix
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ from_suffix,
+ )
+ if not probe_sql_is_evaluable(
+ sql, database.backend, len(distinct), from_suffix
+ ):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
Review Comment:
The probe cache key covers the database record but not the identity the warehouse runs the query as, so with impersonation or a `DB_CONNECTION_MUTATOR` that picks per-user accounts, a cache hit hands user B the values a transform computed under user A's permissions, and preview echoes them in `emitted_predicate`. For example, on Oracle a transform wrapping `DBMS_XMLGEN.GETXML('select secret from vault …')` (not in `DISALLOWED_SQL_FUNCTIONS`) previewed by an account that can read `vault` is then served to one that cannot. Should the key include the effective execution user, or should caching be skipped for connections whose identity varies per user?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2338 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error(
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the probe
+ uninspected -- string elements are escaped by the dialect's own literal
+ processor. `probe_sql_is_evaluable` then re-reads the finished query, which
+ is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ else:
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ rendered = _compile_literal(clause, dialect)
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Four things have to hold, and all four are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if not isinstance(statement, SQLStatement):
+ # A dialect whose statements this gate cannot take apart -- KQL -- gets
+ # no probe rather than an unchecked one. It never had one: the clause
+ # inspection below is implemented for SQL statements only, and the
+ # alternative to declining here is an `AttributeError` that `_probe`
+ # swallows into the same outcome, less legibly.
+ return False
+ if statement.has_subquery():
+ return False
+ if statement.get_clause_names() - {"from"}:
+ return False
+ if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+ """
+ The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+ Parsed rather than string-compared so that the comparison in
+ `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+ not parse answers ``None``, which no statement carrying a FROM can match --
+ the probe then declines, which is the right way for an unreadable engine
+ constant to fail.
+ """
+ if not from_suffix.strip():
+ return None
+ try:
+ return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+ except SupersetParseError:
+ return None
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=values is not None and not any(value is None for value in values),
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ from_suffix = database.db_engine_spec.select_without_from_suffix
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ from_suffix,
+ )
+ if not probe_sql_is_evaluable(
+ sql, database.backend, len(distinct), from_suffix
+ ):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _mirror_verdict_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str:
+ """
+ `_probe_cache_key` without the values.
+
+ Whether a transform can be evaluated at all is a property of the transform
+ and the connection, not of the filter that happened to be probing it, so
+ one chart's answer settles the question for the next one.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_verdict:{digest}"
+
+
+def record_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ *,
+ mirrors: bool,
+) -> None:
+ """
+ Remember whether this transform produced a mirror, for the UI to read.
+
+ Advisory only. Nothing in the query path consults it: a probe that failed
+ once is retried on the next chart exactly as it is today, because declining
+ to prune for a whole cache timeout over one transient engine blip is the
+ trade `evaluate_transform` deliberately refuses -- see the comment where it
+ declines to cache a failure.
+
+ What this is for is the *claim*. `is_transform_active` parses the transform
+ and no more, so a transform the database rejects -- a misspelled function
+ is the common case -- is "active", and the editor's banner and Explore's
+ pruning glyph promise a speed-up that never happens. A promise is exactly
+ the thing that may be withheld on one bad answer and restored on a good
+ one, which is why this is a separate entry from the probe's own results
+ rather than a relaxation of that rule.
+
+ Written by `_run_probe`, so the preview endpoint -- which shares the
+ evaluator -- settles the question before the owner has even saved.
+ """
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(
+ _mirror_verdict_cache_key(database, catalog, schema, transform),
+ mirrors,
+ timeout=timeout,
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform verdict", exc_info=True)
+
+
+def known_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> bool | None:
+ """
+ The last verdict `record_mirror_verdict` stored, or `None` if there is none.
+
+ `None` is the honest answer on a cold cache and is deliberately not `False`:
+ reporting a working mapping as broken until something probes it would
+ trade one wrong claim for another. The alternative -- probing from the
+ read side -- would put a warehouse round trip on every Explore and
+ dashboard load, and a failing transform is not cached at all, so it would
+ be a round trip every single time.
+ """
+ try:
+ verdict = cache_manager.cache.get(
+ _mirror_verdict_cache_key(database, catalog, schema, transform)
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return verdict if isinstance(verdict, bool) else None
+
+
+def _compile_literal(element: Any, dialect: Dialect | None) -> str:
+ """
+ Compile with inline literals, undoing the paramstyle's percent doubling.
+
+ Both ``TextClause`` and literal compilation run the dialect's
+ ``post_process_text``, which doubles every ``%`` whenever the identifier
+ preparer asks it to -- true for MySQL and Postgres and for every spec
+ inheriting their paramstyle. That doubling exists so a later DBAPI
+ parameter-interpolation pass can undo it, and the probe has no such pass:
+ it executes with no bound parameters at all. So a transform of
+ ``date_format(:value, '%Y%m%d')`` reaches the warehouse asking for the
+ literal string ``%%Y%%m%%d``, the probe returns that instead of a date, and
+ the mirrored predicate drops every row the filter keeps.
+
+ The same normalization ``Database.compile_sqla_query`` applies for the same
+ reason. ``_double_percents`` is private and not guaranteed on a third-party
+ dialect, hence the ``getattr`` default.
+ """
+ compiled = str(
+ element.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
+ )
+ if dialect is not None and getattr(
+ dialect.identifier_preparer, "_double_percents", False
+ ):
+ compiled = compiled.replace("%%", "%")
+ return compiled
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be *asked* to stand in for itself, and the transform
+ cannot carry Jinja or call a non-deterministic function. Tier 2
+ (``blocking=False``) is everything that merely leaves the mapping inactive
+ -- including a self-mapping nobody asked for, where the partition column
+ merely happens to be the default datetime column.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column == partition_column:
+ # Asked for explicitly, so report it as the mistake it is.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+ elif not partition_mapped_column and main_dttm_col == partition_column:
+ # Resolved onto itself only because the default datetime column happens
+ # to be the partition column -- a state metadata sync could produce
+ # without anyone asking for it. The mapping is inert either way, since
+ # `resolve_partition_mapping` bails out on it, so this reports and lets
+ # the write through: blocking here means a dataset already in the state
+ # can never be saved again, not even to change its description, and
+ # there is no field whose edit would clear the error first.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "%(name)s is both the partition column and the default "
+ "datetime column, so the mapping points at itself and "
+ "stays inactive. Set a mapped column override, or change "
+ "the default datetime column.",
+ name=partition_column,
+ ),
+ blocking=False,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_bare_expression(transform, engine):
+ # Blocking, and deliberately placed in `validate_transform` rather than
+ # only at the probe: one issue here closes the PUT, the importer, the
+ # query-time gate through `is_transform_active`, the Explore indicator's
+ # active verdict and the preview endpoint, all of which already consult
+ # this function.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform must be a single SQL expression. It "
+ "cannot carry a FROM, WHERE, GROUP BY or any other clause, "
+ "and it cannot contain a sub-query."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not contains_value_placeholder(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform must contain the :value placeholder, "
+ "which stands for the filter value being mirrored."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not placeholder_is_executable(transform, engine):
+ # Blocking, and for the same reason the shape gate above is: this is
+ # the function the PUT, the importer, `is_transform_active`, the
+ # Explore indicator and the preview all consult, so one issue here
+ # closes every door at once. A placeholder inside a string literal is
+ # a sub-query the engine will run once a filter value closes the quote;
+ # one inside a comment silently eats the probe's own alias.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The :value placeholder must appear where the engine will "
+ "evaluate it. It cannot sit inside a string literal or a "
+ "comment."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if functions := find_non_deterministic_functions(transform, engine):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform calls %(functions)s, whose result "
+ "depends on when and where it runs. The transform is "
+ "evaluated in a separate session and the result is cached, "
+ "so the emitted predicate would freeze a snapshot of that "
+ "moment.",
+ functions=", ".join(sorted(functions)),
+ ),
+ blocking=True,
+ )
+ ]
+
+ return []
+
+
+@lru_cache(maxsize=LRU_CACHE_MAX_SIZE)
+def is_transform_active(transform: str | None, engine: str) -> bool:
+ """
+ Whether Superset will mirror filters through this transform.
+
+ `validate_transform` with the messages discarded, so the Explore indicator
+ cannot advertise a mapping the save path recorded as inactive. Anything
+ cheaper here would be a second, weaker statement of the same rule, free to
+ drift from the one the save path applies.
+
+ Blocking issues count too. Jinja and non-deterministic transforms are
+ rejected on PUT, but `CreateDatasetCommand` and import do not validate the
+ mapping, so one can still reach the database -- and it would never mirror a
+ filter either.
+
+ Memoized because `partition_filter_mapping_summary` is serialized on every
+ Explore and dashboard load and this parses the transform. The key is
+ everything the answer depends on: `validate_transform` reads no session, no
+ locale and no config beyond `SQL_MAX_PARSE_LENGTH`, which bounds the parser
+ rather than changing a verdict within that bound.
+ """
+ return not validate_transform(transform, engine)
+
+
+def preview_partition_mapping( # pylint: disable=too-many-return-statements
+ datasource: SqlaTable,
+ *,
+ mapped_column: str,
+ value_transform: str | None,
+ sample_values: list[str],
+ operator: FilterOperator = FilterOperator.EQUALS,
+ is_monotonic: bool = False,
+ partition_column: str | None = None,
+) -> dict[str, Any]:
+ """
+ Evaluate a candidate mapping and describe the predicate it would emit.
+
+ Shares the evaluator -- and therefore the probe cache -- with the query
+ path, so preview and runtime cannot drift and a previewed transform warms
+ the chart path for free. The predicate itself comes from
+ `build_mirrored_predicates`, the same builder the query path uses, so
+ operator shapes cannot drift either: what the panel shows is what a chart
+ would emit.
+
+ Validation runs first and the engine second: a half-typed transform is by
+ definition unparseable, so most of what a text input produces costs zero
+ queries.
+
+ Every part of the mapping is taken from the request rather than the stored
+ dataset. The editor previews while the owner is still editing -- a mapping
+ that has to be saved before it can be checked is not a preview.
+ """
+ partition_column = partition_column or datasource.partition_column
+ if not partition_column:
+ return {
+ "valid": False,
+ "reason": "unconfigured",
+ "error": _("No partition column is set."),
+ }
+
+ columns_by_name = {str(column.column_name): column for column in datasource.columns}
+ if mapped_column not in columns_by_name:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _("%(name)s is not a column on this dataset.", name=mapped_column),
+ }
+
+ # The bail-out `resolve_partition_mapping` makes at query time, and that
+ # `partition_filter_mapping_summary` repeats for the Explore indicator.
+ # Without it here, preview reports a valid emitted predicate for a mapping
+ # no chart will ever mirror -- the one answer a preview panel must not give.
+ if has_active_advanced_data_type(columns_by_name[mapped_column]):
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _(
+ "%(name)s has an advanced data type, so its filters are "
+ "translated into their own predicate shape and cannot be "
+ "mirrored onto the partition column.",
+ name=mapped_column,
+ ),
+ }
+
+ engine = datasource.database.backend
+ for issue in validate_partition_mapping(
+ column_names=set(columns_by_name),
+ partition_column=str(partition_column),
+ partition_mapped_column=mapped_column,
+ main_dttm_col=datasource.main_dttm_col,
+ transform=value_transform,
+ engine=engine,
+ ):
+ return {
+ "valid": False,
+ # The parse failure is the one an owner sees constantly, and it is
+ # the only one the mockup gives its own headline to.
+ "reason": (
+ "parse"
+ if issue.field == "partition_value_transform"
+ and not is_parseable(value_transform, engine)
+ else "validation"
+ ),
+ "error": str(issue.message),
+ }
+
+ # The policy every other stored expression goes through. The save path
+ # applies it in `UpdateDatasetCommand._validate_partition_mapping`, but
+ # preview evaluates a candidate transform that has not been saved, so
+ # without this the gate had a door around it. See
+ # `stored_expression_error` for what is being kept out and why.
+ if reason := stored_expression_error(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ cast(str, value_transform),
+ ):
+ return {"valid": False, "reason": "validation", "error": reason}
+
+ mapping = PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=mapped_column,
+ value_transform=cast(str, value_transform),
+ is_monotonic=is_monotonic,
+ equality_is_safe=equality_mirrors_safely(
+ columns_by_name[mapped_column], datasource.database.db_engine_spec
+ ),
+ )
+ sample_input = _render_sample_input(
+ datasource, mapped_column, operator, sample_values
+ )
+
+ if operator not in PREVIEWABLE_OPERATORS:
+ # Checked before `mirrors`, which lets `TEMPORAL_RANGE` through when the
+ # transform is declared monotonic -- and the single sample value would
+ # then reach `handle_comparison_filter`, which has no case for a range
+ # and raises. The request schema rejects it too; this keeps the function
+ # honest for any other caller.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is mirrored as a pair of bounds, which "
+ "a preview of a single value cannot describe.",
+ operator=operator.value,
+ ),
+ }
+
+ if not mapping.mirrors(operator):
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is only mirrored when the transform "
+ "preserves ordering, which this one is not declared to do.",
+ operator=operator.value,
+ ),
+ }
+
+ value = _probe_input(
+ datasource, columns_by_name[mapped_column], operator, sample_values
+ )
+ errors: list[str] = []
+ type_errors: list[str] = []
+ predicates = build_mirrored_predicates(
+ datasource,
+ mapping,
+ [(operator, value)],
+ errors=errors,
+ type_errors=type_errors,
+ )
+ if type_errors:
+ # Its own reason, because "the database would not evaluate this" and
+ # "it evaluated and answered with the wrong kind of thing" are
+ # different problems with different fixes, and the owner is the only
+ # one who can tell which transform they meant to write.
+ return {
+ "valid": False,
+ "reason": "type",
+ "sample_input": sample_input,
+ "error": type_errors[0],
+ }
+ if not predicates:
+ return {
+ "valid": False,
+ "reason": "engine",
+ "sample_input": sample_input,
+ "error": (
+ _(
+ "The transform could not be evaluated against the "
+ "database: %(reason)s",
+ reason=errors[0],
+ )
+ if errors
+ else _("The transform could not be evaluated against the database.")
+ ),
+ }
+
+ return {
+ "valid": True,
+ "sample_input": sample_input,
+ "emitted_predicate": _render_predicate(datasource, predicates[0]),
+ }
+
+
+def _probe_input(
+ datasource: SqlaTable,
+ column: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+) -> Any:
+ """
+ The sample values as the query path would bind them.
+
+ The request carries samples as strings, and the probe is keyed on exactly
+ what it is handed, so passing them through raw asks the engine a different
+ question from the one a chart asks. A sample of ``2025`` on a numeric
+ column has to arrive as the integer the chart compares: under a transform
+ of ``typeof(:value)`` the raw string previewed ``'text'`` where the chart
+ emitted ``'integer'``. And because `_probe_cache_key` keys on each value's
+ ``repr``, the two also missed each other's cache entirely -- so the "a
+ previewed transform warms the chart path for free" claim in
+ `preview_partition_mapping`'s docstring did not actually hold.
+
+ Coerced by `filter_values_handler`, the same function the query path uses,
+ rather than by a second implementation of the same rules.
+
+ Ranges are not previewable (see `PREVIEWABLE_OPERATORS`), so the bound
+ conversion `_collect_partition_mirror_range` applies -- a ``datetime`` into
+ the column's stored representation -- has no counterpart here.
+ """
+ is_list = operator == FilterOperator.IN
+ column_spec = datasource.db_engine_spec.get_column_spec(native_type=column.type)
+ handled = datasource.filter_values_handler(
+ # `list[str]` is not a `list[FilterValue]` to mypy, invariantly, even
+ # though every `str` is a `FilterValue`.
+ values=cast(FilterValues, sample_values if is_list else sample_values[0]),
+ operator=operator,
+ target_generic_type=(
+ column_spec.generic_type if column_spec else utils.GenericDataType.STRING
+ ),
+ target_native_type=column.type,
+ is_list_target=is_list,
+ db_engine_spec=datasource.db_engine_spec,
+ db_extra=datasource.db_extra,
+ )
+
+ def bindable(value: Any) -> Any:
+ # An epoch-milliseconds sample on a temporal column comes back as
+ # engine SQL rather than a value, and SQL cannot be the value of a bind
+ # parameter -- carried as text so the probe substitutes it, the same way
+ # an array literal is.
+ if isinstance(value, ColumnElement):
+ return raw_probe_value(datasource.database, value)
+ return value
+
+ if is_list and isinstance(handled, (list, tuple)):
+ return [bindable(entry) for entry in handled]
+ return bindable(handled)
+
+
+def _render_sample_input(
+ datasource: SqlaTable,
+ mapped_column: str,
+ operator: FilterOperator,
+ values: list[str],
+) -> str:
+ """
+ The filter being previewed, written the way an owner would read it.
+
+ Display-only -- it is never executed -- but it is still read as SQL, so the
+ column is quoted and the values are rendered by the dialect rather than
+ concatenated raw. A column named ``order date`` would otherwise come out as
+ two bare words.
+ """
+ quoted = datasource.quote_identifier(mapped_column)
+ if operator == FilterOperator.IN:
+ rendered = ", ".join(
+ _render_literal(datasource.database, value) for value in values
+ )
+ return f"{quoted} IN ({rendered})"
+ return (
+ f"{quoted} {operator.value} {_render_literal(datasource.database, values[0])}"
+ )
+
+
+def _render_predicate(datasource: SqlaTable, predicate: ColumnElement[Any]) -> str:
+ """
+ Compile a mirrored predicate to the text a reader would see in View query.
+
+ Every value in it is a probed constant by this point, so ``literal_binds``
+ renders the same literals the chart query carries.
+ """
+ return _compile_literal(predicate, _dialect_for(datasource.database)).replace(
+ "\n", " "
+ )
+
+
+def _render_literal(database: Database, value: Any) -> str:
+ """
+ Render a value the way it appears in the generated SQL.
+
+ Compiled by the dialect rather than formatted by hand. `str()` would render
+ a NULL as the Python repr `None` and leave a date unquoted, neither of which
+ is SQL, and hand-rolled quote-doubling would only ever have been right for
+ strings.
+ """
+ return _compile_literal(sa.literal(value), _dialect_for(database))
+
+
+def build_mirrored_predicates(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ requests: list[tuple[FilterOperator, Any]],
+ *,
+ errors: list[str] | None = None,
+ type_errors: list[str] | None = None,
+) -> list[ColumnElement[Any]]:
+ """
+ Turn collected ``(operator, value)`` mirror requests into predicates.
+
+ ``requests`` is expected to be deduplicated by the caller. Every value is
+ resolved in a single probe round trip -- one per chart query at most -- then
+ emitted as a literal constant, so "View query" shows the reader an ordinary
+ ``WHERE`` clause rather than an inline expression.
+
+ A strict bound is emitted non-strictly; see `mirror_operator`. That happens
+ here, at the one point where a ``FilterOperator`` becomes SQL, rather than
+ at the collection sites in `ExploreMixin`: the preview endpoint calls this
+ directly, so this is what keeps the predicate the editor shows an owner and
+ the predicate the chart carries from disagreeing.
+
+ :param errors: optional sink; see `evaluate_transform`.
+ :param type_errors: optional sink for a probe result the partition column
+ cannot hold -- see `probed_value_type_error`. Separate from ``errors``
+ because the two say different things to an owner: that one is "the
+ database would not evaluate this", and this one is "it evaluated, and
+ answered with the wrong kind of thing".
+ """
+ if not requests:
+ return []
+
+ partition_column = next(
+ (
+ column
+ for column in datasource.columns
+ if column.column_name == mapping.partition_column
+ ),
+ None,
+ )
+ if partition_column is None:
+ return []
+
+ # Flatten every value that needs probing into one list, remembering how many
+ # each request consumed so the results can be handed back out.
+ flat: list[Any] = []
+ spans: list[tuple[FilterOperator, int, int]] = []
+ for operator, value in requests:
+ values = list(value) if operator == FilterOperator.IN else [value]
+ spans.append((operator, len(flat), len(values)))
+ flat.extend(values)
+
+ evaluated = evaluate_transform(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ mapping.value_transform,
+ flat,
+ errors=errors,
+ )
+ if evaluated is None:
+ return []
+
+ if not _bounds_are_ordered(evaluated, spans):
+ return []
+
+ # Declining here is the last chance to decline at all: once these
+ # predicates are in the statement, a value the partition column cannot
+ # hold fails the whole chart rather than its pruning.
+ if reason := probed_value_type_error(partition_column, evaluated):
+ logger.warning(
+ "Partition transform returned a value the partition column cannot "
+ "hold; queries will not prune: %s",
+ reason,
+ )
+ if type_errors is not None:
+ type_errors.append(reason)
+ record_mirror_verdict(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ mapping.value_transform,
+ mirrors=False,
+ )
+ return []
+
+ sqla_col = datasource.convert_tbl_column_to_sqla_col(partition_column)
+ predicates = _predicates_from_probe(
+ sqla_col, datasource.db_engine_spec, evaluated, spans
+ )
+ if not predicates:
+ return []
+
+ # A comparison against a NULL partition value is NULL, so a row parked in a
+ # NULL partition is dropped by the mirror even when the real filter matches
+ # it -- Hive and Impala's default partition, or a transform that returns
+ # NULL for an input it cannot convert. The mirror only has to be no
+ # narrower than the filter it stands in for, so admitting NULL partitions
+ # keeps those rows. Engines still prune; they read one extra partition.
+ return [sa.or_(sa.and_(*predicates), sqla_col.is_(None))]
+
+
+def _predicates_from_probe(
+ sqla_col: ColumnElement[Any],
+ db_engine_spec: type[BaseEngineSpec],
+ evaluated: list[Any],
+ spans: list[tuple[FilterOperator, int, int]],
+) -> list[ColumnElement[Any]]:
+ """
+ One predicate on the partition column per surviving mirror request.
+
+ A request whose probe answered `None` for any of its values is skipped
+ rather than emitted: `col = NULL` is `NULL`, so it would drop every row the
+ filter keeps. A strict bound is emitted non-strictly; see `mirror_operator`.
+ """
+ predicates: list[ColumnElement[Any]] = []
+ for operator, start, length in spans:
+ chunk = evaluated[start : start + length]
+ if any(value is None for value in chunk):
+ continue
+ if operator == FilterOperator.IN:
+ # The probe answers per value, so a transform over a mixed-number
+ # filter can answer with a mixed-number partition key -- and
+ # `in_` infers the bind type from the first element it is handed.
+ # Without this, probe results of `[33, 29.02]` emit
+ # `IN (33, 29)` and prune away the partition holding `29.02`.
+ predicates.append(sqla_col.in_(normalize_mixed_numbers(chunk)))
+ else:
+ predicates.append(
+ db_engine_spec.handle_comparison_filter(
+ sqla_col, mirror_operator(operator), chunk[0]
+ )
+ )
+ return predicates
+
+
+#: Operators whose value is the lower end of a range, and whose upper-end twins.
+#:
+#: Shared with `ExploreMixin._mirror_probe_input`, which rounds a bound *outward*
+#: where the engine resolves it more coarsely than the filter carries -- backward
+#: for a lower bound, forward for an upper one. Which end an operator names is
+#: the only thing separating the two directions in either caller, so the two have
+#: to agree on it rather than each classify for itself.
+LOWER_BOUND_OPERATORS = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+}
+UPPER_BOUND_OPERATORS = {
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+#: What Python type a probe result may have, per generic type of the partition
+#: column it is about to be compared against.
+#:
+#: Only the types a mismatch can actually break a query with are listed. An
+#: unresolvable column type is absent because there is nothing to check
+#: against, and ``MULTI_VALUE`` because this module does not mirror onto an
+#: array partition key at all.
+#: ``numbers.Number`` rather than ``(int, float)``: Postgres answers
+#: ``extract(epoch from ...)`` with a `Decimal`, which is the single commonest
+#: transform this feature has, and an engine is free to answer with any number
+#: type its driver prefers. What the check is for is a *string* where a number
+#: belongs, and every numeric type is equally not that.
+_PROBE_RESULT_TYPES: dict[utils.GenericDataType, tuple[type, ...]] = {
+ utils.GenericDataType.NUMERIC: (numbers.Number,),
+ utils.GenericDataType.BOOLEAN: (bool,),
+ # A day key such as ``to_char(:value, 'YYYYMMDD')`` is legitimately text.
+ utils.GenericDataType.TEMPORAL: (datetime, date, str),
Review Comment:
Accepting any `str` for a temporal partition column means a mirror can fail the chart rather than decline: on PostgreSQL with `country VARCHAR` mapped to `p DATE` via `lower(:value)`, the filter `country = 'US'` probes successfully to `'us'` and emits `p = 'us'`, which PostgreSQL rejects as a date, so a chart that worked before the mapping now errors. Preview reports it valid. Could a string result for a temporal column be checked as parseable by the engine (or only admitted when it parses as an ISO date/day key) before it is mirrored?
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/PartitionMappingSection.tsx:
##########
@@ -0,0 +1,344 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { useEffect } from 'react';
+import { t } from '@apache-superset/core/translation';
+import { css, useTheme } from '@apache-superset/core/theme';
+import { Alert } from '@apache-superset/core/components';
+import {
+ Button,
+ Checkbox,
+ Flex,
+ Icons,
+ InfoTooltip,
+ Input,
+ Loading,
+ Typography,
+} from '@superset-ui/core/components';
+import { useDebouncedCommit } from './useDebouncedCommit';
+import { usePartitionMappingPreview } from './usePartitionMappingPreview';
+import {
+ partitionRowState,
+ previewOperatorFor,
+ sampleValuesFor,
+ valueTransformIssues,
+} from './utils';
+import type {
+ PartitionMappingColumn,
+ PartitionMappingDatasource,
+} from './types';
+
+interface PartitionMappingSectionProps {
+ /** Injected by Field when `passItemToControl` is set. */
+ item?: PartitionMappingColumn;
+ /** The column's `partition_value_transform`, injected by Field. */
+ value?: string | null;
+ onChange?: (newValue: string | null) => void;
+ datasource: PartitionMappingDatasource;
+ /** Move the mapping onto this column, pre-filling a transform if we have one. */
+ onMoveMappingHere: (columnName: string) => void;
+ onRemoveMapping: () => void;
+ onMonotonicChange: (columnName: string, isMonotonic: boolean) => void;
+ /**
+ * Report whether the previewed transform mirrors, so the dataset-level
+ * banner can stop claiming a mirror this panel has already refused. A
+ * one-way report rather than a lift of the debounced transform this panel
+ * owns -- `null` while there is no verdict to report.
+ */
+ onPreviewVerdict?: (mirrors: boolean | null) => void;
+}
+
+/**
+ * The "Partition filter mapping" subsection of a column's row expand
+ * (wireframes 1c, 1h).
+ *
+ * Three states, because the model is one partition column and one mapped
+ * column: the mapped column carries the transform, every other column offers to
+ * take the mapping over, and the partition column itself shows nothing -- it is
+ * the target, not a source.
+ */
+export default function PartitionMappingSection({
+ item,
+ value,
+ onChange,
+ datasource,
+ onMoveMappingHere,
+ onRemoveMapping,
+ onMonotonicChange,
+ onPreviewVerdict,
+}: PartitionMappingSectionProps) {
+ const theme = useTheme();
+ const columnName = item?.column_name ?? '';
+ const state = partitionRowState(datasource, columnName);
+ const isMonotonic = Boolean(item?.partition_transform_is_monotonic);
+ const isTemporal = Boolean(item?.is_dttm);
+
+ // The editor's commit path echoes the value back several renders later, so an
+ // input driven straight off `value` loses whatever is typed in the meantime.
+ const {
+ value: transform,
+ onChange: onTransformChange,
+ flush: flushTransform,
+ } = useDebouncedCommit(value, (next: string) => onChange?.(next || null));
+
+ const { preview, loading } = usePartitionMappingPreview({
+ datasetId: datasource.id,
+ mappedColumn: columnName,
+ partitionColumn: datasource.partition_column ?? '',
+ // The local value, not the committed one: a preview is a statement about
+ // the expression in the box. Keying it off the commit would stack the
+ // commit debounce, the round trip and the preview's own debounce, and show
+ // a predicate for text that is no longer on screen.
+ valueTransform: transform,
+ sampleValues: sampleValuesFor(item),
+ operator: previewOperatorFor(item),
+ isMonotonic,
+ enabled: state === 'mapped',
+ });
+
+ // Reported rather than read upward, because the transform the preview judges
+ // is the local, debounced one this panel holds. `null` while a request is in
+ // flight: the previous verdict belongs to text that is no longer on screen.
+ useEffect(() => {
+ onPreviewVerdict?.(loading || !preview ? null : preview.valid);
Review Comment:
Every expanded row reports to the same `onPreviewVerdict`, and rows that aren't the mapped column report `null` (their preview is disabled), so expanding any other column after the mapped row's preview failed (e.g. `no_such_fn(:value)`) resets the verdict to `null` and the dataset banner goes back to saying filters will automatically apply while the mapped row still shows the failure. Should only the row in the `mapped` state publish a verdict?
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/utils.ts:
##########
@@ -0,0 +1,510 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { t } from '@apache-superset/core/translation';
+import type {
+ PartitionMappingColumn,
+ PartitionMappingDatasource,
+ PartitionMappingIssue,
+ PartitionRowState,
+} from './types';
+
+/**
+ * Jinja delimiters.
+ *
+ * A transform is evaluated in a different context and at a different time from
+ * the chart query, so a template would not render the same way -- the backend
+ * rejects one outright. Shared so the check that declines to preview a Jinja
+ * transform and the check that blocks saving it cannot drift apart.
+ */
+const JINJA_PATTERN = /\{\{|\{%|\{#/;
+
+/**
+ * The column whose filters are mirrored.
+ *
+ * `partition_mapped_column` is an explicit override; `null` means "follow the
+ * default datetime column", so re-pointing that column moves the mapping with
+ * it. Mirrors `SqlaTable.partition_filter_mapping_summary` on the backend.
+ */
+export function resolveMappedColumn(
+ datasource: PartitionMappingDatasource,
+): string | null {
+ if (!datasource.partition_column) {
+ return null;
+ }
+ return datasource.partition_mapped_column || datasource.main_dttm_col || null;
+}
+
+/** Whether the mapped column came from `main_dttm_col` rather than an override. */
+export function mappedColumnIsImplicit(
+ datasource: PartitionMappingDatasource,
+): boolean {
+ return Boolean(
+ datasource.partition_column &&
+ !datasource.partition_mapped_column &&
+ datasource.main_dttm_col,
+ );
+}
+
+/**
+ * Whether a transform is worth spending a preview request on.
+ *
+ * A necessary condition, never a sufficient one: the server stays the authority
+ * on whether a transform is usable, and anything this cannot see -- an
+ * unparseable expression, a non-deterministic function -- still comes back from
+ * it. What this catches is the cases that are knowably hopeless while the owner
+ * is still typing, which would otherwise spend the per-user preview budget and
+ * leave none for the transform they eventually finish writing.
+ */
+export function transformCanPreview(
+ transform: string | null | undefined,
+ mappedColumn?: string | null,
+ partitionColumn?: string | null,
+): boolean {
+ const trimmed = transform?.trim();
+ if (!trimmed) {
+ return false;
+ }
+ // Without the placeholder there is no value to substitute, so the transform
+ // is inert however well-formed it is.
+ if (!/:value\b/.test(trimmed)) {
+ return false;
+ }
+ // Jinja is rejected on save, so previewing it is pointless.
+ if (JINJA_PATTERN.test(trimmed)) {
+ return false;
+ }
+ // A column cannot stand in for itself; the backend rejects this outright.
+ if (mappedColumn && partitionColumn && mappedColumn === partitionColumn) {
+ return false;
+ }
+ return true;
+}
+
+/**
+ * Whether the mapping will actually mirror anything.
+ *
+ * Drives the choice between the green "filters will automatically apply"
+ * message and the warning that nothing is mirrored yet, so "non-blank text in
+ * the box" is not a good enough test: a transform with no `:value` to
+ * substitute, or one carrying Jinja, is as inert as an empty one and the
+ * backend's own summary reports it inactive. Claiming otherwise tells an owner
+ * their queries are pruning when they are not.
+ *
+ * Shares `transformCanPreview`'s conditions rather than restating them, and is
+ * necessary rather than sufficient for the same reason: an unparseable
+ * expression or a non-deterministic function needs a SQL parser to spot, so the
+ * server stays the authority -- `valueTransformIssues` surfaces what it says at
+ * the transform field itself.
+ */
+export function mappingIsActive(
+ datasource: PartitionMappingDatasource,
+ columns: PartitionMappingColumn[],
+): boolean {
+ const mappedColumnName = resolveMappedColumn(datasource);
+ if (!mappedColumnName || mappedColumnName === datasource.partition_column) {
+ return false;
+ }
+ const mappedColumn = columns.find(
+ column => column.column_name === mappedColumnName,
+ );
+ return transformCanPreview(
+ mappedColumn?.partition_value_transform,
+ mappedColumnName,
+ datasource.partition_column,
+ );
+}
+
+/**
+ * What is wrong with one column's value transform, if anything.
+ *
+ * Split out of `partitionMappingErrors` because the two callers disagree about
+ * which text to judge. The save gate reads the committed column record; the
+ * field's own message has to describe the text on screen, which lags the commit
+ * by a debounce. Passing the transform separately lets both ask the same
+ * question about different values instead of reimplementing the checks.
+ */
+export function valueTransformIssues(
+ column: PartitionMappingColumn | undefined,
+ transform: string | null | undefined,
+): PartitionMappingIssue[] {
+ if (!column) {
+ return [];
+ }
+
+ if (JINJA_PATTERN.test(transform ?? '')) {
+ return [
+ {
+ field: 'partition_value_transform',
+ message: t(
+ 'Jinja templating is not supported in a partition value transform. The transform is evaluated in a different context and at a different time from the chart query, so a template would not render the same way.',
+ ),
+ },
+ ];
+ }
+
+ // A temporal column falls back on the engine's own default, so leaving the box
+ // empty there only makes the mapping inactive -- which the dataset-level
+ // warning already says. A non-temporal column has nothing to fall back on.
+ if (!column.is_dttm && !transform?.trim()) {
+ return [
+ {
+ field: 'partition_value_transform',
+ message: t(
+ 'A value transform is required on %(name)s, which is not a temporal column. Use :value for each value.',
+ { name: column.column_name },
+ ),
+ },
+ ];
+ }
+
+ return [];
+}
+
+/**
+ * Everything wrong with the mapping that should stop the save.
+ *
+ * The client half of `validate_partition_mapping` in
+ * `superset/connectors/sqla/partition_mapping.py`, restricted to its blocking
+ * (Tier 1) issues. Those are the ones the PUT would reject anyway, so catching
+ * them here turns a 400 toast arriving after the modal closed into a disabled
+ * Save button that says why. Tier 2 is deliberately absent: an unparseable
+ * transform, or one missing `:value`, is "saved but stays inactive until it
+ * parses" per the PRD, and must not cost the owner the rest of their edits.
+ *
+ * One check is stricter than the backend's: an empty transform on a
+ * non-temporal mapped column blocks. The backend files that as Tier 2 for every
+ * column, but a non-temporal column has no default transform to fall back on --
+ * the field carries a required marker saying exactly this -- so the marker
+ * should mean something.
+ *
+ * Callers gate on the feature flag themselves, the way the two mount sites in
+ * `DatasourceEditor` already do; a dataset carrying a stale `partition_column`
+ * on an engine that cannot use one must not block a save the backend accepts.
+ */
+export function partitionMappingErrors(
+ datasource: PartitionMappingDatasource,
+ columns: PartitionMappingColumn[],
+): PartitionMappingIssue[] {
+ const partitionColumn = datasource.partition_column;
+ if (!partitionColumn) {
+ return [];
+ }
+
+ const issues: PartitionMappingIssue[] = [];
+ const columnNames = new Set(columns.map(column => column.column_name));
+
+ if (!columnNames.has(partitionColumn)) {
+ issues.push({
+ field: 'partition_column',
+ message: t('Partition column %(name)s is not a column on this dataset.', {
+ name: partitionColumn,
+ }),
+ });
+ }
+
+ const override = datasource.partition_mapped_column;
+ if (override && !columnNames.has(override)) {
+ issues.push({
+ field: 'partition_mapped_column',
+ message: t('Mapped column %(name)s is not a column on this dataset.', {
+ name: override,
+ }),
+ });
+ }
+
+ const mappedColumnName = resolveMappedColumn(datasource);
+ if (mappedColumnName === partitionColumn) {
Review Comment:
This rejects every resolved self-mapping, but the backend deliberately lets the implicit one through as a non-blocking issue (`partition_mapped_column` null with `main_dttm_col == partition_column`). A dataset in that state (which metadata sync used to be able to produce) opens in the editor with Save disabled even for a description-only change, which is the situation the backend comment says it avoids. Should only an explicit `partition_mapped_column === partition_column` be blocking here, with the implicit case shown as a warning?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "eschutho (via GitHub)" <gi...@apache.org>.
eschutho commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4238260110
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2770 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+#: Returned by `ExploreMixin.mirror_probe_request` for a filter no mirror can
+#: stand in for: one the engine compares more coarsely than the value carries, a
+#: value it cannot render as a literal, or an ``IN`` list with a member of
+#: either kind. A sentinel rather than `None`, because `None` is a filter value
+#: in its own right.
+#:
+#: Lives here rather than beside that method so the preview can read it too:
+#: `superset.models.helpers` imports this module, so the sentinel can only cross
+#: the boundary in this direction. Both callers have to recognise the same
+#: object -- a preview that answered "valid" for a request the chart path
+#: declines is the drift this is here to prevent.
+UNMIRRORABLE = object()
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error( # noqa: C901
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ And it must be a *read*. Shape is a separate question from effect: a bare
+ scalar expression can still write, so `SQLStatement.is_mutating` is asked
+ too -- the same question SQL Lab and the chart executor ask before letting
+ SQL run. See the gate itself for what that reaches and what it does not.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ # Also ahead of the parse, and for a stronger reason than cost: every gate
+ # below reasons about the parse tree, and this is the one construct that
+ # makes the parse tree describe a different statement from the one the
+ # engine runs. Checked here as well as in `validate_transform` because this
+ # is the door a row written by an earlier release still comes through.
+ if contains_executable_comment(transform):
+ return str(
+ _(
+ "A partition value transform cannot contain a MySQL "
+ "executable comment, which the database executes and every "
+ "validator reads as a comment."
+ )
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The read-only gate, which nothing above implies. The shape gates ask what
+ # the transform *selects*; this asks what evaluating it *does*, and a bare
+ # scalar expression can still write. `nextval(:value)` on PostgreSQL
+ # advances a sequence: one function call, no clause, no sub-query, and not
+ # in the default `DISALLOWED_SQL_FUNCTIONS` either -- so every gate above
+ # passes it and the probe then runs it. `setval` is the same shape, and
+ # `exp.Execute` and the opaque-`exp.Command` forms arrive the same way.
+ #
+ # The large-object writers (`lo_export`, `lowrite`, `lo_from_bytea`, ...)
+ # are caught here too, and the shipped denylist happens to name them as
+ # well -- but that is config an operator can replace, while this is not.
+ #
+ # `is_mutating` is the same question SQL Lab, `get_virtual_table_metadata`
+ # and the chart executor ask before letting SQL run, so a transform is held
+ # to the bar the rest of Superset already sets rather than to one invented
+ # here. Unconditional rather than gated on `Database.allow_dml`: a transform
+ # is a scalar function of `:value` by definition, so there is no legitimate
+ # mutating one, and the probe runs on a cache schedule nobody chose -- a
+ # write would repeat every time the entry expired.
+ #
+ # It bears saying what this does not reach. A user-defined function whose
+ # body writes is a plain call no parser can tell from `lower(:value)`, and
+ # `is_mutating`'s function-name walk is PostgreSQL-only by design, since the
+ # same names are read-only elsewhere. Neither residual is specific to this
+ # feature -- a dataset editor can already have the engine evaluate an
+ # arbitrary expression through a calculated column or a virtual dataset's
+ # SQL -- and closing them means authorizing the preview against the
+ # database, not parsing harder.
+ if statement.is_mutating():
+ return str(
+ _(
+ "A partition value transform cannot change data. It is "
+ "evaluated against the database to check that it mirrors, so "
+ "it has to be a read."
+ )
+ )
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the probe
+ uninspected -- string elements are escaped by the dialect's own literal
+ processor. `probe_sql_is_evaluable` then re-reads the finished query, which
+ is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def _placeholder_is_bindable(transform: str) -> bool:
+ """
+ Whether SQLAlchemy's ``text()`` can see ``:value`` as a bound parameter.
+
+ `VALUE_PLACEHOLDER_RE` is ``:value\b``, which matches the placeholder in a
+ Postgres cast such as ``:value::bigint``. SQLAlchemy's own bind scan is
+ ``(?<![:\\w$]):([\\w$]+)(?![:\\w$])`` -- note the trailing exclusion -- so a
+ following colon stops it: ``text(":value::bigint")`` reports a parameter
+ named ``valu``, and ``.bindparams(bindparam("value"))`` then raises
+ ``ArgumentError``.
+
+ `_probe` swallows that, so the only symptom was a perfectly valid transform
+ whose mapping silently never pruned, and a preview reporting an engine
+ failure for SQL that was never sent. Every write-side gate passes the
+ transform: it parses, it is a bare expression, and the placeholder *is* in
+ an executable position.
+
+ Answered by attempting the bind itself rather than by pattern-matching
+ ``::`` or reading ``text()``'s private parameter map, so this cannot
+ disagree with what `build_probe_sql` is about to do -- on any dialect, or on
+ a SQLAlchemy whose scan changes.
+ """
+ try:
+ sa.text(transform).bindparams(sa.bindparam("value", value=None))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return False
+ return True
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ bindable = _placeholder_is_bindable(transform)
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ elif bindable:
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ rendered = _compile_literal(clause, dialect)
+ else:
+ # `text()` cannot see the placeholder (see
+ # `_placeholder_is_bindable`), so the value is rendered by the
+ # dialect's own literal processor first and substituted as SQL
+ # text. The same two steps in the other order: binding exists to
+ # get the value through that processor, and `_compile_literal`
+ # inlines the result either way, so this is the same string by a
+ # different route -- not a loosening of the "never interpolate a
+ # raw value" rule. `parse_skeleton` substitutes literally, so a
+ # rendered literal containing a backslash is safe here.
+ rendered = parse_skeleton(
+ transform, _compile_literal(sa.literal(value), dialect)
+ )
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Four things have to hold, and all four are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ # Before the parse, because this gate's whole contract is that what the
+ # parse describes is what the engine will run, and an executable comment is
+ # precisely the text where that stops being true. The transform is already
+ # refused for carrying one; this covers the compiled statement, so no later
+ # change to how values are rendered can reintroduce it behind the gates
+ # below.
+ if contains_executable_comment(sql):
+ return False
+
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if not isinstance(statement, SQLStatement):
+ # A dialect whose statements this gate cannot take apart -- KQL -- gets
+ # no probe rather than an unchecked one. It never had one: the clause
+ # inspection below is implemented for SQL statements only, and the
+ # alternative to declining here is an `AttributeError` that `_probe`
+ # swallows into the same outcome, less legibly.
+ return False
+ if statement.has_subquery():
+ return False
+ if statement.get_clause_names() - {"from"}:
+ return False
+ if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+ """
+ The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+ Parsed rather than string-compared so that the comparison in
+ `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+ not parse answers ``None``, which no statement carrying a FROM can match --
+ the probe then declines, which is the right way for an unreadable engine
+ constant to fail.
+ """
+ if not from_suffix.strip():
+ return None
+ try:
+ return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+ except SupersetParseError:
+ return None
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=values is not None and not any(value is None for value in values),
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ from_suffix = database.db_engine_spec.select_without_from_suffix
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ from_suffix,
+ )
+ if not probe_sql_is_evaluable(
+ sql, database.backend, len(distinct), from_suffix
+ ):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _execution_identity(database: Database) -> str | None:
+ """
+ Who the warehouse will run the probe as, when that can vary by caller.
+
+ `_probe_cache_key` keys on the `Database` record, which is the *connection*
+ -- not the identity it is opened under. Two hooks make that identity a
+ function of the Superset user instead:
+
+ * ``impersonate_user`` on the database, which hands the effective username
+ to `db_engine_spec.impersonate_user`;
+ * ``DB_CONNECTION_MUTATOR``, which receives the effective username and may
+ return an entirely different account's URL.
+
+ Under either one, a cached probe result computed under user A's grants was
+ served to user B, and the preview echoed it back in ``emitted_predicate``.
+ A transform wrapping a read-capable function the denylist does not name --
+ Oracle's ``DBMS_XMLGEN.GETXML`` is the worked example -- then leaks across
+ users who were never allowed the same rows.
+
+ Returns ``None`` when neither hook is configured, which is the common case
+ and deliberately leaves the key as it was: the cache exists to keep a
+ synchronous warehouse round trip off the chart-query path, and keying every
+ deployment on the username would cost every deployment the hit rate to fix
+ the two that need it.
+
+ The *Superset* username rather than the resolved warehouse account, because
+ it is the input both hooks branch on, and reading it needs no URL parse and
+ puts no credential in the key.
+ """
+ if not (database.impersonate_user or app.config["DB_CONNECTION_MUTATOR"]):
+ return None
+ return get_username()
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _mirror_verdict_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str:
+ """
+ `_probe_cache_key` without the values.
+
+ Whether a transform can be evaluated at all is a property of the transform
+ and the connection, not of the filter that happened to be probing it, so
+ one chart's answer settles the question for the next one.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ # Whether a transform *can* be evaluated is a property of the
+ # transform and the connection -- but under impersonation the
+ # connection is per-user, and a function one account may call can
+ # be refused to another. See `_execution_identity`.
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_verdict:{digest}"
+
+
+def record_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ *,
+ mirrors: bool,
+) -> None:
+ """
+ Remember whether this transform produced a mirror, for the UI to read.
+
+ Advisory only. Nothing in the query path consults it: a probe that failed
+ once is retried on the next chart exactly as it is today, because declining
+ to prune for a whole cache timeout over one transient engine blip is the
+ trade `evaluate_transform` deliberately refuses -- see the comment where it
+ declines to cache a failure.
+
+ What this is for is the *claim*. `is_transform_active` parses the transform
+ and no more, so a transform the database rejects -- a misspelled function
+ is the common case -- is "active", and the editor's banner and Explore's
+ pruning glyph promise a speed-up that never happens. A promise is exactly
+ the thing that may be withheld on one bad answer and restored on a good
+ one, which is why this is a separate entry from the probe's own results
+ rather than a relaxation of that rule.
+
+ Written by `_run_probe`, so the preview endpoint -- which shares the
+ evaluator -- settles the question before the owner has even saved.
+ """
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(
+ _mirror_verdict_cache_key(database, catalog, schema, transform),
+ mirrors,
+ timeout=timeout,
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform verdict", exc_info=True)
+
+
+def known_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> bool | None:
+ """
+ The last verdict `record_mirror_verdict` stored, or `None` if there is none.
+
+ `None` is the honest answer on a cold cache and is deliberately not `False`:
+ reporting a working mapping as broken until something probes it would
+ trade one wrong claim for another. The alternative -- probing from the
+ read side -- would put a warehouse round trip on every Explore and
+ dashboard load, and a failing transform is not cached at all, so it would
+ be a round trip every single time.
+ """
+ try:
+ verdict = cache_manager.cache.get(
+ _mirror_verdict_cache_key(database, catalog, schema, transform)
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return verdict if isinstance(verdict, bool) else None
+
+
+def _compile_literal(element: Any, dialect: Dialect | None) -> str:
+ """
+ Compile with inline literals, undoing the paramstyle's percent doubling.
+
+ Both ``TextClause`` and literal compilation run the dialect's
+ ``post_process_text``, which doubles every ``%`` whenever the identifier
+ preparer asks it to -- true for MySQL and Postgres and for every spec
+ inheriting their paramstyle. That doubling exists so a later DBAPI
+ parameter-interpolation pass can undo it, and the probe has no such pass:
+ it executes with no bound parameters at all. So a transform of
+ ``date_format(:value, '%Y%m%d')`` reaches the warehouse asking for the
+ literal string ``%%Y%%m%%d``, the probe returns that instead of a date, and
+ the mirrored predicate drops every row the filter keeps.
+
+ The same normalization ``Database.compile_sqla_query`` applies for the same
+ reason. ``_double_percents`` is private and not guaranteed on a third-party
+ dialect, hence the ``getattr`` default.
+ """
+ compiled = str(
+ element.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
+ )
+ if dialect is not None and getattr(
+ dialect.identifier_preparer, "_double_percents", False
+ ):
+ compiled = compiled.replace("%%", "%")
+ return compiled
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be *asked* to stand in for itself, and the transform
+ cannot carry Jinja or call a non-deterministic function. Tier 2
+ (``blocking=False``) is everything that merely leaves the mapping inactive
+ -- including a self-mapping nobody asked for, where the partition column
+ merely happens to be the default datetime column.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column == partition_column:
+ # Asked for explicitly, so report it as the mistake it is.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+ elif not partition_mapped_column and main_dttm_col == partition_column:
+ # Resolved onto itself only because the default datetime column happens
+ # to be the partition column -- a state metadata sync could produce
+ # without anyone asking for it. The mapping is inert either way, since
+ # `resolve_partition_mapping` bails out on it, so this reports and lets
+ # the write through: blocking here means a dataset already in the state
+ # can never be saved again, not even to change its description, and
+ # there is no field whose edit would clear the error first.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "%(name)s is both the partition column and the default "
+ "datetime column, so the mapping points at itself and "
+ "stays inactive. Set a mapped column override, or change "
+ "the default datetime column.",
+ name=partition_column,
+ ),
+ blocking=False,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def drop_unmapped_value_transforms(
+ columns: list[dict[str, Any]] | None,
+ *,
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ names_by_id: dict[int, str] | None = None,
+) -> list[str]:
+ """
+ Null the value transform on every *incoming* column the mapping cannot mirror.
+
+ The write-side twin of `DatasetDAO.clear_unmapped_partition_transforms`,
+ which answers for the model. A mapping has exactly one mirrored column, so
+ at most one column may carry a transform. One parked on any other column is
+ invisible -- no row but the mapped one renders a transform -- and yet it is
+ stored, and it goes live the moment the mapped column resolves back to it.
+ Clearing an override is enough to do that: a null
+ ``partition_mapped_column`` means "follow ``main_dttm_col``".
+
+ Ungated on the feature flag, unlike its model-level twin, and the difference
+ is what each one discards. That one drops stored configuration, so with the
+ flag off it would be pure loss. This one drops only a value the request in
+ hand is asking to write where the invariant says none may live -- and the
+ flag-off window is precisely when such a value gets parked for later, since
+ the editor hides these fields and the model-level pass declines to run.
+
+ Three writers reach the columns with no effective model-level pass between
+ them, which is why this exists at all: the deprecated
+ ``POST /datasource/save/``, which writes straight through
+ `update_from_object` and so never had one; and a
+ ``PUT /api/v1/dataset/<pk>`` or a dataset import made while the flag is
+ off, where the pass runs on both sides of the write and declines on both.
+
+ Mutates the payload in place, because every caller hands its own request
+ dict straight on to the code that writes it. Returns the names it cleared,
+ so the caller can say so in a log: this is a silent correction to a payload
+ whose author may have meant it.
+
+ A column whose payload mentions neither field is left alone. "Incoming" is
+ the whole scope -- a transform already in storage on a column this request
+ says nothing about is the model-level pass's business, under its own flag.
+
+ The mapped column resolves the way every other reader resolves it,
+ ``partition_mapped_column or main_dttm_col``, and resolves to nothing
+ without a partition column -- in which case no column may hold a transform
+ either.
+
+ :param names_by_id: how to read the name off a payload entry that gives
+ only an ``id``. `DatasetDAO._upsert_columns` identifies an existing
+ column by its primary key and lets ``column_name`` be omitted -- the
+ column keeps the name it has -- so without this an ordinary PUT looked
+ like a payload of nameless columns, none of which matched the mapped
+ one, and every transform in it was dropped. Callers whose writer keys
+ on the name instead (`update_from_object`, the importer) pass nothing.
+ An entry this cannot name is left alone rather than guessed at.
+ """
+ mapped_column = (
+ (partition_mapped_column or main_dttm_col) if partition_column else None
+ )
+ cleared: list[str] = []
+ for column in columns or []:
+ name = column.get("column_name")
+ if name is None and names_by_id is not None:
+ column_id = column.get("id")
+ if column_id is not None:
+ name = names_by_id.get(column_id)
+ if name is None or name == mapped_column:
+ continue
+ if column.get("partition_value_transform") or column.get(
+ "partition_transform_is_monotonic"
+ ):
+ column["partition_value_transform"] = None
+ column["partition_transform_is_monotonic"] = False
+ cleared.append(name)
+ return cleared
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if contains_executable_comment(transform):
+ # Blocking, and checked on raw text next to the Jinja gate because no
+ # parse reports it: sqlglot reads `/*!50000 ... */` as comment data
+ # while MySQL and MariaDB execute it, so every shape gate downstream
+ # inspects a statement the engine will not run. See
+ # `EXECUTABLE_COMMENT_RE`.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform cannot contain a MySQL executable "
+ "comment (/*! ... */ or /*M! ... */). Those are comments "
+ "to every validator and statement text to the database, "
+ "so what would run is not what was checked."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_bare_expression(transform, engine):
+ # Blocking, and deliberately placed in `validate_transform` rather than
+ # only at the probe: one issue here closes the PUT, the importer, the
+ # query-time gate through `is_transform_active`, the Explore indicator's
+ # active verdict and the preview endpoint, all of which already consult
+ # this function.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform must be a single SQL expression. It "
+ "cannot carry a FROM, WHERE, GROUP BY or any other clause, "
+ "and it cannot contain a sub-query."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not contains_value_placeholder(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform must contain the :value placeholder, "
+ "which stands for the filter value being mirrored."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not placeholder_is_executable(transform, engine):
+ # Blocking, and for the same reason the shape gate above is: this is
+ # the function the PUT, the importer, `is_transform_active`, the
+ # Explore indicator and the preview all consult, so one issue here
+ # closes every door at once. A placeholder inside a string literal is
+ # a sub-query the engine will run once a filter value closes the quote;
+ # one inside a comment silently eats the probe's own alias.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The :value placeholder must appear where the engine will "
+ "evaluate it. It cannot sit inside a string literal or a "
+ "comment."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if functions := find_non_deterministic_functions(transform, engine):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform calls %(functions)s, whose result "
+ "depends on when and where it runs. The transform is "
+ "evaluated in a separate session and the result is cached, "
+ "so the emitted predicate would freeze a snapshot of that "
+ "moment.",
+ functions=", ".join(sorted(functions)),
+ ),
+ blocking=True,
+ )
+ ]
+
+ return []
+
+
+@lru_cache(maxsize=LRU_CACHE_MAX_SIZE)
+def is_transform_active(transform: str | None, engine: str) -> bool:
+ """
+ Whether Superset will mirror filters through this transform.
+
+ `validate_transform` with the messages discarded, so the Explore indicator
+ cannot advertise a mapping the save path recorded as inactive. Anything
+ cheaper here would be a second, weaker statement of the same rule, free to
+ drift from the one the save path applies.
+
+ Blocking issues count too. Jinja and non-deterministic transforms are
+ rejected on PUT, but `CreateDatasetCommand` and import do not validate the
+ mapping, so one can still reach the database -- and it would never mirror a
+ filter either.
+
+ Memoized because `partition_filter_mapping_summary` is serialized on every
+ Explore and dashboard load and this parses the transform. The key is
+ everything the answer depends on: `validate_transform` reads no session, no
+ locale and no config beyond `SQL_MAX_PARSE_LENGTH`, which bounds the parser
+ rather than changing a verdict within that bound.
+ """
+ return not validate_transform(transform, engine)
+
+
+def preview_partition_mapping( # pylint: disable=too-many-return-statements
+ datasource: SqlaTable,
+ *,
+ mapped_column: str,
+ value_transform: str | None,
+ sample_values: list[str],
+ operator: FilterOperator = FilterOperator.EQUALS,
+ is_monotonic: bool = False,
+ partition_column: str | None = None,
+) -> dict[str, Any]:
+ """
+ Evaluate a candidate mapping and describe the predicate it would emit.
+
+ Shares the evaluator -- and therefore the probe cache -- with the query
+ path, so preview and runtime cannot drift and a previewed transform warms
+ the chart path for free. The predicate itself comes from
+ `build_mirrored_predicates`, the same builder the query path uses, so
+ operator shapes cannot drift either: what the panel shows is what a chart
+ would emit.
+
+ Validation runs first and the engine second: a half-typed transform is by
+ definition unparseable, so most of what a text input produces costs zero
+ queries.
+
+ Every part of the mapping is taken from the request rather than the stored
+ dataset. The editor previews while the owner is still editing -- a mapping
+ that has to be saved before it can be checked is not a preview.
+ """
+ partition_column = partition_column or datasource.partition_column
+ if not partition_column:
+ return {
+ "valid": False,
+ "reason": "unconfigured",
+ "error": _("No partition column is set."),
+ }
+
+ columns_by_name = {str(column.column_name): column for column in datasource.columns}
+ if mapped_column not in columns_by_name:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _("%(name)s is not a column on this dataset.", name=mapped_column),
+ }
+
+ # The bail-out `resolve_partition_mapping` makes at query time, and that
+ # `partition_filter_mapping_summary` repeats for the Explore indicator.
+ # Without it here, preview reports a valid emitted predicate for a mapping
+ # no chart will ever mirror -- the one answer a preview panel must not give.
+ if has_active_advanced_data_type(columns_by_name[mapped_column]):
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _(
+ "%(name)s has an advanced data type, so its filters are "
+ "translated into their own predicate shape and cannot be "
+ "mirrored onto the partition column.",
+ name=mapped_column,
+ ),
+ }
+
+ engine = datasource.database.backend
+ for issue in validate_partition_mapping(
+ column_names=set(columns_by_name),
+ partition_column=str(partition_column),
+ partition_mapped_column=mapped_column,
+ main_dttm_col=datasource.main_dttm_col,
+ transform=value_transform,
+ engine=engine,
+ ):
+ return {
+ "valid": False,
+ # The parse failure is the one an owner sees constantly, and it is
+ # the only one the mockup gives its own headline to.
+ "reason": (
+ "parse"
+ if issue.field == "partition_value_transform"
+ and not is_parseable(value_transform, engine)
+ else "validation"
+ ),
+ "error": str(issue.message),
+ }
+
+ # The policy every other stored expression goes through. The save path
+ # applies it in `UpdateDatasetCommand._validate_partition_mapping`, but
+ # preview evaluates a candidate transform that has not been saved, so
+ # without this the gate had a door around it. See
+ # `stored_expression_error` for what is being kept out and why.
+ if reason := stored_expression_error(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ cast(str, value_transform),
+ ):
+ return {"valid": False, "reason": "validation", "error": reason}
+
+ mapping = PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=mapped_column,
+ value_transform=cast(str, value_transform),
+ is_monotonic=is_monotonic,
+ equality_is_safe=equality_mirrors_safely(
+ columns_by_name[mapped_column], datasource.database.db_engine_spec
+ ),
+ )
+ sample_input = _render_sample_input(
+ datasource, mapped_column, operator, sample_values
+ )
+
+ if operator not in PREVIEWABLE_OPERATORS:
+ # Checked before `mirrors`, which lets `TEMPORAL_RANGE` through when the
+ # transform is declared monotonic -- and the single sample value would
+ # then reach `handle_comparison_filter`, which has no case for a range
+ # and raises. The request schema rejects it too; this keeps the function
+ # honest for any other caller.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is mirrored as a pair of bounds, which "
+ "a preview of a single value cannot describe.",
+ operator=operator.value,
+ ),
+ }
+
+ if operator in MIRRORABLE_ALWAYS and not mapping.equality_is_safe:
+ # Withdrawn by `equality_mirrors_safely`, which no declaration about
+ # ordering can change -- so naming monotonicity here would send the
+ # owner to a checkbox that leaves the answer as it is.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter on this text column is not mirrored: "
+ "the database may treat strings that differ in case or "
+ "trailing spaces as equal, and the mirrored predicate could "
+ "then drop rows the filter keeps.",
+ operator=operator.value,
+ ),
+ }
+
+ if not mapping.mirrors(operator):
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is only mirrored when the transform "
+ "preserves ordering, which this one is not declared to do.",
+ operator=operator.value,
+ ),
+ }
+
+ return _preview_probe(
+ datasource,
+ mapping,
+ columns_by_name[mapped_column],
+ operator,
+ sample_values,
+ sample_input,
+ )
+
+
+def _preview_probe(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ mapped_col: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+ sample_input: str,
+) -> dict[str, Any]:
+ """
+ The half of a preview that needs the warehouse.
+
+ Split out from `preview_partition_mapping` so that the gates which answer
+ from the stored mapping alone stay readable as the single run of guard
+ clauses they are. Everything here has either run a query or decided not to.
+ """
+ value = datasource.mirror_probe_request(
+ operator,
+ _probe_input(datasource, mapped_col, operator, sample_values),
+ mapped_col,
+ )
+ if value is UNMIRRORABLE:
+ # The same step the chart path applies, so the preview cannot promise a
+ # mirror the query declines. Its own reason: the transform is fine and
+ # the engine evaluates it, the filter just carries more of the value
+ # than the engine compares on this column -- which is the column's type
+ # talking, not a broken expression.
+ return {
+ "valid": False,
+ "reason": "resolution",
+ "sample_input": sample_input,
+ "error": _(
+ "This engine compares less of a %(operator)s value on "
+ "%(column)s than the filter carries, so there is no mirror a "
+ "predicate on the partition column could stand in for. Map a "
+ "column the engine compares in full to mirror this operator.",
+ operator=operator.value,
+ column=mapped_col.column_name,
+ ),
+ }
+ errors: list[str] = []
+ type_errors: list[str] = []
+ predicates = build_mirrored_predicates(
+ datasource,
+ mapping,
+ [(operator, value)],
+ errors=errors,
+ type_errors=type_errors,
+ )
+ if type_errors:
+ # Its own reason, because "the database would not evaluate this" and
+ # "it evaluated and answered with the wrong kind of thing" are
+ # different problems with different fixes, and the owner is the only
+ # one who can tell which transform they meant to write.
+ return {
+ "valid": False,
+ "reason": "type",
+ "sample_input": sample_input,
+ "error": type_errors[0],
+ }
+ if not predicates:
+ return {
+ "valid": False,
+ "reason": "engine",
+ "sample_input": sample_input,
+ "error": (
+ _(
+ "The transform could not be evaluated against the "
+ "database: %(reason)s",
+ reason=errors[0],
+ )
+ if errors
+ else _("The transform could not be evaluated against the database.")
+ ),
+ }
+
+ return {
+ "valid": True,
+ "sample_input": sample_input,
+ "emitted_predicate": _render_predicate(datasource, predicates[0]),
+ }
+
+
+def _probe_input(
+ datasource: SqlaTable,
+ column: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+) -> Any:
+ """
+ The sample values as the query path would bind them.
+
+ The request carries samples as strings, and the probe is keyed on exactly
+ what it is handed, so passing them through raw asks the engine a different
+ question from the one a chart asks. A sample of ``2025`` on a numeric
+ column has to arrive as the integer the chart compares: under a transform
+ of ``typeof(:value)`` the raw string previewed ``'text'`` where the chart
+ emitted ``'integer'``. And because `_probe_cache_key` keys on each value's
+ ``repr``, the two also missed each other's cache entirely -- so the "a
+ previewed transform warms the chart path for free" claim in
+ `preview_partition_mapping`'s docstring did not actually hold.
+
+ Coerced by `filter_values_handler`, the same function the query path uses,
+ rather than by a second implementation of the same rules. Everything the
+ query path then does to the coerced value -- rendering an expression as a
+ literal, widening a bound, declining a comparison the engine resolves too
+ coarsely -- is `ExploreMixin.mirror_probe_request`'s, and the caller hands
+ this result straight to it.
+
+ Ranges are not previewable (see `PREVIEWABLE_OPERATORS`), so the bound
+ conversion `_collect_partition_mirror_range` applies -- a ``datetime`` into
+ the column's stored representation -- has no counterpart here.
+
+ An array column is the exception to `filter_values_handler`: its predicate
+ is built from the raw value, parsed into elements and rendered as the
+ engine's own array literal, so the chart path probes that literal
+ (`ExploreMixin._array_mirror_probe_value`) and this does too. Passing the
+ handled text instead previewed ``length('[1, 2]')`` for a filter whose
+ query probes ``length(array(1, 2))``.
+
+ Answers with a value, or `None` where an engine spec claims array columns
+ without an array literal -- which `mirror_probe_request` then declines, as
+ the chart path declines it. Otherwise `UNMIRRORABLE` is
+ `mirror_probe_request`'s to return, and the caller hands this straight to it.
+ """
+ is_list = operator == FilterOperator.IN
+ column_spec = datasource.db_engine_spec.get_column_spec(native_type=column.type)
+ if (
+ column_spec
+ and column_spec.generic_type == utils.GenericDataType.MULTI_VALUE
+ and operator in MIRRORABLE_ALWAYS
+ ):
+ # `=` and `IN` are the previewable operators the array branch builds a
+ # literal for; a bound on an array column binds the handled value on
+ # the chart path too, so it falls through to the same here.
+ return datasource._array_mirror_probe_value( # noqa: SLF001
+ sample_values if is_list else sample_values[0],
+ operator,
+ datasource.db_engine_spec.get_array_element_type(column.type),
+ datasource.db_engine_spec,
+ )
+ handled = datasource.filter_values_handler(
+ # `list[str]` is not a `list[FilterValue]` to mypy, invariantly, even
+ # though every `str` is a `FilterValue`.
+ values=cast(FilterValues, sample_values if is_list else sample_values[0]),
+ operator=operator,
+ target_generic_type=(
+ column_spec.generic_type if column_spec else utils.GenericDataType.STRING
+ ),
+ target_native_type=column.type,
+ is_list_target=is_list,
+ db_engine_spec=datasource.db_engine_spec,
+ db_extra=datasource.db_extra,
+ )
+ # No `ColumnElement` conversion here: an epoch-milliseconds sample comes back
+ # as engine SQL rather than a value, and `mirror_probe_request` renders it --
+ # the same step, on the same values, as for a chart filter.
+ return handled
+
+
+def _render_sample_input(
+ datasource: SqlaTable,
+ mapped_column: str,
+ operator: FilterOperator,
+ values: list[str],
+) -> str:
+ """
+ The filter being previewed, written the way an owner would read it.
+
+ Display-only -- it is never executed -- but it is still read as SQL, so the
+ column is quoted and the values are rendered by the dialect rather than
+ concatenated raw. A column named ``order date`` would otherwise come out as
+ two bare words.
+ """
+ quoted = datasource.quote_identifier(mapped_column)
+ if operator == FilterOperator.IN:
+ rendered = ", ".join(
+ _render_literal(datasource.database, value) for value in values
+ )
+ return f"{quoted} IN ({rendered})"
+ return (
+ f"{quoted} {operator.value} {_render_literal(datasource.database, values[0])}"
+ )
+
+
+def _render_predicate(datasource: SqlaTable, predicate: ColumnElement[Any]) -> str:
+ """
+ Compile a mirrored predicate to the text a reader would see in View query.
+
+ Every value in it is a probed constant by this point, so ``literal_binds``
+ renders the same literals the chart query carries.
+ """
+ return _compile_literal(predicate, _dialect_for(datasource.database)).replace(
+ "\n", " "
+ )
+
+
+def _render_literal(database: Database, value: Any) -> str:
+ """
+ Render a value the way it appears in the generated SQL.
+
+ Compiled by the dialect rather than formatted by hand. `str()` would render
+ a NULL as the Python repr `None` and leave a date unquoted, neither of which
+ is SQL, and hand-rolled quote-doubling would only ever have been right for
+ strings.
+ """
+ return _compile_literal(sa.literal(value), _dialect_for(database))
+
+
+def build_mirrored_predicates(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ requests: list[tuple[FilterOperator, Any]],
+ *,
+ errors: list[str] | None = None,
+ type_errors: list[str] | None = None,
+) -> list[ColumnElement[Any]]:
+ """
+ Turn collected ``(operator, value)`` mirror requests into predicates.
+
+ ``requests`` is expected to be deduplicated by the caller. Every value is
+ resolved in a single probe round trip -- one per chart query at most -- then
+ emitted as a literal constant, so "View query" shows the reader an ordinary
+ ``WHERE`` clause rather than an inline expression.
+
+ A strict bound is emitted non-strictly; see `mirror_operator`. That happens
+ here, at the one point where a ``FilterOperator`` becomes SQL, rather than
+ at the collection sites in `ExploreMixin`: the preview endpoint calls this
+ directly, so this is what keeps the predicate the editor shows an owner and
+ the predicate the chart carries from disagreeing.
+
+ :param errors: optional sink; see `evaluate_transform`.
+ :param type_errors: optional sink for a probe result the partition column
+ cannot hold -- see `probed_value_type_error`. Separate from ``errors``
+ because the two say different things to an owner: that one is "the
+ database would not evaluate this", and this one is "it evaluated, and
+ answered with the wrong kind of thing".
+ """
+ if not requests:
+ return []
+
+ partition_column = next(
+ (
+ column
+ for column in datasource.columns
+ if column.column_name == mapping.partition_column
+ ),
+ None,
+ )
+ if partition_column is None:
+ return []
+
+ # Flatten every value that needs probing into one list, remembering how many
+ # each request consumed so the results can be handed back out.
+ flat: list[Any] = []
+ spans: list[tuple[FilterOperator, int, int]] = []
+ for operator, value in requests:
+ values = list(value) if operator == FilterOperator.IN else [value]
+ spans.append((operator, len(flat), len(values)))
+ flat.extend(values)
+
+ evaluated = evaluate_transform(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ mapping.value_transform,
+ flat,
+ errors=errors,
+ )
+ if evaluated is None:
+ return []
+
+ if not _bounds_are_ordered(evaluated, spans):
+ return []
+
+ # Declining here is the last chance to decline at all: once these
+ # predicates are in the statement, a value the partition column cannot
+ # hold fails the whole chart rather than its pruning.
+ if reason := probed_value_type_error(partition_column, evaluated):
+ logger.warning(
+ "Partition transform returned a value the partition column cannot "
+ "hold; queries will not prune: %s",
+ reason,
+ )
+ if type_errors is not None:
+ type_errors.append(reason)
+ # Deliberately *not* recorded as a mirror verdict. The transform
+ # evaluated perfectly; what failed is the comparison against this
+ # dataset's partition column -- and `_mirror_verdict_cache_key` is
+ # keyed on database, catalog, schema and transform, with no partition
+ # column in it. Recorded, this dataset-specific outcome answered for
+ # every other dataset sharing the transform: `CAST(:value AS text)`
+ # mirroring happily onto a text key in dataset A was reported
+ # `evaluable: false` -- and its pruning indicator hidden -- because
+ # someone previewed the same transform against a numeric key in
+ # dataset B. A probe cache hit on A never rewrites the verdict, so it
+ # stayed wrong until the entry expired.
+ return []
+
+ sqla_col = datasource.convert_tbl_column_to_sqla_col(partition_column)
+ predicates = _predicates_from_probe(
+ sqla_col, datasource.db_engine_spec, evaluated, spans
+ )
+ if not predicates:
+ return []
+
+ # A comparison against a NULL partition value is NULL, so a row parked in a
+ # NULL partition is dropped by the mirror even when the real filter matches
+ # it -- Hive and Impala's default partition, or a transform that returns
+ # NULL for an input it cannot convert. The mirror only has to be no
+ # narrower than the filter it stands in for, so admitting NULL partitions
+ # keeps those rows. Engines still prune; they read one extra partition.
+ return [sa.or_(sa.and_(*predicates), sqla_col.is_(None))]
+
+
+def _predicates_from_probe(
+ sqla_col: ColumnElement[Any],
+ db_engine_spec: type[BaseEngineSpec],
+ evaluated: list[Any],
+ spans: list[tuple[FilterOperator, int, int]],
+) -> list[ColumnElement[Any]]:
+ """
+ One predicate on the partition column per surviving mirror request.
+
+ A request whose probe answered `None` for any of its values is skipped
+ rather than emitted: `col = NULL` is `NULL`, so it would drop every row the
+ filter keeps. A strict bound is emitted non-strictly; see `mirror_operator`.
+ """
+ predicates: list[ColumnElement[Any]] = []
+ for operator, start, length in spans:
+ chunk = evaluated[start : start + length]
+ if any(value is None for value in chunk):
+ continue
+ if operator == FilterOperator.IN:
+ # The probe answers per value, so a transform over a mixed-number
+ # filter can answer with a mixed-number partition key -- and
+ # `in_` infers the bind type from the first element it is handed.
+ # Without this, probe results of `[33, 29.02]` emit
+ # `IN (33, 29)` and prune away the partition holding `29.02`.
+ predicates.append(sqla_col.in_(normalize_mixed_numbers(chunk)))
+ else:
+ predicates.append(
+ db_engine_spec.handle_comparison_filter(
+ sqla_col, mirror_operator(operator), chunk[0]
+ )
+ )
+ return predicates
+
+
+#: Operators whose value is the lower end of a range, and whose upper-end twins.
+#:
+#: Shared with `ExploreMixin._mirror_probe_input`, which rounds a bound *outward*
+#: where the engine resolves it more coarsely than the filter carries -- backward
+#: for a lower bound, forward for an upper one. Which end an operator names is
+#: the only thing separating the two directions in either caller, so the two have
+#: to agree on it rather than each classify for itself.
+LOWER_BOUND_OPERATORS = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+}
+UPPER_BOUND_OPERATORS = {
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+#: What Python type a probe result may have, per generic type of the partition
+#: column it is about to be compared against.
+#:
+#: Only the types a mismatch can actually break a query with are listed. An
+#: unresolvable column type is absent because there is nothing to check
+#: against, and ``MULTI_VALUE`` because this module does not mirror onto an
+#: array partition key at all.
+#: ``numbers.Number`` rather than ``(int, float)``: Postgres answers
+#: ``extract(epoch from ...)`` with a `Decimal`, which is the single commonest
+#: transform this feature has, and an engine is free to answer with any number
+#: type its driver prefers. What the check is for is a *string* where a number
+#: belongs, and every numeric type is equally not that.
+_PROBE_RESULT_TYPES: dict[utils.GenericDataType, tuple[type, ...]] = {
+ utils.GenericDataType.NUMERIC: (numbers.Number,),
+ utils.GenericDataType.BOOLEAN: (bool,),
+ # A day key such as ``to_char(:value, 'YYYYMMDD')`` is legitimately text,
+ # so ``str`` is admitted -- but only for text an engine reads as an
+ # instant. `_reads_as_temporal` is the second half of this entry.
+ utils.GenericDataType.TEMPORAL: (datetime, date, str),
+ # Text, and not a number rendered as one. Not every engine accepts a number
+ # in a text comparison: Postgres refuses ``character varying = integer``,
+ # Trino ``varchar = bigint`` and BigQuery ``STRING = INT64``, all of which
+ # fail the whole chart once the predicate is in the statement. SQLite is
+ # worse -- it raises nothing and compares across storage classes as never
+ # equal, so the mirror drops every row rather than losing pruning, which is
+ # the one outcome this feature may not have. An owner whose partition key
+ # really is text writes the cast into the transform.
+ utils.GenericDataType.STRING: (str,),
+}
+
+
+#: Day/second keys a temporal column accepts as text, beyond ISO 8601.
+#: ``YYYYMMDD`` is the commonest bucketing key this feature exists for, and
+#: Postgres, Trino and BigQuery all read it as a date.
+_TEMPORAL_KEY_FORMATS = ("%Y%m%d", "%Y%m%d%H%M%S", "%Y-%m-%d %H:%M:%S")
Review Comment:
Replying on Hugh's behalf: Hugh fixed this in fd9e6d0609 (`fix(datasets): hold a mirror to the comparison the engine performs`; b24f70ab17 before today's rebase onto master), along the lines you suggested. `_reads_as_temporal` now admits only the extended ISO forms by default. Any other text formats an engine reads are declared on the engine spec through a new `BaseEngineSpec.temporal_literal_formats`, which defaults to `()`. Only Postgres declares `%Y%m%d` / `%Y%m%d%H%M%S`, so on BigQuery `format_date('%Y%m%d', :value)` against a `DATE` key declines the mirror instead of emitting `part_date = '20260115'`. The misleading comment was rewritten too. Tests cover the default, the Postgres opt-in, and the epoch round-trip.
There is one related case this doesn't cover, and I'm leaving it for Hugh since it's a design call. The ISO path still admits any `fromisoformat`-parseable string with a date prefix, so a timestamp-shaped result such as `'2026-01-15 00:00:00'` against a `DATE` key is accepted on every engine. As far as I know, BigQuery only coerces the canonical `YYYY-MM-DD` form to `DATE`, and Presto/Trino don't implicitly compare `varchar` with `date` at all. Rendering a text result through the engine's typed literal (`convert_dttm`), or narrowing the default to a bare `YYYY-MM-DD`, would close that.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4238369378
##########
superset/connectors/sqla/models.py:
##########
@@ -1689,6 +1727,8 @@ class SqlaTable(
"normalize_columns",
"always_filter_main_dttm",
"folders",
+ "partition_column",
Review Comment:
Adding the mapping fields to `export_fields` also routes them through the v0 importer behind `legacy_import_datasources`, which calls `SqlaTable.import_from_dict` directly and skips the dangling-reference repair added to the v1 importer. With an existing dataset mapped onto `dt_epoch`, importing an older bundle with `--sync columns` that omits that column deletes it but keeps `partition_column='dt_epoch'`. Pruning then silently stops, and every later PUT, even a description-only one, fails the partition-column-not-found validation.
Should the same cleanup run on the v0 path?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2929 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+class Unmirrorable:
+ """
+ A filter no mirror can stand in for, and why.
+
+ Returned by `ExploreMixin.mirror_probe_request` for a value the engine
+ compares more coarsely than the filter carries, one it cannot render as a
+ literal, one in a time frame the transform would discard, or an ``IN`` list
+ with a member of any of those kinds. An object rather than `None`, because
+ `None` is a filter value in its own right.
+
+ The reason rides along because the preview has to explain the decline to
+ the owner, and the two declines want different advice: "the engine compares
+ less of this value than you typed, so map a column it compares in full" is
+ sound guidance for a `DATE` column and actively misleading for an
+ offset-bearing bound on a `TIMESTAMP` one, which already is such a column.
+ Carried rather than re-derived so the preview's explanation cannot come
+ apart from the chart path's decision.
+
+ Lives here rather than beside that method so the preview can read it too:
+ `superset.models.helpers` imports this module, so these can only cross the
+ boundary in this direction. Both callers recognise the same instances -- a
+ preview that answered "valid" for a request the chart path declines is the
+ drift this is here to prevent.
+ """
+
+ __slots__ = ("reason",)
+
+ def __init__(self, reason: str) -> None:
+ self.reason = reason
+
+ def __repr__(self) -> str:
+ return f"<Unmirrorable {self.reason}>"
+
+
+#: The ordinary decline: whatever the mirror cannot be built from, with the
+#: engine's own comparison resolution as the reason an owner can act on.
+UNMIRRORABLE = Unmirrorable("resolution")
+
+#: A value carrying a UTC offset, declined whatever the column's resolution.
+#: A transform such as ``CAST(:value AS TIMESTAMP)`` drops the offset, so even
+#: an engine that compares the whole instant would be probed in the wrong
+#: frame -- which is not something mapping a different column fixes.
+UNMIRRORABLE_OFFSET = Unmirrorable("offset")
+
+
+def is_unmirrorable(value: Any) -> bool:
+ """Whether `mirror_probe_request` declined this request."""
+ return isinstance(value, Unmirrorable)
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+#: Declared types whose comparison ignores trailing blanks.
+#:
+#: The fixed-width character types, which the SQL standard has compare as
+#: though both sides were padded to the same length -- so ``'US'`` and
+#: ``'US '`` are equal in a ``CHARACTER(3)``, while ``lower()`` of the two is
+#: not. Spelled out rather than matched by prefix because the variable-width
+#: names start with the same letters: ``VARCHAR`` and ``CHARACTER VARYING``
+#: compare the blanks and must not land here.
+PADDED_CHARACTER_TYPES = frozenset(
+ {
+ "CHAR",
+ "NCHAR",
+ # PostgreSQL's own name for ``CHARACTER``, which is what reflection
+ # reports for a ``CHAR(n)`` column there.
+ "BPCHAR",
+ "CHARACTER",
+ "NATIONAL CHAR",
+ "NATIONAL CHARACTER",
+ }
+)
+
+
+def _is_padded_character_type(column: TableColumn) -> bool:
+ """
+ Whether ``column``'s declared type compares without its trailing blanks.
+
+ Read off the declared type rather than the engine spec's resolved one: the
+ specs map ``CHAR`` and ``VARCHAR`` onto the same `sqlalchemy.String`, so
+ the distinction this needs is gone by then. The length suffix is dropped
+ and the name matched against `PADDED_CHARACTER_TYPES`, so an unfamiliar
+ spelling answers ``False`` and the engine-level flag decides as before --
+ this gate adds a decline rather than lifting one. A column with no
+ declared type has nothing to read, and answers the same way.
+ """
+ if not isinstance(column.type, str):
+ return False
+ native = re.sub(r"\s+", " ", column.type.strip().upper())
+ return native.split("(")[0].strip() in PADDED_CHARACTER_TYPES
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ Padding is asked about per column, because it is a property of the *type*
+ rather than of the engine. ``binary_string_comparison`` speaks for an
+ engine's default text comparison, and on PostgreSQL -- which declares it
+ -- a ``CHAR(2)`` still matches a filter for ``'US '`` against a stored
+ ``'US'``, because the standard says a padded character type compares
+ without its trailing blanks. The mirror ``region_key = lower('US ')`` then
+ excludes the row. So a fixed-width character type declines whatever the
+ engine says, and an engine that ignores trailing blanks on its *variable*
+ types says so by not declaring the flag at all (see `RedshiftEngineSpec`).
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ # Ahead of the generic-type question, which a padded type can lose: the
+ # specs map ``CHARACTER`` onto no generic type at all on some engines, and
+ # a fixed-width character type is a string whether or not Superset can say
+ # so from the name.
+ if _is_padded_character_type(column):
+ return False
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error( # noqa: C901
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ And it must be a *read*. Shape is a separate question from effect: a bare
+ scalar expression can still write, so `SQLStatement.is_mutating` is asked
+ too -- the same question SQL Lab and the chart executor ask before letting
+ SQL run. See the gate itself for what that reaches and what it does not.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ # Also ahead of the parse, and for a stronger reason than cost: every gate
+ # below reasons about the parse tree, and this is the one construct that
+ # makes the parse tree describe a different statement from the one the
+ # engine runs. Checked here as well as in `validate_transform` because this
+ # is the door a row written by an earlier release still comes through.
+ if contains_executable_comment(transform):
+ return str(
+ _(
+ "A partition value transform cannot contain a MySQL "
+ "executable comment, which the database executes and every "
+ "validator reads as a comment."
+ )
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The read-only gate, which nothing above implies. The shape gates ask what
+ # the transform *selects*; this asks what evaluating it *does*, and a bare
+ # scalar expression can still write. `nextval(:value)` on PostgreSQL
+ # advances a sequence: one function call, no clause, no sub-query, and not
+ # in the default `DISALLOWED_SQL_FUNCTIONS` either -- so every gate above
+ # passes it and the probe then runs it. `setval` is the same shape, and
+ # `exp.Execute` and the opaque-`exp.Command` forms arrive the same way.
+ #
+ # The large-object writers (`lo_export`, `lowrite`, `lo_from_bytea`, ...)
+ # are caught here too, and the shipped denylist happens to name them as
+ # well -- but that is config an operator can replace, while this is not.
+ #
+ # `is_mutating` is the same question SQL Lab, `get_virtual_table_metadata`
+ # and the chart executor ask before letting SQL run, so a transform is held
+ # to the bar the rest of Superset already sets rather than to one invented
+ # here. Unconditional rather than gated on `Database.allow_dml`: a transform
+ # is a scalar function of `:value` by definition, so there is no legitimate
+ # mutating one, and the probe runs on a cache schedule nobody chose -- a
+ # write would repeat every time the entry expired.
+ #
+ # It bears saying what this does not reach. A user-defined function whose
+ # body writes is a plain call no parser can tell from `lower(:value)`, and
+ # `is_mutating`'s function-name walk is PostgreSQL-only by design, since the
+ # same names are read-only elsewhere. Neither residual is specific to this
+ # feature -- a dataset editor can already have the engine evaluate an
+ # arbitrary expression through a calculated column or a virtual dataset's
+ # SQL -- and closing them means authorizing the preview against the
+ # database, not parsing harder.
+ if statement.is_mutating():
+ return str(
+ _(
+ "A partition value transform cannot change data. It is "
+ "evaluated against the database to check that it mirrors, so "
+ "it has to be a read."
+ )
+ )
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
Review Comment:
The function denylist is matched on the SQL function name sqlglot reports, so a name written with a PostgreSQL Unicode escape is not recognised. For example, `CAST(U&"\0071uery_to_xml"(:value, false, true, '') AS TEXT)` parses as an anonymous function called `\0071uery_to_xml` and is not matched against `query_to_xml`, but PostgreSQL decodes the identifier and runs the query passed as the sample value. The probe then executes through `database.get_df()` without RLS injection, and the result is echoed back in `emitted_predicate`, so an owner without SQL Lab access could read rows outside their RLS scope.
Should the denylist check normalize escaped identifiers (or reject `U&` identifiers) before this gate relies on it?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2929 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+class Unmirrorable:
+ """
+ A filter no mirror can stand in for, and why.
+
+ Returned by `ExploreMixin.mirror_probe_request` for a value the engine
+ compares more coarsely than the filter carries, one it cannot render as a
+ literal, one in a time frame the transform would discard, or an ``IN`` list
+ with a member of any of those kinds. An object rather than `None`, because
+ `None` is a filter value in its own right.
+
+ The reason rides along because the preview has to explain the decline to
+ the owner, and the two declines want different advice: "the engine compares
+ less of this value than you typed, so map a column it compares in full" is
+ sound guidance for a `DATE` column and actively misleading for an
+ offset-bearing bound on a `TIMESTAMP` one, which already is such a column.
+ Carried rather than re-derived so the preview's explanation cannot come
+ apart from the chart path's decision.
+
+ Lives here rather than beside that method so the preview can read it too:
+ `superset.models.helpers` imports this module, so these can only cross the
+ boundary in this direction. Both callers recognise the same instances -- a
+ preview that answered "valid" for a request the chart path declines is the
+ drift this is here to prevent.
+ """
+
+ __slots__ = ("reason",)
+
+ def __init__(self, reason: str) -> None:
+ self.reason = reason
+
+ def __repr__(self) -> str:
+ return f"<Unmirrorable {self.reason}>"
+
+
+#: The ordinary decline: whatever the mirror cannot be built from, with the
+#: engine's own comparison resolution as the reason an owner can act on.
+UNMIRRORABLE = Unmirrorable("resolution")
+
+#: A value carrying a UTC offset, declined whatever the column's resolution.
+#: A transform such as ``CAST(:value AS TIMESTAMP)`` drops the offset, so even
+#: an engine that compares the whole instant would be probed in the wrong
+#: frame -- which is not something mapping a different column fixes.
+UNMIRRORABLE_OFFSET = Unmirrorable("offset")
+
+
+def is_unmirrorable(value: Any) -> bool:
+ """Whether `mirror_probe_request` declined this request."""
+ return isinstance(value, Unmirrorable)
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+#: Declared types whose comparison ignores trailing blanks.
+#:
+#: The fixed-width character types, which the SQL standard has compare as
+#: though both sides were padded to the same length -- so ``'US'`` and
+#: ``'US '`` are equal in a ``CHARACTER(3)``, while ``lower()`` of the two is
+#: not. Spelled out rather than matched by prefix because the variable-width
+#: names start with the same letters: ``VARCHAR`` and ``CHARACTER VARYING``
+#: compare the blanks and must not land here.
+PADDED_CHARACTER_TYPES = frozenset(
+ {
+ "CHAR",
+ "NCHAR",
+ # PostgreSQL's own name for ``CHARACTER``, which is what reflection
+ # reports for a ``CHAR(n)`` column there.
+ "BPCHAR",
+ "CHARACTER",
+ "NATIONAL CHAR",
+ "NATIONAL CHARACTER",
+ }
+)
+
+
+def _is_padded_character_type(column: TableColumn) -> bool:
+ """
+ Whether ``column``'s declared type compares without its trailing blanks.
+
+ Read off the declared type rather than the engine spec's resolved one: the
+ specs map ``CHAR`` and ``VARCHAR`` onto the same `sqlalchemy.String`, so
+ the distinction this needs is gone by then. The length suffix is dropped
+ and the name matched against `PADDED_CHARACTER_TYPES`, so an unfamiliar
+ spelling answers ``False`` and the engine-level flag decides as before --
+ this gate adds a decline rather than lifting one. A column with no
+ declared type has nothing to read, and answers the same way.
+ """
+ if not isinstance(column.type, str):
+ return False
+ native = re.sub(r"\s+", " ", column.type.strip().upper())
+ return native.split("(")[0].strip() in PADDED_CHARACTER_TYPES
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ Padding is asked about per column, because it is a property of the *type*
+ rather than of the engine. ``binary_string_comparison`` speaks for an
+ engine's default text comparison, and on PostgreSQL -- which declares it
+ -- a ``CHAR(2)`` still matches a filter for ``'US '`` against a stored
+ ``'US'``, because the standard says a padded character type compares
+ without its trailing blanks. The mirror ``region_key = lower('US ')`` then
+ excludes the row. So a fixed-width character type declines whatever the
+ engine says, and an engine that ignores trailing blanks on its *variable*
+ types says so by not declaring the flag at all (see `RedshiftEngineSpec`).
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ # Ahead of the generic-type question, which a padded type can lose: the
+ # specs map ``CHARACTER`` onto no generic type at all on some engines, and
+ # a fixed-width character type is a string whether or not Superset can say
+ # so from the name.
+ if _is_padded_character_type(column):
+ return False
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error( # noqa: C901
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ And it must be a *read*. Shape is a separate question from effect: a bare
+ scalar expression can still write, so `SQLStatement.is_mutating` is asked
+ too -- the same question SQL Lab and the chart executor ask before letting
+ SQL run. See the gate itself for what that reaches and what it does not.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ # Also ahead of the parse, and for a stronger reason than cost: every gate
+ # below reasons about the parse tree, and this is the one construct that
+ # makes the parse tree describe a different statement from the one the
+ # engine runs. Checked here as well as in `validate_transform` because this
+ # is the door a row written by an earlier release still comes through.
+ if contains_executable_comment(transform):
+ return str(
+ _(
+ "A partition value transform cannot contain a MySQL "
+ "executable comment, which the database executes and every "
+ "validator reads as a comment."
+ )
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The read-only gate, which nothing above implies. The shape gates ask what
+ # the transform *selects*; this asks what evaluating it *does*, and a bare
+ # scalar expression can still write. `nextval(:value)` on PostgreSQL
+ # advances a sequence: one function call, no clause, no sub-query, and not
+ # in the default `DISALLOWED_SQL_FUNCTIONS` either -- so every gate above
+ # passes it and the probe then runs it. `setval` is the same shape, and
+ # `exp.Execute` and the opaque-`exp.Command` forms arrive the same way.
+ #
+ # The large-object writers (`lo_export`, `lowrite`, `lo_from_bytea`, ...)
+ # are caught here too, and the shipped denylist happens to name them as
+ # well -- but that is config an operator can replace, while this is not.
+ #
+ # `is_mutating` is the same question SQL Lab, `get_virtual_table_metadata`
+ # and the chart executor ask before letting SQL run, so a transform is held
+ # to the bar the rest of Superset already sets rather than to one invented
+ # here. Unconditional rather than gated on `Database.allow_dml`: a transform
+ # is a scalar function of `:value` by definition, so there is no legitimate
+ # mutating one, and the probe runs on a cache schedule nobody chose -- a
+ # write would repeat every time the entry expired.
+ #
+ # It bears saying what this does not reach. A user-defined function whose
+ # body writes is a plain call no parser can tell from `lower(:value)`, and
+ # `is_mutating`'s function-name walk is PostgreSQL-only by design, since the
+ # same names are read-only elsewhere. Neither residual is specific to this
+ # feature -- a dataset editor can already have the engine evaluate an
+ # arbitrary expression through a calculated column or a virtual dataset's
+ # SQL -- and closing them means authorizing the preview against the
+ # database, not parsing harder.
+ if statement.is_mutating():
+ return str(
+ _(
+ "A partition value transform cannot change data. It is "
+ "evaluated against the database to check that it mirrors, so "
+ "it has to be a read."
+ )
+ )
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the probe
+ uninspected -- string elements are escaped by the dialect's own literal
+ processor. `probe_sql_is_evaluable` then re-reads the finished query, which
+ is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def _placeholder_is_bindable(transform: str) -> bool:
+ """
+ Whether SQLAlchemy's ``text()`` can see ``:value`` as a bound parameter.
+
+ `VALUE_PLACEHOLDER_RE` is ``:value\b``, which matches the placeholder in a
+ Postgres cast such as ``:value::bigint``. SQLAlchemy's own bind scan is
+ ``(?<![:\\w$]):([\\w$]+)(?![:\\w$])`` -- note the trailing exclusion -- so a
+ following colon stops it: ``text(":value::bigint")`` reports a parameter
+ named ``valu``, and ``.bindparams(bindparam("value"))`` then raises
+ ``ArgumentError``.
+
+ `_probe` swallows that, so the only symptom was a perfectly valid transform
+ whose mapping silently never pruned, and a preview reporting an engine
+ failure for SQL that was never sent. Every write-side gate passes the
+ transform: it parses, it is a bare expression, and the placeholder *is* in
+ an executable position.
+
+ Answered by attempting the bind itself rather than by pattern-matching
+ ``::`` or reading ``text()``'s private parameter map, so this cannot
+ disagree with what `build_probe_sql` is about to do -- on any dialect, or on
+ a SQLAlchemy whose scan changes.
+ """
+ try:
+ sa.text(transform).bindparams(sa.bindparam("value", value=None))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return False
+ return True
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ bindable = _placeholder_is_bindable(transform)
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ elif bindable:
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ rendered = _compile_literal(clause, dialect)
+ else:
+ # `text()` cannot see the placeholder (see
+ # `_placeholder_is_bindable`), so the value is rendered by the
+ # dialect's own literal processor first and substituted as SQL
+ # text. The same two steps in the other order: binding exists to
+ # get the value through that processor, and `_compile_literal`
+ # inlines the result either way, so this is the same string by a
+ # different route -- not a loosening of the "never interpolate a
+ # raw value" rule. `parse_skeleton` substitutes literally, so a
+ # rendered literal containing a backslash is safe here.
+ rendered = parse_skeleton(
+ transform, _compile_literal(sa.literal(value), dialect)
+ )
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Four things have to hold, and all four are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ # Before the parse, because this gate's whole contract is that what the
+ # parse describes is what the engine will run, and an executable comment is
+ # precisely the text where that stops being true. The transform is already
+ # refused for carrying one; this covers the compiled statement, so no later
+ # change to how values are rendered can reintroduce it behind the gates
+ # below.
+ if contains_executable_comment(sql):
+ return False
+
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if not isinstance(statement, SQLStatement):
+ # A dialect whose statements this gate cannot take apart -- KQL -- gets
+ # no probe rather than an unchecked one. It never had one: the clause
+ # inspection below is implemented for SQL statements only, and the
+ # alternative to declining here is an `AttributeError` that `_probe`
+ # swallows into the same outcome, less legibly.
+ return False
+ if statement.has_subquery():
+ return False
+ if statement.get_clause_names() - {"from"}:
+ return False
+ if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+ """
+ The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+ Parsed rather than string-compared so that the comparison in
+ `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+ not parse answers ``None``, which no statement carrying a FROM can match --
+ the probe then declines, which is the right way for an unreadable engine
+ constant to fail.
+ """
+ if not from_suffix.strip():
+ return None
+ try:
+ return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+ except SupersetParseError:
+ return None
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=values is not None and not any(value is None for value in values),
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ from_suffix = database.db_engine_spec.select_without_from_suffix
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ from_suffix,
+ )
+ if not probe_sql_is_evaluable(
+ sql, database.backend, len(distinct), from_suffix
+ ):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _execution_identity(database: Database) -> str | None:
+ """
+ Who the warehouse will run the probe as, when that can vary by caller.
+
+ `_probe_cache_key` keys on the `Database` record, which is the *connection*
+ -- not the identity it is opened under. Two hooks make that identity a
+ function of the Superset user instead:
+
+ * ``impersonate_user`` on the database, which hands the effective username
+ to `db_engine_spec.impersonate_user`;
+ * ``DB_CONNECTION_MUTATOR``, which receives the effective username and may
+ return an entirely different account's URL.
+
+ Under either one, a cached probe result computed under user A's grants was
+ served to user B, and the preview echoed it back in ``emitted_predicate``.
+ A transform wrapping a read-capable function the denylist does not name --
+ Oracle's ``DBMS_XMLGEN.GETXML`` is the worked example -- then leaks across
+ users who were never allowed the same rows.
+
+ Returns ``None`` when neither hook is configured, which is the common case
+ and deliberately leaves the key as it was: the cache exists to keep a
+ synchronous warehouse round trip off the chart-query path, and keying every
+ deployment on the username would cost every deployment the hit rate to fix
+ the two that need it.
+
+ The *Superset* username rather than the resolved warehouse account, because
+ it is the input both hooks branch on, and reading it needs no URL parse and
+ puts no credential in the key.
+ """
+ if not (database.impersonate_user or app.config["DB_CONNECTION_MUTATOR"]):
+ return None
+ return get_username()
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _mirror_verdict_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str:
+ """
+ `_probe_cache_key` without the values.
+
+ Whether a transform can be evaluated at all is a property of the transform
+ and the connection, not of the filter that happened to be probing it, so
+ one chart's answer settles the question for the next one.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ # Whether a transform *can* be evaluated is a property of the
+ # transform and the connection -- but under impersonation the
+ # connection is per-user, and a function one account may call can
+ # be refused to another. See `_execution_identity`.
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_verdict:{digest}"
+
+
+def record_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ *,
+ mirrors: bool,
+) -> None:
+ """
+ Remember whether this transform produced a mirror, for the UI to read.
+
+ Advisory only. Nothing in the query path consults it: a probe that failed
+ once is retried on the next chart exactly as it is today, because declining
+ to prune for a whole cache timeout over one transient engine blip is the
+ trade `evaluate_transform` deliberately refuses -- see the comment where it
+ declines to cache a failure.
+
+ What this is for is the *claim*. `is_transform_active` parses the transform
+ and no more, so a transform the database rejects -- a misspelled function
+ is the common case -- is "active", and the editor's banner and Explore's
+ pruning glyph promise a speed-up that never happens. A promise is exactly
+ the thing that may be withheld on one bad answer and restored on a good
+ one, which is why this is a separate entry from the probe's own results
+ rather than a relaxation of that rule.
+
+ Written by `_run_probe`, so the preview endpoint -- which shares the
+ evaluator -- settles the question before the owner has even saved.
+ """
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(
+ _mirror_verdict_cache_key(database, catalog, schema, transform),
+ mirrors,
+ timeout=timeout,
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform verdict", exc_info=True)
+
+
+def known_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> bool | None:
+ """
+ The last verdict `record_mirror_verdict` stored, or `None` if there is none.
+
+ `None` is the honest answer on a cold cache and is deliberately not `False`:
+ reporting a working mapping as broken until something probes it would
+ trade one wrong claim for another. The alternative -- probing from the
+ read side -- would put a warehouse round trip on every Explore and
+ dashboard load, and a failing transform is not cached at all, so it would
+ be a round trip every single time.
+ """
+ try:
+ verdict = cache_manager.cache.get(
+ _mirror_verdict_cache_key(database, catalog, schema, transform)
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return verdict if isinstance(verdict, bool) else None
+
+
+def _compile_literal(element: Any, dialect: Dialect | None) -> str:
+ """
+ Compile with inline literals, undoing the paramstyle's percent doubling.
+
+ Both ``TextClause`` and literal compilation run the dialect's
+ ``post_process_text``, which doubles every ``%`` whenever the identifier
+ preparer asks it to -- true for MySQL and Postgres and for every spec
+ inheriting their paramstyle. That doubling exists so a later DBAPI
+ parameter-interpolation pass can undo it, and the probe has no such pass:
+ it executes with no bound parameters at all. So a transform of
+ ``date_format(:value, '%Y%m%d')`` reaches the warehouse asking for the
+ literal string ``%%Y%%m%%d``, the probe returns that instead of a date, and
+ the mirrored predicate drops every row the filter keeps.
+
+ The same normalization ``Database.compile_sqla_query`` applies for the same
+ reason. ``_double_percents`` is private and not guaranteed on a third-party
+ dialect, hence the ``getattr`` default.
+ """
+ compiled = str(
+ element.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
+ )
+ if dialect is not None and getattr(
+ dialect.identifier_preparer, "_double_percents", False
+ ):
+ compiled = compiled.replace("%%", "%")
+ return compiled
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be *asked* to stand in for itself, and the transform
+ cannot carry Jinja or call a non-deterministic function. Tier 2
+ (``blocking=False``) is everything that merely leaves the mapping inactive
+ -- including a self-mapping nobody asked for, where the partition column
+ merely happens to be the default datetime column.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column == partition_column:
+ # Asked for explicitly, so report it as the mistake it is.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+ elif not partition_mapped_column and main_dttm_col == partition_column:
+ # Resolved onto itself only because the default datetime column happens
+ # to be the partition column -- a state metadata sync could produce
+ # without anyone asking for it. The mapping is inert either way, since
+ # `resolve_partition_mapping` bails out on it, so this reports and lets
+ # the write through: blocking here means a dataset already in the state
+ # can never be saved again, not even to change its description, and
+ # there is no field whose edit would clear the error first.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "%(name)s is both the partition column and the default "
+ "datetime column, so the mapping points at itself and "
+ "stays inactive. Set a mapped column override, or change "
+ "the default datetime column.",
+ name=partition_column,
+ ),
+ blocking=False,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def drop_unmapped_value_transforms(
+ columns: list[dict[str, Any]] | None,
+ *,
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ names_by_id: dict[int, str] | None = None,
+) -> list[str]:
+ """
+ Null the value transform on every *incoming* column the mapping cannot mirror.
+
+ The write-side twin of `DatasetDAO.clear_unmapped_partition_transforms`,
+ which answers for the model. A mapping has exactly one mirrored column, so
+ at most one column may carry a transform. One parked on any other column is
+ invisible -- no row but the mapped one renders a transform -- and yet it is
+ stored, and it goes live the moment the mapped column resolves back to it.
+ Clearing an override is enough to do that: a null
+ ``partition_mapped_column`` means "follow ``main_dttm_col``".
+
+ Ungated on the feature flag, unlike its model-level twin, and the difference
+ is what each one discards. That one drops stored configuration, so with the
+ flag off it would be pure loss. This one drops only a value the request in
+ hand is asking to write where the invariant says none may live -- and the
+ flag-off window is precisely when such a value gets parked for later, since
+ the editor hides these fields and the model-level pass declines to run.
+
+ Three writers reach the columns with no effective model-level pass between
+ them, which is why this exists at all: the deprecated
+ ``POST /datasource/save/``, which writes straight through
+ `update_from_object` and so never had one; and a
+ ``PUT /api/v1/dataset/<pk>`` or a dataset import made while the flag is
+ off, where the pass runs on both sides of the write and declines on both.
+
+ Mutates the payload in place, because every caller hands its own request
+ dict straight on to the code that writes it. Returns the names it cleared,
+ so the caller can say so in a log: this is a silent correction to a payload
+ whose author may have meant it.
+
+ A column whose payload mentions neither field is left alone. "Incoming" is
+ the whole scope -- a transform already in storage on a column this request
+ says nothing about is the model-level pass's business, under its own flag.
+
+ The mapped column resolves the way every other reader resolves it,
+ ``partition_mapped_column or main_dttm_col``, and resolves to nothing
+ without a partition column -- in which case no column may hold a transform
+ either.
+
+ :param names_by_id: how to read the name off a payload entry that gives
+ only an ``id``. `DatasetDAO._upsert_columns` identifies an existing
+ column by its primary key and lets ``column_name`` be omitted -- the
+ column keeps the name it has -- so without this an ordinary PUT looked
+ like a payload of nameless columns, none of which matched the mapped
+ one, and every transform in it was dropped. Callers whose writer keys
+ on the name instead (`update_from_object`, the importer) pass nothing.
+ An entry this cannot name is left alone rather than guessed at.
+ """
+ mapped_column = (
+ (partition_mapped_column or main_dttm_col) if partition_column else None
+ )
+ cleared: list[str] = []
+ for column in columns or []:
+ name = column.get("column_name")
+ if name is None and names_by_id is not None:
+ column_id = column.get("id")
+ if column_id is not None:
+ name = names_by_id.get(column_id)
+ if name is None or name == mapped_column:
+ continue
+ if column.get("partition_value_transform") or column.get(
+ "partition_transform_is_monotonic"
+ ):
+ column["partition_value_transform"] = None
+ column["partition_transform_is_monotonic"] = False
+ cleared.append(name)
+ return cleared
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if contains_executable_comment(transform):
+ # Blocking, and checked on raw text next to the Jinja gate because no
+ # parse reports it: sqlglot reads `/*!50000 ... */` as comment data
+ # while MySQL and MariaDB execute it, so every shape gate downstream
+ # inspects a statement the engine will not run. See
+ # `EXECUTABLE_COMMENT_RE`.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform cannot contain a MySQL executable "
+ "comment (/*! ... */ or /*M! ... */). Those are comments "
+ "to every validator and statement text to the database, "
+ "so what would run is not what was checked."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_bare_expression(transform, engine):
+ # Blocking, and deliberately placed in `validate_transform` rather than
+ # only at the probe: one issue here closes the PUT, the importer, the
+ # query-time gate through `is_transform_active`, the Explore indicator's
+ # active verdict and the preview endpoint, all of which already consult
+ # this function.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform must be a single SQL expression. It "
+ "cannot carry a FROM, WHERE, GROUP BY or any other clause, "
+ "and it cannot contain a sub-query."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not contains_value_placeholder(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform must contain the :value placeholder, "
+ "which stands for the filter value being mirrored."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not placeholder_is_executable(transform, engine):
+ # Blocking, and for the same reason the shape gate above is: this is
+ # the function the PUT, the importer, `is_transform_active`, the
+ # Explore indicator and the preview all consult, so one issue here
+ # closes every door at once. A placeholder inside a string literal is
+ # a sub-query the engine will run once a filter value closes the quote;
+ # one inside a comment silently eats the probe's own alias.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The :value placeholder must appear where the engine will "
+ "evaluate it. It cannot sit inside a string literal or a "
+ "comment."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if functions := find_non_deterministic_functions(transform, engine):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform calls %(functions)s, whose result "
+ "depends on when and where it runs. The transform is "
+ "evaluated in a separate session and the result is cached, "
+ "so the emitted predicate would freeze a snapshot of that "
+ "moment.",
+ functions=", ".join(sorted(functions)),
+ ),
+ blocking=True,
+ )
+ ]
+
+ return []
+
+
+@lru_cache(maxsize=LRU_CACHE_MAX_SIZE)
+def is_transform_active(transform: str | None, engine: str) -> bool:
+ """
+ Whether Superset will mirror filters through this transform.
+
+ `validate_transform` with the messages discarded, so the Explore indicator
+ cannot advertise a mapping the save path recorded as inactive. Anything
+ cheaper here would be a second, weaker statement of the same rule, free to
+ drift from the one the save path applies.
+
+ Blocking issues count too. Jinja and non-deterministic transforms are
+ rejected on PUT, but `CreateDatasetCommand` and import do not validate the
+ mapping, so one can still reach the database -- and it would never mirror a
+ filter either.
+
+ Memoized because `partition_filter_mapping_summary` is serialized on every
+ Explore and dashboard load and this parses the transform. The key is
+ everything the answer depends on: `validate_transform` reads no session, no
+ locale and no config beyond `SQL_MAX_PARSE_LENGTH`, which bounds the parser
+ rather than changing a verdict within that bound.
+ """
+ return not validate_transform(transform, engine)
+
+
+def preview_partition_mapping( # pylint: disable=too-many-return-statements
+ datasource: SqlaTable,
+ *,
+ mapped_column: str,
+ value_transform: str | None,
+ sample_values: list[str],
+ operator: FilterOperator = FilterOperator.EQUALS,
+ is_monotonic: bool = False,
+ partition_column: str | None = None,
+) -> dict[str, Any]:
+ """
+ Evaluate a candidate mapping and describe the predicate it would emit.
+
+ Shares the evaluator -- and therefore the probe cache -- with the query
+ path, so preview and runtime cannot drift and a previewed transform warms
+ the chart path for free. The predicate itself comes from
+ `build_mirrored_predicates`, the same builder the query path uses, so
+ operator shapes cannot drift either: what the panel shows is what a chart
+ would emit.
+
+ Validation runs first and the engine second: a half-typed transform is by
+ definition unparseable, so most of what a text input produces costs zero
+ queries.
+
+ Every part of the mapping is taken from the request rather than the stored
+ dataset. The editor previews while the owner is still editing -- a mapping
+ that has to be saved before it can be checked is not a preview.
+ """
+ partition_column = partition_column or datasource.partition_column
+ if not partition_column:
+ return {
+ "valid": False,
+ "reason": "unconfigured",
+ "error": _("No partition column is set."),
+ }
+
+ columns_by_name = {str(column.column_name): column for column in datasource.columns}
+ if mapped_column not in columns_by_name:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _("%(name)s is not a column on this dataset.", name=mapped_column),
+ }
+
+ # The bail-out `resolve_partition_mapping` makes at query time, and that
+ # `partition_filter_mapping_summary` repeats for the Explore indicator.
+ # Without it here, preview reports a valid emitted predicate for a mapping
+ # no chart will ever mirror -- the one answer a preview panel must not give.
+ if has_active_advanced_data_type(columns_by_name[mapped_column]):
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _(
+ "%(name)s has an advanced data type, so its filters are "
+ "translated into their own predicate shape and cannot be "
+ "mirrored onto the partition column.",
+ name=mapped_column,
+ ),
+ }
+
+ engine = datasource.database.backend
+ for issue in validate_partition_mapping(
+ column_names=set(columns_by_name),
+ partition_column=str(partition_column),
+ partition_mapped_column=mapped_column,
+ main_dttm_col=datasource.main_dttm_col,
+ transform=value_transform,
+ engine=engine,
+ ):
+ return {
+ "valid": False,
+ # The parse failure is the one an owner sees constantly, and it is
+ # the only one the mockup gives its own headline to.
+ "reason": (
+ "parse"
+ if issue.field == "partition_value_transform"
+ and not is_parseable(value_transform, engine)
+ else "validation"
+ ),
+ "error": str(issue.message),
+ }
+
+ # The policy every other stored expression goes through. The save path
+ # applies it in `UpdateDatasetCommand._validate_partition_mapping`, but
+ # preview evaluates a candidate transform that has not been saved, so
+ # without this the gate had a door around it. See
+ # `stored_expression_error` for what is being kept out and why.
+ if reason := stored_expression_error(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ cast(str, value_transform),
+ ):
+ return {"valid": False, "reason": "validation", "error": reason}
+
+ mapping = PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=mapped_column,
+ value_transform=cast(str, value_transform),
+ is_monotonic=is_monotonic,
+ equality_is_safe=equality_mirrors_safely(
+ columns_by_name[mapped_column], datasource.database.db_engine_spec
+ ),
+ )
+ sample_input = _render_sample_input(
+ datasource, mapped_column, operator, sample_values
+ )
+
+ if operator not in PREVIEWABLE_OPERATORS:
+ # Checked before `mirrors`, which lets `TEMPORAL_RANGE` through when the
+ # transform is declared monotonic -- and the single sample value would
+ # then reach `handle_comparison_filter`, which has no case for a range
+ # and raises. The request schema rejects it too; this keeps the function
+ # honest for any other caller.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is mirrored as a pair of bounds, which "
+ "a preview of a single value cannot describe.",
+ operator=operator.value,
+ ),
+ }
+
+ if operator in MIRRORABLE_ALWAYS and not mapping.equality_is_safe:
+ # Withdrawn by `equality_mirrors_safely`, which no declaration about
+ # ordering can change -- so naming monotonicity here would send the
+ # owner to a checkbox that leaves the answer as it is.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter on this text column is not mirrored: "
+ "the database may treat strings that differ in case or "
+ "trailing spaces as equal, and the mirrored predicate could "
+ "then drop rows the filter keeps.",
+ operator=operator.value,
+ ),
+ }
+
+ if not mapping.mirrors(operator):
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is only mirrored when the transform "
+ "preserves ordering, which this one is not declared to do.",
+ operator=operator.value,
+ ),
+ }
+
+ return _preview_probe(
+ datasource,
+ mapping,
+ columns_by_name[mapped_column],
+ operator,
+ sample_values,
+ sample_input,
+ )
+
+
+def _preview_probe(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ mapped_col: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+ sample_input: str,
+) -> dict[str, Any]:
+ """
+ The half of a preview that needs the warehouse.
+
+ Split out from `preview_partition_mapping` so that the gates which answer
+ from the stored mapping alone stay readable as the single run of guard
+ clauses they are. Everything here has either run a query or decided not to.
+ """
+ value = datasource.mirror_probe_request(
+ operator,
+ _probe_input(datasource, mapped_col, operator, sample_values),
+ mapped_col,
+ )
+ if is_unmirrorable(value):
+ # The same step the chart path applies, so the preview cannot promise a
+ # mirror the query declines -- and it reports the reason that step
+ # recorded rather than deriving one of its own, which is what let the
+ # offset case be explained as a precision loss it is not.
+ if value.reason == "offset":
+ # The transform is fine and the column may well compare the whole
+ # instant; what cannot be mirrored is the frame. Advising a
+ # different column here would send the owner after a column they
+ # already have.
+ return {
+ "valid": False,
+ "reason": "offset",
+ "sample_input": sample_input,
+ "error": _(
+ "A filter value carrying a UTC offset is not mirrored: a "
+ "transform is evaluated in the database's own time frame, "
+ "so the mirrored predicate could ask for a partition the "
+ "matching rows are not in. Write the bound without an "
+ "offset to mirror this filter.",
+ ),
+ }
+ # The transform is fine and the engine evaluates it, the filter just
+ # carries more of the value than the engine compares on this column --
+ # which is the column's type talking, not a broken expression.
+ return {
+ "valid": False,
+ "reason": "resolution",
+ "sample_input": sample_input,
+ "error": _(
+ "This engine compares less of a %(operator)s value on "
+ "%(column)s than the filter carries, so there is no mirror a "
+ "predicate on the partition column could stand in for. Map a "
+ "column the engine compares in full to mirror this operator.",
+ operator=operator.value,
+ column=mapped_col.column_name,
+ ),
+ }
+ errors: list[str] = []
+ type_errors: list[str] = []
+ predicates = build_mirrored_predicates(
+ datasource,
+ mapping,
+ [(operator, value)],
+ errors=errors,
+ type_errors=type_errors,
+ )
+ if type_errors:
+ # Its own reason, because "the database would not evaluate this" and
+ # "it evaluated and answered with the wrong kind of thing" are
+ # different problems with different fixes, and the owner is the only
+ # one who can tell which transform they meant to write.
+ return {
+ "valid": False,
+ "reason": "type",
+ "sample_input": sample_input,
+ "error": type_errors[0],
+ }
+ if not predicates:
+ return {
+ "valid": False,
+ "reason": "engine",
+ "sample_input": sample_input,
+ "error": (
+ _(
+ "The transform could not be evaluated against the "
+ "database: %(reason)s",
+ reason=errors[0],
+ )
+ if errors
+ else _("The transform could not be evaluated against the database.")
+ ),
+ }
+
+ return {
+ "valid": True,
+ "sample_input": sample_input,
+ "emitted_predicate": _render_predicate(datasource, predicates[0]),
+ }
+
+
+def _probe_input(
+ datasource: SqlaTable,
+ column: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+) -> Any:
+ """
+ The sample values as the query path would bind them.
+
+ The request carries samples as strings, and the probe is keyed on exactly
+ what it is handed, so passing them through raw asks the engine a different
+ question from the one a chart asks. A sample of ``2025`` on a numeric
+ column has to arrive as the integer the chart compares: under a transform
+ of ``typeof(:value)`` the raw string previewed ``'text'`` where the chart
+ emitted ``'integer'``. And because `_probe_cache_key` keys on each value's
+ ``repr``, the two also missed each other's cache entirely -- so the "a
+ previewed transform warms the chart path for free" claim in
+ `preview_partition_mapping`'s docstring did not actually hold.
+
+ Coerced by `filter_values_handler`, the same function the query path uses,
+ rather than by a second implementation of the same rules. Everything the
+ query path then does to the coerced value -- rendering an expression as a
+ literal, widening a bound, declining a comparison the engine resolves too
+ coarsely -- is `ExploreMixin.mirror_probe_request`'s, and the caller hands
+ this result straight to it.
+
+ Ranges are not previewable (see `PREVIEWABLE_OPERATORS`), so the bound
+ conversion `_collect_partition_mirror_range` applies -- a ``datetime`` into
+ the column's stored representation -- has no counterpart here.
+
+ An array column is the exception to `filter_values_handler`: its predicate
+ is built from the raw value, parsed into elements and rendered as the
+ engine's own array literal, so the chart path probes that literal
+ (`ExploreMixin._array_mirror_probe_value`) and this does too. Passing the
+ handled text instead previewed ``length('[1, 2]')`` for a filter whose
+ query probes ``length(array(1, 2))``.
+
+ Answers with a value, or `None` where an engine spec claims array columns
+ without an array literal -- which `mirror_probe_request` then declines, as
+ the chart path declines it. Otherwise `UNMIRRORABLE` is
+ `mirror_probe_request`'s to return, and the caller hands this straight to it.
+ """
+ is_list = operator == FilterOperator.IN
+ column_spec = datasource.db_engine_spec.get_column_spec(native_type=column.type)
+ if (
+ column_spec
+ and column_spec.generic_type == utils.GenericDataType.MULTI_VALUE
+ and operator in MIRRORABLE_ALWAYS
+ ):
+ # `=` and `IN` are the previewable operators the array branch builds a
+ # literal for; a bound on an array column binds the handled value on
+ # the chart path too, so it falls through to the same here.
+ return datasource._array_mirror_probe_value( # noqa: SLF001
+ sample_values if is_list else sample_values[0],
+ operator,
+ datasource.db_engine_spec.get_array_element_type(column.type),
+ datasource.db_engine_spec,
+ )
+ handled = datasource.filter_values_handler(
+ # `list[str]` is not a `list[FilterValue]` to mypy, invariantly, even
+ # though every `str` is a `FilterValue`.
+ values=cast(FilterValues, sample_values if is_list else sample_values[0]),
+ operator=operator,
+ target_generic_type=(
+ column_spec.generic_type if column_spec else utils.GenericDataType.STRING
+ ),
+ target_native_type=column.type,
+ is_list_target=is_list,
+ db_engine_spec=datasource.db_engine_spec,
+ db_extra=datasource.db_extra,
+ )
+ # No `ColumnElement` conversion here: an epoch-milliseconds sample comes back
+ # as engine SQL rather than a value, and `mirror_probe_request` renders it --
+ # the same step, on the same values, as for a chart filter.
+ return handled
+
+
+def _render_sample_input(
+ datasource: SqlaTable,
+ mapped_column: str,
+ operator: FilterOperator,
+ values: list[str],
+) -> str:
+ """
+ The filter being previewed, written the way an owner would read it.
+
+ Display-only -- it is never executed -- but it is still read as SQL, so the
+ column is quoted and the values are rendered by the dialect rather than
+ concatenated raw. A column named ``order date`` would otherwise come out as
+ two bare words.
+ """
+ quoted = datasource.quote_identifier(mapped_column)
+ if operator == FilterOperator.IN:
+ rendered = ", ".join(
+ _render_literal(datasource.database, value) for value in values
+ )
+ return f"{quoted} IN ({rendered})"
+ return (
+ f"{quoted} {operator.value} {_render_literal(datasource.database, values[0])}"
+ )
+
+
+def _render_predicate(datasource: SqlaTable, predicate: ColumnElement[Any]) -> str:
+ """
+ Compile a mirrored predicate to the text a reader would see in View query.
+
+ Every value in it is a probed constant by this point, so ``literal_binds``
+ renders the same literals the chart query carries.
+ """
+ return _compile_literal(predicate, _dialect_for(datasource.database)).replace(
+ "\n", " "
+ )
+
+
+def _render_literal(database: Database, value: Any) -> str:
+ """
+ Render a value the way it appears in the generated SQL.
+
+ Compiled by the dialect rather than formatted by hand. `str()` would render
+ a NULL as the Python repr `None` and leave a date unquoted, neither of which
+ is SQL, and hand-rolled quote-doubling would only ever have been right for
+ strings.
+ """
+ return _compile_literal(sa.literal(value), _dialect_for(database))
+
+
+def build_mirrored_predicates(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ requests: list[tuple[FilterOperator, Any]],
+ *,
+ errors: list[str] | None = None,
+ type_errors: list[str] | None = None,
+) -> list[ColumnElement[Any]]:
+ """
+ Turn collected ``(operator, value)`` mirror requests into predicates.
+
+ ``requests`` is expected to be deduplicated by the caller. Every value is
+ resolved in a single probe round trip -- one per chart query at most -- then
+ emitted as a literal constant, so "View query" shows the reader an ordinary
+ ``WHERE`` clause rather than an inline expression.
+
+ A strict bound is emitted non-strictly; see `mirror_operator`. That happens
+ here, at the one point where a ``FilterOperator`` becomes SQL, rather than
+ at the collection sites in `ExploreMixin`: the preview endpoint calls this
+ directly, so this is what keeps the predicate the editor shows an owner and
+ the predicate the chart carries from disagreeing.
+
+ :param errors: optional sink; see `evaluate_transform`.
+ :param type_errors: optional sink for a probe result the partition column
+ cannot hold -- see `probed_value_type_error`. Separate from ``errors``
+ because the two say different things to an owner: that one is "the
+ database would not evaluate this", and this one is "it evaluated, and
+ answered with the wrong kind of thing".
+ """
+ if not requests:
+ return []
+
+ partition_column = next(
+ (
+ column
+ for column in datasource.columns
+ if column.column_name == mapping.partition_column
+ ),
+ None,
+ )
+ if partition_column is None:
+ return []
+
+ # Flatten every value that needs probing into one list, remembering how many
+ # each request consumed so the results can be handed back out.
+ flat: list[Any] = []
+ spans: list[tuple[FilterOperator, int, int]] = []
+ for operator, value in requests:
+ values = list(value) if operator == FilterOperator.IN else [value]
+ spans.append((operator, len(flat), len(values)))
+ flat.extend(values)
+
+ evaluated = evaluate_transform(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ mapping.value_transform,
+ flat,
+ errors=errors,
+ )
+ if evaluated is None:
+ return []
+
+ if not _bounds_are_ordered(evaluated, spans):
+ return []
+
+ # Declining here is the last chance to decline at all: once these
+ # predicates are in the statement, a value the partition column cannot
+ # hold fails the whole chart rather than its pruning.
+ if reason := probed_value_type_error(partition_column, evaluated):
+ logger.warning(
+ "Partition transform returned a value the partition column cannot "
+ "hold; queries will not prune: %s",
+ reason,
+ )
+ if type_errors is not None:
+ type_errors.append(reason)
+ # Deliberately *not* recorded as a mirror verdict. The transform
+ # evaluated perfectly; what failed is the comparison against this
+ # dataset's partition column -- and `_mirror_verdict_cache_key` is
+ # keyed on database, catalog, schema and transform, with no partition
+ # column in it. Recorded, this dataset-specific outcome answered for
+ # every other dataset sharing the transform: `CAST(:value AS text)`
+ # mirroring happily onto a text key in dataset A was reported
+ # `evaluable: false` -- and its pruning indicator hidden -- because
+ # someone previewed the same transform against a numeric key in
+ # dataset B. A probe cache hit on A never rewrites the verdict, so it
+ # stayed wrong until the entry expired.
+ return []
+
+ sqla_col = datasource.convert_tbl_column_to_sqla_col(partition_column)
+ predicates = _predicates_from_probe(
+ sqla_col, datasource.db_engine_spec, evaluated, spans
+ )
+ if not predicates:
+ return []
+
+ # A comparison against a NULL partition value is NULL, so a row parked in a
+ # NULL partition is dropped by the mirror even when the real filter matches
+ # it -- Hive and Impala's default partition, or a transform that returns
+ # NULL for an input it cannot convert. The mirror only has to be no
+ # narrower than the filter it stands in for, so admitting NULL partitions
+ # keeps those rows. Engines still prune; they read one extra partition.
+ return [sa.or_(sa.and_(*predicates), sqla_col.is_(None))]
+
+
+def _predicates_from_probe(
+ sqla_col: ColumnElement[Any],
+ db_engine_spec: type[BaseEngineSpec],
+ evaluated: list[Any],
+ spans: list[tuple[FilterOperator, int, int]],
+) -> list[ColumnElement[Any]]:
+ """
+ One predicate on the partition column per surviving mirror request.
+
+ A request whose probe answered `None` for any of its values is skipped
+ rather than emitted: `col = NULL` is `NULL`, so it would drop every row the
+ filter keeps. A strict bound is emitted non-strictly; see `mirror_operator`.
+ """
+ predicates: list[ColumnElement[Any]] = []
+ for operator, start, length in spans:
+ chunk = evaluated[start : start + length]
+ if any(value is None for value in chunk):
+ continue
+ if operator == FilterOperator.IN:
+ # The probe answers per value, so a transform over a mixed-number
+ # filter can answer with a mixed-number partition key -- and
+ # `in_` infers the bind type from the first element it is handed.
+ # Without this, probe results of `[33, 29.02]` emit
+ # `IN (33, 29)` and prune away the partition holding `29.02`.
+ predicates.append(sqla_col.in_(normalize_mixed_numbers(chunk)))
+ else:
+ predicates.append(
+ db_engine_spec.handle_comparison_filter(
+ sqla_col, mirror_operator(operator), chunk[0]
+ )
+ )
+ return predicates
+
+
+#: Operators whose value is the lower end of a range, and whose upper-end twins.
+#:
+#: Shared with `ExploreMixin._mirror_probe_input`, which rounds a bound *outward*
+#: where the engine resolves it more coarsely than the filter carries -- backward
+#: for a lower bound, forward for an upper one. Which end an operator names is
+#: the only thing separating the two directions in either caller, so the two have
+#: to agree on it rather than each classify for itself.
+LOWER_BOUND_OPERATORS = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+}
+UPPER_BOUND_OPERATORS = {
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+#: What Python type a probe result may have, per generic type of the partition
+#: column it is about to be compared against.
+#:
+#: Only the types a mismatch can actually break a query with are listed. An
+#: unresolvable column type is absent because there is nothing to check
+#: against, and ``MULTI_VALUE`` because this module does not mirror onto an
+#: array partition key at all.
+#: ``numbers.Number`` rather than ``(int, float)``: Postgres answers
+#: ``extract(epoch from ...)`` with a `Decimal`, which is the single commonest
+#: transform this feature has, and an engine is free to answer with any number
+#: type its driver prefers. What the check is for is a *string* where a number
+#: belongs, and every numeric type is equally not that.
+_PROBE_RESULT_TYPES: dict[utils.GenericDataType, tuple[type, ...]] = {
+ utils.GenericDataType.NUMERIC: (numbers.Number,),
+ utils.GenericDataType.BOOLEAN: (bool,),
+ # A day key such as ``to_char(:value, 'YYYYMMDD')`` is legitimately text,
+ # so ``str`` is admitted -- but only for text *this* engine reads as an
+ # instant. `_reads_as_temporal` is the second half of this entry.
+ utils.GenericDataType.TEMPORAL: (datetime, date, str),
+ # Text, and not a number rendered as one. Not every engine accepts a number
+ # in a text comparison: Postgres refuses ``character varying = integer``,
+ # Trino ``varchar = bigint`` and BigQuery ``STRING = INT64``, all of which
+ # fail the whole chart once the predicate is in the statement. SQLite is
+ # worse -- it raises nothing and compares across storage classes as never
+ # equal, so the mirror drops every row rather than losing pruning, which is
+ # the one outcome this feature may not have. An owner whose partition key
+ # really is text writes the cast into the transform.
+ utils.GenericDataType.STRING: (str,),
+}
+
+
+#: The extended ISO 8601 date, which every engine reads as a date.
+#:
+#: Used to tell an ISO value apart from a merely ISO-*parseable* one:
+#: `datetime.fromisoformat` also accepts the basic forms -- ``20260115``,
+#: ``20260706100811`` -- and those are exactly what an engine may not read.
+#: BigQuery coerces a STRING literal to ``DATE`` only in the canonical
+#: ``YYYY-MM-DD`` form, so admitting the basic forms everywhere emitted
+#: ``part_date = '20260115'`` there and failed the chart.
+_ISO_DATE_PREFIX_RE = re.compile(r"^\d{4}-\d{2}-\d{2}")
+
+
+def _reads_as_temporal(value: str, db_engine_spec: type[BaseEngineSpec]) -> bool:
+ """
+ Whether this engine would read this text as a date or timestamp.
+
+ `_PROBE_RESULT_TYPES` admits ``str`` for a temporal partition column
+ because a day key such as ``to_char(:value, 'YYYYMMDD')`` is legitimately
+ text -- but it admitted *every* string, so a transform that answers with
+ ordinary text passed the gate and failed the chart instead. On PostgreSQL a
+ ``VARCHAR`` mapped column under ``lower(:value)`` probes ``'US'`` to
+ ``'us'`` and emits ``p = 'us'`` against a ``DATE`` key, which the engine
+ refuses once the predicate is already in the statement -- so a chart that
+ worked before the mapping returns an error rather than losing its pruning.
+
+ Which text counts is per engine beyond the extended ISO forms, because the
+ day key this feature exists for is not universal: PostgreSQL reads
+ ``'20260115'`` as a date, BigQuery coerces a STRING literal to ``DATE``
+ only in the canonical ``YYYY-MM-DD`` form, and Trino wants an explicit
+ cast. So an engine names what it reads in
+ `BaseEngineSpec.temporal_literal_formats` and says nothing by default,
+ which declines and costs only the pruning.
+
+ Answered by parsing, not by asking the engine: the check runs on the
+ chart-query path, where a second round trip is the cost this module spends
+ its effort avoiding. Parsing is also the conservative direction -- anything
+ unrecognised declines.
+ """
+ if _ISO_DATE_PREFIX_RE.match(value):
Review Comment:
Any extended-ISO string is treated as a date literal on every engine, but the docstring above says Trino wants an explicit cast. On Trino with `event_time TIMESTAMP`, `part_date DATE` and a monotonic transform such as `date_format(CAST(:value AS TIMESTAMP), '%Y-%m-%d')`, a Jan 15-16 range mirrors as `part_date >= '2026-01-15'`. Trino has no implicit VARCHAR-to-DATE comparison, so the chart errors instead of just losing pruning, and the preview still reports success because it only renders the predicate.
Could this accept ISO text only for engines that declare it (as `temporal_literal_formats` does for the other forms), or render a typed date literal for the rest?
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/usePartitionMappingPreview.ts:
##########
@@ -0,0 +1,163 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { SupersetClient, getClientErrorObject } from '@superset-ui/core';
+import { t } from '@apache-superset/core/translation';
+import { useDebounceValue } from 'src/hooks/useDebounceValue';
+import type { PartitionMappingPreview } from './types';
+import { transformCanPreview } from './utils';
+
+interface PreviewRequest {
+ datasetId?: number;
+ mappedColumn: string;
+ partitionColumn: string;
+ valueTransform: string;
+ sampleValues: string[];
+ operator: string;
+ isMonotonic: boolean;
+ /** Skip entirely when the section isn't showing a mapping. */
+ enabled: boolean;
+}
+
+/**
+ * Preview the predicate a transform would emit, debounced.
+ *
+ * The endpoint fires a real warehouse query, so the transform is debounced
+ * before it leaves the browser, and a transform that cannot work is not sent at
+ * all. Neither is a guard -- the server keeps a per-user, per-dataset budget of
+ * its own, and remains the authority on whether a transform is usable. The
+ * point is that a half-written transform should not spend that budget and leave
+ * none for the finished one.
+ */
+export function usePartitionMappingPreview({
+ datasetId,
+ mappedColumn,
+ partitionColumn,
+ valueTransform,
+ sampleValues,
+ operator,
+ isMonotonic,
+ enabled,
+}: PreviewRequest) {
+ const [preview, setPreview] = useState<PartitionMappingPreview | null>(null);
+ const [loading, setLoading] = useState(false);
+ // Which request the displayed state belongs to. `AbortController` alone is
+ // not enough: aborting settles nothing, so a handler still runs and has to
+ // ask whether it is still the current one. See the effect below.
+ const latestRequest = useRef(0);
+
+ const debouncedTransform = useDebounceValue(valueTransform, 500);
+ // `sampleValues` is a fresh array on every render, so depending on it
+ // directly would refire the effect -- and spend the preview budget -- on
+ // every keystroke elsewhere in the row. Depend on its serialized form and
+ // hand the effect a value whose identity tracks that same key.
+ const sampleKey = JSON.stringify(sampleValues);
+ const samples = useMemo<string[]>(() => JSON.parse(sampleKey), [sampleKey]);
+
+ useEffect(() => {
+ const transform = debouncedTransform?.trim();
+ // Claimed before the early return as well, so a request already in flight
+ // cannot come back and overwrite what this run decided.
+ latestRequest.current += 1;
+ const requestId = latestRequest.current;
+
+ if (
+ !enabled ||
+ !datasetId ||
+ !mappedColumn ||
+ !transformCanPreview(transform, mappedColumn, partitionColumn)
+ ) {
+ setPreview(null);
+ // The spinner belongs to a request this run has just superseded. Its own
+ // handlers see the abort and stop short of clearing it, so clearing it
+ // here is the only thing that does -- otherwise clearing the transform
+ // mid-flight left the panel spinning for good.
+ setLoading(false);
+ return undefined;
+ }
+
+ const controller = new AbortController();
+ setLoading(true);
+
+ SupersetClient.post({
+ endpoint: `/api/v1/dataset/${datasetId}/partition_mapping/preview/`,
+ jsonPayload: {
+ mapped_column: mappedColumn,
+ // The candidate, not the saved one: the owner is previewing a mapping
+ // they have not committed yet.
+ partition_column: partitionColumn,
+ value_transform: transform,
+ sample_values: samples,
+ operator,
+ is_monotonic: isMonotonic,
+ },
+ signal: controller.signal,
+ })
+ .then(({ json }) => {
+ // This hits a live warehouse query, so responses can arrive out of
+ // order. Without this an older one overwrites the current preview and
+ // reports "Valid" for a transform the input no longer holds.
+ if (requestId !== latestRequest.current) {
+ return;
+ }
+ setPreview(json.result as PartitionMappingPreview);
+ })
+ .catch(async error => {
+ if (requestId !== latestRequest.current) {
+ return;
+ }
+ const clientError = await getClientErrorObject(error);
Review Comment:
The staleness check runs before `await getClientErrorObject(error)`, but not after it. If request A fails, passes the check and is still normalizing its error while request B becomes current and returns a valid preview, A then calls `setPreview` with its error and overwrites B's result. The panel then shows an error for the transform the box actually holds. Could the check be repeated after the await, with a test that delays A's error normalization until B has resolved?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "eschutho (via GitHub)" <gi...@apache.org>.
eschutho commented on PR #43870:
URL: https://github.com/apache/superset/pull/43870#issuecomment-6136106669
On Hugh's behalf: ad5bb47d4b rewrites `contains_jinja` in `partition_mapping.py` to clear CodeQL alert #3953 (`py/polynomial-redos`).
- **What changed:** the lazy `{{.*?}}|{%.*?%}|{#.*?#}` regex is replaced with a linear `str.find` scan: the first opening delimiter of each kind, then a closing delimiter after it. It gives the same answer on every input. A new test checks it against the old pattern on every string of up to seven characters over the delimiter characters, and another times a 200,000-delimiter run.
- **Why not a length cap:** `is_transform_active` runs this on *stored* transforms, which have no length bound, so a cap would have let an over-long stored transform containing Jinja skip the Jinja refusal. Without a bound, the old pattern was genuinely slow: about 10 s on 40 KB of `{{`.
- **CodeQL:** the run on the new head passes, and #3953 is reported as fixed on the PR merge ref, so no maintainer dismissal is needed.
Re-requested review from @aminghadersohi and @sadpandajoe.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "hughhhh (via GitHub)" <gi...@apache.org>.
hughhhh commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4162114560
##########
superset-frontend/src/explore/components/PartitionPruningIndicator/index.tsx:
##########
@@ -0,0 +1,80 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { t } from '@apache-superset/core/translation';
+import { css, useTheme } from '@apache-superset/core/theme';
+import { Icons, Tooltip } from '@superset-ui/core/components';
+import type { PartitionFilterMapping } from '@superset-ui/chart-controls';
+
+interface PartitionPruningIndicatorProps {
+ /** The dataset's mapping summary, straight off the datasource payload. */
+ mapping?: PartitionFilterMapping | null;
+}
+
+/**
+ * The glyph on a filter whose column is mirrored onto a partition column
+ * (wireframe 1d).
+ *
+ * Chart authors do not configure any of this and ideally never learn the word
+ * "partition"; the indicator exists only to explain why their query got faster,
+ * and to point at the generated SQL where the extra predicate is visible.
+ */
+export default function PartitionPruningIndicator({
+ mapping,
+}: PartitionPruningIndicatorProps) {
+ const theme = useTheme();
+
+ if (!mapping?.active) {
+ return null;
+ }
+
+ return (
+ <Tooltip
+ placement="top"
+ title={t(
+ 'This filter is also applied to a partition column for faster queries. See "View query" for the generated SQL.',
+ )}
+ >
+ <span data-test="partition-pruning-indicator">
+ <Icons.FilterOutlined
+ iconSize="s"
+ iconColor={theme.colorSuccess}
+ css={css`
+ margin-left: ${theme.sizeUnit}px;
+ vertical-align: middle;
+ `}
+ />
+ </span>
+ </Tooltip>
+ );
+}
+
+/**
+ * Whether a filter on `columnName` is the one being mirrored.
+ *
+ * The mapping names exactly one mapped column, so anything else on the chart --
+ * including other filters on the same dataset -- gets no indicator.
+ */
+export function isMirroredColumn(
+ mapping: PartitionFilterMapping | null | undefined,
+ columnName: string | null | undefined,
+): boolean {
+ return Boolean(
+ mapping?.active && columnName && mapping.mapped_column === columnName,
+ );
Review Comment:
Fixed in `bdfaeb9299` (earlier on this branch). `isMirroredFilter` checks the operator against `mirrorable_operators`, which the server computes from the transform's declared monotonicity — so `country != 'US'` gets no glyph. Tested at `PartitionPruningIndicator.test.tsx`.
##########
superset-frontend/packages/superset-ui-chart-controls/src/shared-controls/sharedControls.tsx:
##########
@@ -208,9 +208,56 @@ const time_grain_sqla: SharedControlConfig<'SelectControl'> = {
sortComparator: () => 0, // Disable frontend sorting to preserve backend order
};
+/**
+ * The mapping to hand the time control's partition-pruning indicator, or `null`
+ * when this time range is not mirrored.
+ *
+ * The control renders whatever mapping it is given, so the applicability check
+ * belongs here, where the selected temporal column and the range are both in
+ * scope. Unlike an ad-hoc filter chip the control names no column of its own:
+ * the query path mirrors the time range only when the *chart's* temporal column
+ * is the mapped one (`superset/models/helpers.py`, the `granularity` and
+ * `always_filter_main_dttm` branches), and only when the range resolves to at
+ * least one bound -- `No filter` resolves to neither.
+ */
+function timeRangePartitionMapping({
+ datasource,
+ form_data: formData,
+}: ControlPanelState) {
+ const dataset = datasource as Dataset | null;
+ const mapping = dataset?.partition_filter_mapping;
+ if (
+ !mapping?.active ||
+ !mapping.mirrorable_operators?.includes('TEMPORAL_RANGE')
+ ) {
+ return null;
+ }
+ if (formData?.time_range === NO_TIME_RANGE) {
+ return null;
+ }
+ const granularity = formData?.granularity_sqla;
+ const selectedColumn = isDefined(granularity)
+ ? getColumnLabel(granularity)
+ : undefined;
+ const mirrorsSelectedColumn = selectedColumn === mapping.mapped_column;
+ // `always_filter_main_dttm` adds a second time filter on the main datetime
+ // column even when the chart groups by another one, and that filter mirrors.
+ const mirrorsMainDttm = Boolean(
+ dataset?.always_filter_main_dttm &&
+ dataset.main_dttm_col === mapping.mapped_column,
+ );
+ return mirrorsSelectedColumn || mirrorsMainDttm ? mapping : null;
+}
+
const time_range: SharedControlConfig<'DateFilterControl'> = {
type: 'DateFilterControl',
freeForm: true,
+ // The indicator needs to know whether this filter is mirrored onto a
+ // partition column; the summary is self-contained on the datasource so this
+ // does not have to reach into `columns`.
+ mapStateToProps: state => ({
Review Comment:
Fixed in `46e4cd7c54` + `e21eac2728` (earlier on this branch). The control opts into render-time recalculation (`shouldMapStateToProps: () => true`) and names `granularity_sqla` in `validationDependencies`. The field-update regression case is `ControlPanelsContainer.test.tsx` — "the partition glyph drops when the time range becomes 'No filter'", built deliberately against the pre-action control state.
##########
superset/daos/dataset.py:
##########
@@ -461,7 +464,12 @@ def update(
if force_update:
attributes["changed_on"] = datetime.now()
- return super().update(item, attributes)
+ updated = super().update(item, attributes)
+ # After the dataset-level attributes land, not before: the mapped column
+ # is `partition_mapped_column or main_dttm_col`, and either can be part
+ # of this very request.
+ cls.clear_unmapped_partition_transforms(updated)
Review Comment:
Fixed in `1e132aefc9`. Right — it discards stored configuration, so it had no business running on a write that cannot change which column is mirrored. It is now gated on the request actually touching `columns`, `main_dttm_col`, `partition_column` or `partition_mapped_column` (`PARTITION_MAPPING_ATTRIBUTES`). Pinned by `test_an_unrelated_save_leaves_a_stray_transform_alone`, which drives a `description`-only `update()`.
##########
superset/daos/dataset.py:
##########
@@ -475,6 +483,48 @@ def _validate_column_date_formats(
"python_date_format is an invalid date/timestamp format."
)
+ @staticmethod
+ def clear_unmapped_partition_transforms(model: SqlaTable) -> None:
+ """
+ Drop the value transform from every column the mapping does not mirror.
+
+ A mapping has exactly one mirrored column, so at most one column may
+ carry a transform. A transform parked on any other column is invisible
+ -- no row but the mapped one renders one -- yet it is still stored, and
+ it goes live the moment the mapped column resolves back to it. Clearing
+ an override is enough to do that: a null `partition_mapped_column` means
+ "follow `main_dttm_col`", so dropping a mapping would otherwise activate
+ whatever the default datetime column happened to be holding, turning a
+ request to remove a mapping into a request to add a different one.
+
+ Enforced here rather than in the editor alone because the editor is only
+ one writer: a PUT, an `override_columns=true` metadata sync and an
+ import all reach the columns directly. The same argument
+ `clear_dangling_partition_mapping` makes about dangling columns.
+
+ Gated on the feature flag, unlike its sibling, because this discards
+ stored configuration rather than repairing a broken reference. With the
+ flag off nothing mirrors, so there is no armed mapping to disarm and
+ clearing would be pure loss.
+ """
+ if not feature_flag_manager.is_feature_enabled(PARTITION_FILTER_MAPPING_FLAG):
+ return
+
+ mapped_column = (
+ (model.partition_mapped_column or model.main_dttm_col)
+ if model.partition_column
+ else None
+ )
+ for column in model.columns:
Review Comment:
Fixed in `1e132aefc9`. Confirmed, and it was the one case the method most needed to catch. `db.session.flush()` + `db.session.expire(model, ["columns"])` now run before the loop, so the collection reflects the FK inserts. Pinned by `test_a_transform_on_a_column_added_in_the_same_request_is_cleared`, which adds a column *with* a transform and points the mapping elsewhere in one request — it fails without the flush.
##########
superset-frontend/src/explore/components/PartitionPruningIndicator/index.tsx:
##########
@@ -0,0 +1,169 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { t } from '@apache-superset/core/translation';
+import { css, useTheme } from '@apache-superset/core/theme';
+import { NO_TIME_RANGE } from '@superset-ui/core';
+import { Icons, Tooltip } from '@superset-ui/core/components';
+import type { PartitionFilterMapping } from '@superset-ui/chart-controls';
+import { ExpressionTypes } from 'src/explore/components/controls/FilterControl/types';
+
+interface PartitionPruningIndicatorProps {
+ /** The dataset's mapping summary, straight off the datasource payload. */
+ mapping?: PartitionFilterMapping | null;
+}
+
+/**
+ * The parts of an ad-hoc filter that decide whether it is mirrored. Structural
+ * rather than the `AdhocFilter` class so native filters and cross-filters --
+ * which reach the query path in the same shape but are not that class -- can be
+ * checked with the same function.
+ */
+export interface MirrorCandidateFilter {
+ expressionType?: string;
+ subject?: string | { column_name?: string } | null;
+ operator?: string | null;
+ comparator?: unknown;
+}
+
+/**
+ * The glyph on a filter whose column is mirrored onto a partition column
+ * (wireframe 1d).
+ *
+ * Chart authors do not configure any of this and ideally never learn the word
+ * "partition"; the indicator exists only to explain why their query got faster,
+ * and to point at the generated SQL where the extra predicate is visible.
+ */
+export default function PartitionPruningIndicator({
+ mapping,
+}: PartitionPruningIndicatorProps) {
+ const theme = useTheme();
+
+ if (!mapping?.active) {
+ return null;
+ }
+
+ return (
+ <Tooltip
+ placement="top"
+ title={t(
+ 'This filter is also applied to a partition column for faster queries. See "View query" for the generated SQL.',
+ )}
+ >
+ <span data-test="partition-pruning-indicator">
+ <Icons.FilterOutlined
+ iconSize="s"
+ iconColor={theme.colorSuccess}
+ css={css`
+ margin-left: ${theme.sizeUnit}px;
+ vertical-align: middle;
+ `}
+ />
+ </span>
+ </Tooltip>
+ );
+}
+
+/**
+ * The filter's column name. `subject` is a bare string for simple filters and a
+ * column object when the filter was built from a dropped column.
+ */
+function subjectName(
+ subject: MirrorCandidateFilter['subject'],
+): string | undefined {
+ return typeof subject === 'string'
+ ? subject
+ : (subject?.column_name ?? undefined);
+}
+
+/**
+ * Whether `columnName` is the one column the mapping mirrors.
+ *
+ * Necessary but not sufficient for the glyph -- see `isMirroredFilter`.
+ */
+export function isMirroredColumn(
+ mapping: PartitionFilterMapping | null | undefined,
+ columnName: string | null | undefined,
+): boolean {
+ return Boolean(
+ mapping?.active && columnName && mapping.mapped_column === columnName,
+ );
+}
+
+/**
+ * Whether the comparator is one the mirrored predicate can be built from.
+ *
+ * A `NULL` inside an `IN` list widens the real predicate to
+ * `col IS NULL OR col IN (...)`, which the mirror cannot express, so the
+ * backend skips those lists outright.
+ */
+function hasMirrorableValue(operator: string, comparator: unknown): boolean {
+ if (operator === 'TEMPORAL_RANGE') {
+ // `No filter` resolves to neither bound, so no range is mirrored.
+ return typeof comparator === 'string' && comparator !== NO_TIME_RANGE;
+ }
+ if (operator === 'IN') {
+ return (
+ Array.isArray(comparator) &&
+ comparator.length > 0 &&
+ !comparator.some(value => value == null)
+ );
+ }
+ return comparator !== null && comparator !== undefined && comparator !== '';
+}
+
+/**
+ * Whether this filter actually produces a predicate on the partition column.
+ *
+ * Naming the mapped column is only the first of the query path's gates
+ * (`_collect_partition_mirror_filter` in `superset/models/helpers.py`): the
+ * operator has to be one the mapping can mirror, and the value has to be one
+ * the mirrored predicate can carry. A `country != 'US'` chip names the mapped
+ * column and mirrors nothing -- negations are never safe, because the transform
+ * need not be injective -- so labelling it would promise a speed-up the query
+ * does not deliver.
+ *
+ * The operator list is not restated here; it is computed server-side from the
+ * transform's declared monotonicity and shipped on the mapping.
+ */
+export function isMirroredFilter(
+ mapping: PartitionFilterMapping | null | undefined,
+ filter: MirrorCandidateFilter | null | undefined,
+): boolean {
+ if (!mapping?.active || !filter) {
+ return false;
+ }
+ // Free-form SQL filters are appended verbatim as `extras.where`; the backend
+ // never sees an (operator, value) pair to mirror.
+ if (
+ filter.expressionType &&
+ filter.expressionType !== ExpressionTypes.Simple
+ ) {
+ return false;
+ }
+ if (!isMirroredColumn(mapping, subjectName(filter.subject))) {
+ return false;
+ }
+ if (
+ !filter.operator ||
+ !mapping.mirrorable_operators?.includes(filter.operator)
+ ) {
+ return false;
+ }
+ return hasMirrorableValue(filter.operator, filter.comparator);
Review Comment:
Fixed in `1e132aefc9`. Both accounted for. `MirrorCandidateFilter` carries `grain`, and a grain on anything but `TEMPORAL_RANGE` now means no glyph — matching the `and not filter_grain` skip in `models/helpers.py`. A grained range still shows, since that one mirrors by widening both bounds. `hasMirrorableValue` also recognises `NULL_STRING`, for the bare `==` case as well as inside an `IN` list.
##########
superset-frontend/packages/superset-ui-chart-controls/src/shared-controls/sharedControls.tsx:
##########
@@ -208,9 +208,68 @@ const time_grain_sqla: SharedControlConfig<'SelectControl'> = {
sortComparator: () => 0, // Disable frontend sorting to preserve backend order
};
+/**
+ * The mapping to hand the time control's partition-pruning indicator, or `null`
+ * when this time range is not mirrored.
+ *
+ * The control renders whatever mapping it is given, so the applicability check
+ * belongs here, where the selected temporal column and the range are both in
+ * scope. Unlike an ad-hoc filter chip the control names no column of its own:
+ * the query path mirrors the time range only when the *chart's* temporal column
+ * is the mapped one (`superset/models/helpers.py`, the `granularity` and
+ * `always_filter_main_dttm` branches), and only when the range resolves to at
+ * least one bound -- `No filter` resolves to neither.
+ */
+function timeRangePartitionMapping({
+ datasource,
+ form_data: formData,
+}: ControlPanelState) {
+ const dataset = datasource as Dataset | null;
+ const mapping = dataset?.partition_filter_mapping;
+ if (
+ !mapping?.active ||
+ !mapping.mirrorable_operators?.includes('TEMPORAL_RANGE')
+ ) {
+ return null;
+ }
+ if (formData?.time_range === NO_TIME_RANGE) {
+ return null;
+ }
+ const granularity = formData?.granularity_sqla;
+ const selectedColumn = isDefined(granularity)
+ ? getColumnLabel(granularity)
+ : undefined;
+ const mirrorsSelectedColumn = selectedColumn === mapping.mapped_column;
+ // `always_filter_main_dttm` adds a second time filter on the main datetime
+ // column even when the chart groups by another one, and that filter mirrors.
+ const mirrorsMainDttm = Boolean(
Review Comment:
Fixed in `1e132aefc9`. `mirrorsMainDttm` now requires a selected granularity, so it cannot fire where the backend's `if granularity:` branch never runs. The existing test always passed a truthy `granularity_sqla`, so the negative case is now covered too.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #43870:
URL: https://github.com/apache/superset/pull/43870#issuecomment-6102875363
### ⚠️ Possible DB migration conflict
@hughhhh the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
To check and, if needed, fix this:
1. Rebase this branch onto the latest `master`.
2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4237885578
##########
superset-frontend/src/explore/components/PartitionPruningIndicator/index.tsx:
##########
@@ -0,0 +1,333 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { t } from '@apache-superset/core/translation';
+import { css, useTheme } from '@apache-superset/core/theme';
+import { NO_TIME_RANGE } from '@superset-ui/core';
+import { Button, Icons, Tooltip } from '@superset-ui/core/components';
+import type { PartitionFilterMapping } from '@superset-ui/chart-controls';
+import { ExpressionTypes } from 'src/explore/components/controls/FilterControl/types';
+import { NULL_STRING } from 'src/utils/common';
+
+interface PartitionPruningIndicatorProps {
+ /** The dataset's mapping summary, straight off the datasource payload. */
+ mapping?: PartitionFilterMapping | null;
+}
+
+/**
+ * The parts of an ad-hoc filter that decide whether it is mirrored. Structural
+ * rather than the `AdhocFilter` class so native filters and cross-filters --
+ * which reach the query path in the same shape but are not that class -- can be
+ * checked with the same function.
+ */
+export interface MirrorCandidateFilter {
+ expressionType?: string;
+ subject?: string | { column_name?: string } | null;
+ operator?: string | null;
+ comparator?: unknown;
+ /**
+ * The time grain a drill-to-detail filter carries. Present here because it
+ * decides whether the filter mirrors at all -- see `isMirroredFilter`.
+ */
+ grain?: string | null;
+}
+
+/**
+ * Whether this mapping mirrors anything at all.
+ *
+ * `active` is the save path's verdict -- a parse, which a misspelled function
+ * clears happily -- so on its own it promised a speed-up for a transform the
+ * database rejects: the probe fails at query time, the mirror is dropped, and
+ * nothing said so. `evaluable` is the weaker claim the engine answers, and
+ * `null` means nothing has probed yet, which is not a reason to go quiet.
+ */
+function mirrorsAnything(
+ mapping: PartitionFilterMapping | null | undefined,
+): mapping is PartitionFilterMapping {
+ // A type predicate rather than a `boolean`: an absent mapping mirrors
+ // nothing, so `true` here means there is one, and the callers that go on to
+ // read its fields should not each have to re-establish that.
+ return Boolean(mapping?.active) && mapping?.evaluable !== false;
+}
+
+/**
+ * The glyph on a filter whose column is mirrored onto a partition column
+ * (wireframe 1d).
+ *
+ * Chart authors do not configure any of this and ideally never learn the word
+ * "partition"; the indicator exists only to explain why their query got faster,
+ * and to point at the generated SQL where the extra predicate is visible.
+ */
+export default function PartitionPruningIndicator({
+ mapping,
+}: PartitionPruningIndicatorProps) {
+ const theme = useTheme();
+
+ if (!mirrorsAnything(mapping)) {
+ return null;
+ }
+
+ const explanation = t(
+ 'This filter is also applied to a partition column for faster queries. See "View query" for the generated SQL.',
+ );
+
+ return (
+ <Tooltip placement="top" title={explanation}>
+ {/* A text-variant `Button` rather than a `span`, the same shape
+ `InfoTooltip` uses: the glyph's only explanation is this tooltip, and
+ on a non-focusable element with no accessible name a keyboard or
+ screen-reader user has no way to reach it. */}
+ <Button
+ type="text"
+ variant="text"
+ data-test="partition-pruning-indicator"
+ aria-label={explanation}
+ css={css`
+ box-shadow: none;
+ padding: 0;
+ height: auto;
+ background: none;
+ vertical-align: middle;
+ &&&:hover,
+ &&&:focus,
+ &&&:active {
+ box-shadow: none;
+ background: none;
+ }
+ `}
+ icon={
+ <Icons.FilterOutlined
+ iconSize="s"
+ iconColor={theme.colorSuccess}
+ css={css`
+ margin-left: ${theme.sizeUnit}px;
+ `}
+ />
+ }
+ />
+ </Tooltip>
+ );
+}
+
+/**
+ * The filter's column name. `subject` is a bare string for simple filters and a
+ * column object when the filter was built from a dropped column.
+ */
+function subjectName(
+ subject: MirrorCandidateFilter['subject'],
+): string | undefined {
+ return typeof subject === 'string'
+ ? subject
+ : (subject?.column_name ?? undefined);
+}
+
+/**
+ * Whether `columnName` is the one column the mapping mirrors.
+ *
+ * Necessary but not sufficient for the glyph -- see `isMirroredFilter`.
+ */
+export function isMirroredColumn(
+ mapping: PartitionFilterMapping | null | undefined,
+ columnName: string | null | undefined,
+): boolean {
+ return Boolean(
+ mirrorsAnything(mapping) &&
+ columnName &&
+ mapping.mapped_column === columnName,
+ );
+}
+
+/** Whether a comparator reaches the query path as a real `NULL`. */
+function isNullish(value: unknown): boolean {
+ // `<NULL>` is the sentinel Explore puts in a filter value for a real NULL;
+ // `filter_values_handler` converts it back to `None` server-side, so it is
+ // nullish here for exactly the same reason `null` is.
+ return value == null || value === NULL_STRING;
+}
+
+const ISO_DATETIME =
+ /^\d{4}-\d{2}-\d{2}[ T](\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?)$/;
+const MIDNIGHT = /^00:00(?::00(?:\.0+)?)?$/;
+
+/**
+ * A value written as an ISO date *and* a non-zero time of day.
+ *
+ * Deliberately narrower than the backend's `datetime.fromisoformat`, and
+ * deliberately only ever used to *hide* the glyph. `Date.parse` accepts strings
+ * `fromisoformat` rejects and the reverse, so matching the server's acceptance
+ * set here is not achievable; what is achievable is a pattern that only ever
+ * fires on a value the server certainly declines. Anything else falls back to
+ * showing the glyph, which is the advisory behaviour this control has always
+ * had -- see `isMirroredFilter`.
+ */
+function carriesTimeOfDay(value: unknown): boolean {
+ if (typeof value !== 'string') {
+ return false;
+ }
+ const time = ISO_DATETIME.exec(value)?.[1];
+ // Midnight is not a time of day for this purpose: the engine's comparison and
+ // the mirror's value agree there, so the filter does mirror.
+ return time !== undefined && !MIDNIGHT.test(time);
+}
+
+/** A zero-padded ISO calendar date, extended (`2024-01-01`) or basic (`20240101`). */
+const ISO_DATE_PREFIX = /^\d{4}(-\d{2}-\d{2}|\d{4})/;
+
+/**
+ * Whether the server stands a chance of reading this value as an instant.
+ *
+ * Where the engine compares less of a value than it carries, the mirror is
+ * built from an instant -- and a string `datetime.fromisoformat` declines is not
+ * one, so the query path declines the filter outright rather than hand the text
+ * to the probe and get a predicate narrower than the filter.
+ *
+ * The same trade as `carriesTimeOfDay`, in the other direction: this is used
+ * only to *hide* the glyph, so it has to fire only on text the server certainly
+ * cannot read. A leading zero-padded ISO date is the test, because everything
+ * `fromisoformat` accepts begins with one and the formats that reached this bug
+ * -- `07/06/2026 10:08:11`, `2026/07/06 10:08:11`, `July 6 2026 10:08:11` -- do
+ * not. Non-strings are left to the gates above: a number is not text the server
+ * reads, and the mirror is built from it the same way either way.
+ */
+function readableAsInstant(value: unknown): boolean {
+ return typeof value !== 'string' || ISO_DATE_PREFIX.test(value);
+}
+
+/**
+ * Whether the comparator is one the mirrored predicate can be built from.
+ *
+ * A `NULL` inside an `IN` list widens the real predicate to
+ * `col IS NULL OR col IN (...)`, which the mirror cannot express, so the
+ * backend skips those lists outright.
+ *
+ * An empty string is *not* excluded. The backend's mirror collector skips only
+ * `None`, so `col = ''` -- which Explore writes as the `<empty string>`
+ * sentinel -- does mirror, and hiding the glyph for it contradicted the SQL.
+ *
+ * On a mapped column the engine compares at day resolution, an `=` or `IN`
+ * whose value carries a time of day is declined server-side: the filter keeps
+ * the whole day while a mirror derived from the time keeps one instant of it,
+ * and an AND-ed equality has nowhere to widen to. Only those two operators --
+ * a bound does have somewhere to widen to, and widens to the day rather than
+ * declining, so the glyph stays on it.
+ *
+ * Wherever the engine compares less than the whole value, a value the server
+ * cannot read as an instant at all is declined for *every* operator, a bound
+ * included -- there is no instant to widen. So that gate is the broader of the
+ * two, and the only one that applies at `second` resolution as well, where what
+ * the engine drops is a sub-second part no pattern here can see.
+ */
+function hasMirrorableValue(
+ operator: string,
+ comparator: unknown,
+ resolution: PartitionFilterMapping['literal_resolution'],
+): boolean {
+ if (operator === 'TEMPORAL_RANGE') {
+ // `No filter` resolves to neither bound, so no range is mirrored. A range
+ // is resolved to a pair of bounds server-side rather than read as one
+ // instant, so neither resolution gate below applies to it.
+ return typeof comparator === 'string' && comparator !== NO_TIME_RANGE;
+ }
+ const comparesLessThanTheValue =
+ resolution === 'day' || resolution === 'second';
+ if (operator === 'IN') {
+ return (
+ Array.isArray(comparator) &&
+ comparator.length > 0 &&
+ !comparator.some(isNullish) &&
+ !(
+ comparesLessThanTheValue &&
+ comparator.some(member => !readableAsInstant(member))
+ ) &&
+ !(resolution === 'day' && comparator.some(carriesTimeOfDay))
+ );
+ }
+ if (comparesLessThanTheValue && !readableAsInstant(comparator)) {
+ return false;
+ }
+ if (
+ operator === '==' &&
+ resolution === 'day' &&
+ carriesTimeOfDay(comparator)
+ ) {
+ return false;
+ }
+ return !isNullish(comparator);
+}
+
+/**
+ * Whether this filter actually produces a predicate on the partition column.
+ *
+ * Naming the mapped column is only the first of the query path's gates
+ * (`_collect_partition_mirror_filter` in `superset/models/helpers.py`): the
+ * operator has to be one the mapping can mirror, and the value has to be one
+ * the mirrored predicate can carry. A `country != 'US'` chip names the mapped
+ * column and mirrors nothing -- negations are never safe, because the transform
+ * need not be injective -- so labelling it would promise a speed-up the query
+ * does not deliver.
+ *
+ * The operator list is not restated here; it is computed server-side from the
+ * transform's declared monotonicity and shipped on the mapping.
+ *
+ * One gate is deliberately not reproduced. A virtual dataset's SQL can consume
+ * a filter with a Jinja `get_filters('col', remove_filter=True)` call, and
+ * `should_skip_filter` then drops both the filter's own predicate and its
+ * mirror -- so the glyph can appear on a filter that produces no SQL at all.
+ * `removed_filters` is assembled while the query is generated and is not in
+ * `form_data`, so the only way to know would be to render the template in the
+ * browser. The glyph is advisory, and "View query" remains the authority.
+ */
+export function isMirroredFilter(
+ mapping: PartitionFilterMapping | null | undefined,
+ filter: MirrorCandidateFilter | null | undefined,
+): boolean {
+ if (!mirrorsAnything(mapping) || !filter) {
+ return false;
+ }
+ // Free-form SQL filters are appended verbatim as `extras.where`; the backend
+ // never sees an (operator, value) pair to mirror.
+ if (
+ filter.expressionType &&
+ filter.expressionType !== ExpressionTypes.Simple
+ ) {
+ return false;
+ }
+ if (!isMirroredColumn(mapping, subjectName(filter.subject))) {
+ return false;
+ }
+ if (
+ !filter.operator ||
+ !mapping.mirrorable_operators?.includes(filter.operator)
+ ) {
+ return false;
+ }
+ // A grain makes the real predicate compare the *truncated* column, so the raw
+ // value no longer describes the rows it matches: drill-to-detail sends `==` on
+ // a bucket start, which every row in the bucket satisfies once truncated.
+ // `_collect_partition_mirror_filter` is skipped entirely for those, so the
+ // glyph would promise pruning the query does not do. A grained range is the
+ // exception -- it mirrors by widening both bounds.
+ if (filter.grain && filter.operator !== 'TEMPORAL_RANGE') {
+ return false;
+ }
+ return hasMirrorableValue(
Review Comment:
With an active mapping on a column the engine compares at full resolution, a filter like `event_time >= '2026-01-01T01:00:00+01:00'` still gets the pruning glyph, but the query path declines any value carrying a UTC offset before the full-resolution return (`_mirror_probe_input` in `helpers.py`), so no partition predicate is emitted and the glyph promises pruning that doesn't happen. `hasMirrorableValue` only looks at time-of-day/readability at day or second resolution and never checks for an offset. Should an explicit offset/`Z` suffix hide the glyph for every resolution, with a case in `PartitionPruningIndicator.test.tsx` asserting `isMirroredFilter(...) === false` for it?
##########
superset/datasets/api.py:
##########
@@ -2075,6 +2178,131 @@ def get(self, id_or_uuid: str, **kwargs: Any) -> Response:
entity_concurrency_token(SqlaTable, table.id, table.uuid),
)
+ @expose("/<int:pk>/partition_mapping/preview/", methods=("POST",))
+ @protect()
+ @safe
+ @statsd_metrics
+ @event_logger.log_this_with_context(
+ action=lambda self, *args, **kwargs: (
+ f"{self.__class__.__name__}.partition_mapping_preview"
+ ),
+ log_to_statsd=False,
+ )
+ def partition_mapping_preview(self, pk: int) -> Response:
+ """Preview the predicate a partition value transform would emit.
+ ---
+ post:
+ summary: Preview a partition filter mapping
+ description: >-
+ Evaluate a partition value transform at sample values and return
+ the predicate that would be appended to queries. The predicate is
+ built by the same code the query path uses, so the preview cannot
+ drift from what a chart emits. Parse and denylist checks run
+ before anything reaches the engine, so an unparseable transform
+ costs no query.
+ parameters:
+ - in: path
+ schema:
+ type: integer
+ name: pk
+ description: The dataset ID
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/PartitionMappingPreviewSchema'
+ responses:
+ 200:
+ description: Preview result
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ result:
+ type: object
+ properties:
+ valid:
+ type: boolean
+ reason:
+ type: string
+ description: >-
+ Why the mapping is not valid. Absent when it is.
+ The editor branches on this to decide how to
+ present the failure.
+ enum:
+ - unconfigured
Review Comment:
The preview can return `reason: "offset"` (a temporal sample carrying a UTC offset, e.g. `2026-01-01T01:00:00+01:00`, comes back as HTTP 200 with that reason, and the new regression test asserts it), but this enum, and the generated `openapi.json` entry, stop at `type`. A client generated from the spec with a strict enum would reject that response, even though the TypeScript type already includes `offset`. Could `offset` be added here and the spec regenerated?
##########
tests/unit_tests/connectors/sqla/partition_mapping_test.py:
##########
@@ -0,0 +1,2674 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Unit tests for ``superset.connectors.sqla.partition_mapping``."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from decimal import Decimal
+from importlib import import_module
+from typing import Any, cast
+from unittest.mock import MagicMock, patch, PropertyMock
+
+import pandas as pd
+import pytest
+from dateutil.relativedelta import relativedelta
+from flask import Flask
+from sqlalchemy.dialects import mysql, postgresql
+
+from superset.config import DISALLOWED_SQL_FUNCTIONS
+from superset.connectors.sqla.models import SqlaTable, TableColumn
+from superset.connectors.sqla.partition_mapping import (
+ _mirror_verdict_cache_key,
+ _placeholder_is_bindable,
+ _probe_cache_key,
+ _reads_as_temporal,
+ _render_literal,
+ build_mirrored_predicates,
+ build_probe_sql,
+ contains_executable_comment,
+ contains_jinja,
+ contains_value_placeholder,
+ drop_unmapped_value_transforms,
+ equality_mirrors_safely,
+ evaluate_transform,
+ find_non_deterministic_functions,
+ grain_bucket_width,
+ GRAIN_BUCKET_WIDTHS,
+ is_bare_expression,
+ is_parseable,
+ is_transform_active,
+ is_unfinished,
+ known_mirror_verdict,
+ MappingValidationIssue,
+ mirror_operator,
+ MIRRORABLE_ALWAYS,
+ MIRRORABLE_IF_MONOTONIC,
+ mirrorable_operators,
+ parse_error_detail,
+ placeholder_is_executable,
+ probe_sql_is_evaluable,
+ probed_value_type_error,
+ RawProbeValue,
+ resolve_partition_mapping,
+ stored_expression_error,
+ validate_partition_mapping,
+ validate_transform,
+)
+from superset.constants import TimeGrain
+from superset.db_engine_specs.base import BaseEngineSpec
+from superset.db_engine_specs.oracle import OracleEngineSpec
+from superset.db_engine_specs.postgres import PostgresEngineSpec
+from superset.models.core import Database
+from superset.sql.parse import SQLStatement
+from superset.utils.core import FilterOperator, GenericDataType, override_user
+
+
+@pytest.fixture(autouse=True)
+def real_probe_cache(app: Flask) -> Any:
+ """
+ The test app runs a null cache, which would make every cache assertion here
+ vacuously pass. Swap in a real in-memory one for the duration.
+ """
+ from flask_caching import Cache
+
+ from superset.extensions import cache_manager
+
+ cache = Cache(config={"CACHE_TYPE": "SimpleCache", "CACHE_DEFAULT_TIMEOUT": 300})
+ cache.init_app(app)
+ original = cache_manager._cache # noqa: SLF001
+ cache_manager._cache = cache # noqa: SLF001
+ yield
+ cache_manager._cache = original # noqa: SLF001
+
+
+@pytest.fixture(autouse=True)
+def enable_partition_filter_mapping(app: Flask) -> Any:
+ """The feature ships off; every test here exercises it on."""
+ original = app.config["DEFAULT_FEATURE_FLAGS"].get("PARTITION_FILTER_MAPPING")
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = True
+ yield
+ if original is None:
+ del app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"]
+ else:
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = original
+
+
+def _table(**kwargs: Any) -> SqlaTable:
+ database = Database(database_name="test_db", sqlalchemy_uri="sqlite://")
+ defaults: dict[str, Any] = {
+ "table_name": "web_events",
+ "database": database,
+ "main_dttm_col": "event_time",
+ "columns": [
+ TableColumn(column_name="event_time", is_dttm=True, type="TIMESTAMP"),
+ TableColumn(
+ column_name="dt_epoch",
+ type="BIGINT",
+ partition_value_transform=None,
+ ),
+ TableColumn(column_name="country", type="VARCHAR"),
+ TableColumn(column_name="region_key", type="VARCHAR"),
+ ],
+ }
+ defaults.update(kwargs)
+ return SqlaTable(**defaults)
+
+
+def _mapped_table(
+ *,
+ partition_column: str = "dt_epoch",
+ mapped_column: str = "event_time",
+ transform: str | None = "unix_timestamp(:value)",
+ monotonic: bool = True,
+ partition_mapped_column: str | None = None,
+ main_dttm_col: str | None = "event_time",
+) -> SqlaTable:
+ table = _table(main_dttm_col=main_dttm_col)
+ table.partition_column = partition_column
+ table.partition_mapped_column = partition_mapped_column
+ for column in table.columns:
+ if column.column_name == mapped_column:
+ column.partition_value_transform = transform
+ column.partition_transform_is_monotonic = monotonic
+ return table
+
+
+# ---------------------------------------------------------------------------
+# §2 — operator safety matrix
+# ---------------------------------------------------------------------------
+
+
+def test_equality_and_in_are_always_mirrorable() -> None:
+ """``=`` and ``IN`` are safe for any function ``T``."""
+ assert MIRRORABLE_ALWAYS == {FilterOperator.EQUALS, FilterOperator.IN}
+
+
+def test_range_operators_require_a_monotonic_transform() -> None:
+ assert MIRRORABLE_IF_MONOTONIC == {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+ }
+
+
+def test_mirrorable_operators_excludes_ranges_when_not_monotonic() -> None:
+ assert mirrorable_operators(is_monotonic=False) == MIRRORABLE_ALWAYS
+
+
+def test_mirrorable_operators_includes_ranges_when_monotonic() -> None:
+ assert mirrorable_operators(is_monotonic=True) == (
+ MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+ )
+
+
+@pytest.mark.parametrize(
+ "operator",
+ [
+ FilterOperator.NOT_EQUALS,
+ FilterOperator.NOT_IN,
+ FilterOperator.LIKE,
+ FilterOperator.ILIKE,
+ FilterOperator.NOT_LIKE,
+ FilterOperator.NOT_ILIKE,
+ FilterOperator.IS_NULL,
+ FilterOperator.IS_NOT_NULL,
+ FilterOperator.IS_TRUE,
+ FilterOperator.IS_FALSE,
+ ],
+)
+def test_negations_and_pattern_matches_are_never_mirrorable(
+ operator: FilterOperator,
+) -> None:
+ """
+ ``T`` is not injective, so ``col != v`` does **not** imply ``T(col) != T(v)``:
+ mirroring it would drop rows the original filter keeps.
+ """
+ assert operator not in mirrorable_operators(is_monotonic=True)
+
+
+def test_equality_is_dropped_when_the_engine_does_not_compare_byte_exactly() -> None:
+ """
+ "Safe for any function ``T``" reasons about value equality: ``T`` is a
+ function, so ``col = v`` gives ``T(col) = T(v)``. The engine reasons about
+ *SQL* equality, and the two part company under a case-insensitive
+ collation -- a stored ``'us'`` satisfies a filter for ``'US'`` while the
+ mirror ``hex('US')`` excludes the row, and the chart loses it silently.
+ """
+ assert mirrorable_operators(is_monotonic=False, equality_is_safe=False) == set()
+
+
+def test_ranges_survive_an_unsafe_equality() -> None:
+ """
+ Range mirroring already rests on the owner declaring ``T``
+ order-preserving with respect to the column's own order -- an assertion
+ about the very comparison semantics this gate checks for. Equality has no
+ such declaration behind it, which is why only equality is withdrawn.
+ """
+ assert (
+ mirrorable_operators(is_monotonic=True, equality_is_safe=False)
+ == MIRRORABLE_IF_MONOTONIC
+ )
+
+
+@pytest.mark.parametrize(
+ "operator,expected",
+ [
+ (FilterOperator.GREATER_THAN, FilterOperator.GREATER_THAN_OR_EQUALS),
+ (FilterOperator.LESS_THAN, FilterOperator.LESS_THAN_OR_EQUALS),
+ (
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ ),
+ (FilterOperator.LESS_THAN_OR_EQUALS, FilterOperator.LESS_THAN_OR_EQUALS),
+ (FilterOperator.EQUALS, FilterOperator.EQUALS),
+ (FilterOperator.IN, FilterOperator.IN),
+ ],
+)
+def test_a_strict_bound_mirrors_non_strictly(
+ operator: FilterOperator, expected: FilterOperator
+) -> None:
+ """
+ Order-preserving means non-decreasing, not injective, so ``col < v``
+ implies only ``T(col) <= T(v)``. A day-key transform maps a whole day onto
+ one value and a strict mirror drops the boundary bucket. The non-strict
+ cases are already safe and pass through, which is what makes applying this
+ twice harmless.
+ """
+ assert mirror_operator(operator) == expected
+
+
+def test_relaxing_a_bound_stays_inside_the_mirrorable_set() -> None:
+ """
+ The substitution is about strictness, not about which filters mirror. The
+ Explore indicator reads `mirrorable_operators`, so leaving that set alone is
+ what keeps the glyph from promising pruning the SQL does not do -- and it is
+ also what guarantees `handle_comparison_filter` is never handed an operator
+ it has no case for.
+ """
+ assert {
+ mirror_operator(operator) for operator in MIRRORABLE_IF_MONOTONIC
+ } <= MIRRORABLE_IF_MONOTONIC
+
+
+def _column(type_: str) -> TableColumn:
+ database = Database(database_name="t", sqlalchemy_uri="sqlite://")
+ table = SqlaTable(table_name="t", database=database)
+ return TableColumn(column_name="c", type=type_, table=table)
+
+
+@pytest.mark.parametrize(
+ "type_, binary, expected",
+ [
+ ("VARCHAR", True, True),
+ ("VARCHAR", False, False),
+ # Numeric and temporal comparison is exact everywhere.
+ ("BIGINT", False, True),
+ ("TIMESTAMP", False, True),
+ ("DOUBLE", False, True),
+ ],
+)
+def test_equality_mirrors_safely_only_guards_string_columns(
+ app: Flask, type_: str, binary: bool, expected: bool
+) -> None:
+ class _Spec(BaseEngineSpec):
+ binary_string_comparison = binary
+
+ with app.app_context():
+ assert equality_mirrors_safely(_column(type_), _Spec) is expected
+
+
+@pytest.mark.parametrize(
+ "type_, expected",
+ [
+ # The padded types: `'US'` and `'US '` are equal in the column, and
+ # `lower()` of the two is not.
+ ("CHAR(2)", False),
+ ("CHAR", False),
+ ("CHARACTER(2)", False),
+ ("NCHAR(2)", False),
+ # What PostgreSQL reflection reports for a `CHAR(n)` column.
+ ("BPCHAR", False),
+ ("bpchar(2)", False),
+ ("NATIONAL CHARACTER(2)", False),
+ # The variable-width types start with the same letters and must not be
+ # caught by it.
+ ("VARCHAR(2)", True),
+ ("NVARCHAR(2)", True),
+ ("CHARACTER VARYING(2)", True),
+ ("TEXT", True),
+ ],
+)
+def test_a_padded_character_column_declines_equality_on_a_byte_exact_engine(
+ app: Flask, type_: str, expected: bool
+) -> None:
+ """
+ `binary_string_comparison` speaks for the engine's default comparison,
+ which PostgreSQL declares -- and a `CHAR(2)` there still matches a filter
+ for `'US '` against a stored `'US'`, so the mirror `lower('US ')` excludes
+ the row. Padding is a property of the type, so it is asked per column.
+ """
+
+ class _Spec(BaseEngineSpec):
+ binary_string_comparison = True
+
+ with app.app_context():
+ assert equality_mirrors_safely(_column(type_), _Spec) is expected
+
+
+def test_redshift_does_not_opt_in_to_byte_exact_comparison() -> None:
+ """
+ Redshift ignores trailing blanks for `VARCHAR` as well as `CHAR`, so the
+ `True` it inherits from `PostgresBaseEngineSpec` would be wrong.
+ """
+ from superset.db_engine_specs.redshift import RedshiftEngineSpec
+
+ assert RedshiftEngineSpec.binary_string_comparison is False
+
+
+def test_equality_mirrors_safely_fails_closed_on_an_unresolvable_type(
+ app: Flask,
+) -> None:
+ """
+ The gate exists to stop a silent wrong answer, so a column whose type it
+ cannot read is treated as the risky case rather than waved through.
+ """
+ column = MagicMock()
+ type(column).type_generic = PropertyMock(side_effect=ValueError("no type"))
+
+ with app.app_context():
+ assert equality_mirrors_safely(column, BaseEngineSpec) is False
+
+
+def test_no_mapped_column_leaves_the_matrix_alone(app: Flask) -> None:
+ """Nothing to reason about, and the resolver bails out on it anyway."""
+ with app.app_context():
+ assert equality_mirrors_safely(None, BaseEngineSpec) is True
+
+
+@pytest.mark.parametrize(
+ "module, spec_name",
+ [
+ ("presto", "PrestoEngineSpec"),
+ ("hive", "HiveEngineSpec"),
+ ("trino", "TrinoEngineSpec"),
+ ("impala", "ImpalaEngineSpec"),
+ ("postgres", "PostgresEngineSpec"),
+ ("bigquery", "BigQueryEngineSpec"),
+ ("sqlite", "SqliteEngineSpec"),
+ ],
+)
+def test_the_byte_exact_engines_opt_in(module: str, spec_name: str) -> None:
+ """
+ The engines this feature targets compare text byte-exactly, so the gate
+ must not cost them the second canonical mapping (`lower(:value)` onto a
+ lowercased key).
+ """
+ spec = getattr(import_module(f"superset.db_engine_specs.{module}"), spec_name)
+ assert spec.binary_string_comparison is True
+
+
+@pytest.mark.parametrize("module, spec_name", [("mysql", "MySQLEngineSpec")])
+def test_a_case_insensitive_engine_does_not_opt_in(module: str, spec_name: str) -> None:
+ """
+ MySQL's default collation is `utf8mb4_0900_ai_ci`, which is exactly the
+ case the reviewer raised.
+ """
+ spec = getattr(import_module(f"superset.db_engine_specs.{module}"), spec_name)
+ assert spec.binary_string_comparison is False
+
+
+def test_the_base_spec_does_not_opt_in() -> None:
+ """A spec that has not said so does not mirror string equality."""
+ assert BaseEngineSpec.binary_string_comparison is False
+
+
+# ---------------------------------------------------------------------------
+# Time grain bucket widths
+# ---------------------------------------------------------------------------
+
+
+@pytest.mark.parametrize("grain", list(TimeGrain))
+def test_every_builtin_grain_has_a_known_bucket_width(
+ app: Flask, grain: TimeGrain
+) -> None:
+ """
+ The widening is only sound for a grain whose bucket width we know, so a
+ grain added upstream without a width here would silently stop mirroring.
+ This is the test that notices.
+ """
+ with app.app_context():
+ assert grain_bucket_width(grain.value, "sqlite") is not None
+
+
+def test_a_calendar_grain_widens_by_a_calendar_month(app: Flask) -> None:
+ """A month is not thirty days, and the month it lands in decides its width."""
+ with app.app_context():
+ width = grain_bucket_width(TimeGrain.MONTH.value, "sqlite")
+
+ assert width is not None
+ assert datetime(2026, 1, 31) + width == datetime(2026, 2, 28)
+ assert datetime(2026, 2, 1) + width == datetime(2026, 3, 1)
+
+
+def test_a_fractional_grain_has_a_width(app: Flask) -> None:
+ """
+ ``PT0.5H`` and ``P0.25Y`` are why the widths are written out rather than
+ parsed -- and the anchored week grains are intervals ``parse_duration``
+ rejects outright.
+ """
+ with app.app_context():
+ assert grain_bucket_width(TimeGrain.HALF_HOUR.value, "sqlite") == relativedelta(
+ minutes=30
+ )
+ assert grain_bucket_width(
+ TimeGrain.WEEK_ENDING_SATURDAY.value, "sqlite"
+ ) == relativedelta(days=7)
+
+
+def test_an_unknown_grain_has_no_known_width(app: Flask) -> None:
+ with app.app_context():
+ assert grain_bucket_width("P13X", "sqlite") is None
+ assert grain_bucket_width(None, "sqlite") is None
+
+
+def test_an_addon_grain_has_no_known_width(app: Flask) -> None:
+ """An operator-declared grain carries whatever duration string they typed."""
+ with app.app_context():
+ app.config["TIME_GRAIN_ADDONS"] = {"PT2S": "2 second"}
+ try:
+ assert grain_bucket_width("PT2S", "sqlite") is None
+ finally:
+ app.config["TIME_GRAIN_ADDONS"] = {}
+
+
+def test_a_builtin_grain_an_operator_redefined_has_no_known_width(
+ app: Flask,
+) -> None:
+ """
+ ``TIME_GRAIN_ADDON_EXPRESSIONS`` replaces a built-in grain's SQL for one
+ engine, so its duration no longer bounds the displacement *there* -- but it
+ still does on every other engine.
+ """
+ with app.app_context():
+ app.config["TIME_GRAIN_ADDON_EXPRESSIONS"] = {
+ "sqlite": {"P1D": "DATETIME({col}, 'start of year')"}
+ }
+ try:
+ assert grain_bucket_width(TimeGrain.DAY.value, "sqlite") is None
+ assert grain_bucket_width(TimeGrain.DAY.value, "hive") is not None
+ finally:
+ app.config["TIME_GRAIN_ADDON_EXPRESSIONS"] = {}
+
+
+def test_the_width_table_is_keyed_on_grain_durations(app: Flask) -> None:
+ """Keys are the ISO duration a filter carries, not the enum member name."""
+ assert GRAIN_BUCKET_WIDTHS[TimeGrain.DAY] == relativedelta(days=1)
+ assert set(GRAIN_BUCKET_WIDTHS) == {grain.value for grain in TimeGrain}
+
+
+# ---------------------------------------------------------------------------
+# §4.1 — resolving the effective mapping, and the defensive bail-outs
+# ---------------------------------------------------------------------------
+
+
+def test_resolve_returns_the_mapping_when_everything_lines_up(app: Flask) -> None:
+ with app.app_context():
+ mapping = resolve_partition_mapping(_mapped_table())
+
+ assert mapping is not None
+ assert mapping.partition_column == "dt_epoch"
+ assert mapping.mapped_column == "event_time"
+ assert mapping.value_transform == "unix_timestamp(:value)"
+ assert mapping.is_monotonic is True
+
+
+def test_effective_mapped_column_follows_main_dttm_col(app: Flask) -> None:
+ """No explicit override: the mapping follows the default datetime column."""
+ with app.app_context():
+ mapping = resolve_partition_mapping(_mapped_table())
+
+ assert mapping is not None
+ assert mapping.mapped_column == "event_time"
+
+
+def test_explicit_override_wins_over_main_dttm_col(app: Flask) -> None:
+ table = _mapped_table(
+ mapped_column="country",
+ transform="lower(:value)",
+ monotonic=False,
+ partition_mapped_column="country",
+ )
+ table.partition_column = "region_key"
+
+ with app.app_context():
+ mapping = resolve_partition_mapping(table)
+
+ assert mapping is not None
+ assert mapping.mapped_column == "country"
+ assert mapping.partition_column == "region_key"
+ assert mapping.is_monotonic is False
+
+
+def test_resolve_returns_none_when_the_feature_flag_is_off(app: Flask) -> None:
+ table = _mapped_table()
+ with app.app_context():
+ with patch(
+ "superset.connectors.sqla.partition_mapping.feature_flag_manager."
+ "is_feature_enabled",
+ return_value=False,
+ ):
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_without_a_partition_column(app: Flask) -> None:
+ table = _mapped_table()
+ table.partition_column = None
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_partition_column_no_longer_exists(
+ app: Flask,
+) -> None:
+ """A column sync can drop the physical partition column out from under us."""
+ table = _mapped_table()
+ table.partition_column = "dt_epoch_gone"
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_the_mapped_column_no_longer_exists(
+ app: Flask,
+) -> None:
+ table = _mapped_table(main_dttm_col="vanished")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_on_self_mapping(app: Flask) -> None:
+ """
+ ``partition_column == effective mapped column`` mirrors a column onto itself.
+ Save-time validation rejects it, but rows predating that validation exist.
+ """
+ table = _mapped_table(
+ partition_column="event_time",
+ mapped_column="event_time",
+ )
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+@pytest.mark.parametrize("transform", [None, "", " "])
+def test_resolve_returns_none_without_a_transform(
+ app: Flask, transform: str | None
+) -> None:
+ table = _mapped_table(transform=transform)
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_the_transform_lacks_the_placeholder(
+ app: Flask,
+) -> None:
+ table = _mapped_table(transform="unix_timestamp(event_time)")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_for_a_non_deterministic_transform(app: Flask) -> None:
+ """
+ The query-time gate is `is_transform_active`, the same one the Explore
+ indicator reads. Anything narrower would let a transform that reached
+ storage without passing `UpdateDatasetCommand` -- through import, or a
+ hand-written bundle -- mirror a filter with a value frozen at probe time,
+ while the editor reported the mapping as inactive and nothing on screen
+ said otherwise.
+ """
+ table = _mapped_table(transform="unix_timestamp(:value) + rand()")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_for_a_multi_expression_transform(app: Flask) -> None:
+ """A select list is not an expression; the probe cannot align its columns."""
+ table = _mapped_table(transform="lower(:value), 'x'")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_for_an_unparseable_transform(app: Flask) -> None:
+ table = _mapped_table(transform="unix_timestamp(:value")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_the_mapped_column_has_an_advanced_data_type(
+ app: Flask,
+) -> None:
+ """
+ ``translate_filter`` builds its own predicate shape from *translated* values,
+ so the ``(operator, value)`` pair the operator matrix reasons about does not
+ exist. Mirroring anyway would silently apply the wrong values (§4.1).
+ """
+ table = _mapped_table()
+ for column in table.columns:
+ if column.column_name == "event_time":
+ column.advanced_data_type = "port"
+
+ with app.app_context():
+ with patch.dict(app.config["ADVANCED_DATA_TYPES"], {"port": MagicMock()}):
+ with patch(
+ "superset.connectors.sqla.partition_mapping.feature_flag_manager."
+ "is_feature_enabled",
+ side_effect=lambda flag: (
+ flag in {"PARTITION_FILTER_MAPPING", "ENABLE_ADVANCED_DATA_TYPES"}
+ ),
+ ):
+ assert resolve_partition_mapping(table) is None
+
+
+def test_advanced_data_type_does_not_block_when_the_flag_is_off(app: Flask) -> None:
+ """An inert ``advanced_data_type`` is not a reason to skip mirroring."""
+ table = _mapped_table()
+ for column in table.columns:
+ if column.column_name == "event_time":
+ column.advanced_data_type = "port"
+
+ with app.app_context():
+ with patch(
+ "superset.connectors.sqla.partition_mapping.feature_flag_manager."
+ "is_feature_enabled",
+ side_effect=lambda flag: flag == "PARTITION_FILTER_MAPPING",
+ ):
+ assert resolve_partition_mapping(table) is not None
+
+
+# ---------------------------------------------------------------------------
+# §5 — transform inspection helpers
+# ---------------------------------------------------------------------------
+
+
+@pytest.mark.parametrize(
+ "transform,expected",
+ [
+ ("unix_timestamp(:value)", True),
+ ("lower(:value)", True),
+ ("CAST(:value AS BIGINT)", True),
+ ("unix_timestamp(event_time)", False),
+ (":values", False),
+ ("", False),
+ (None, False),
+ ],
+)
+def test_contains_value_placeholder(transform: str | None, expected: bool) -> None:
+ assert contains_value_placeholder(transform) is expected
+
+
+@pytest.mark.parametrize(
+ "transform,expected",
+ [
+ ("unix_timestamp(:value)", False),
+ ("{{ current_username() }}", True),
+ ("lower({% if x %}:value{% endif %})", True),
+ ("lower(:value) -- {# comment #}", True),
+ ],
+)
+def test_contains_jinja(transform: str, expected: bool) -> None:
+ assert contains_jinja(transform) is expected
+
+
+@pytest.mark.parametrize(
+ ("transform", "expected"),
+ [
+ ("lower(:value)", False),
+ ("lower(:value) /* an ordinary comment */", False),
+ ("lower(:value) -- a line comment", False),
+ (":value /*!50000 + 1 */", True),
+ (":value /*M!50000 + 1 */", True),
+ (":value /*! + 1 */", True),
+ ("", False),
+ (None, False),
+ ],
+)
+def test_contains_executable_comment(transform: str | None, expected: bool) -> None:
+ assert contains_executable_comment(transform) is expected
+
+
+@pytest.mark.parametrize(
+ "transform",
+ [
+ "unix_timestamp(:value)",
+ "lower(:value)",
+ "CAST(:value AS BIGINT)",
+ "date_format(:value, 'yyyyMMdd')",
+ ],
+)
+def test_pure_transforms_report_no_non_deterministic_functions(
+ transform: str,
+) -> None:
+ assert find_non_deterministic_functions(transform, "hive") == set()
+
+
+@pytest.mark.parametrize(
+ "transform,expected_name",
+ [
+ ("date_diff(:value, now())", "NOW"),
+ ("CAST(:value AS BIGINT) + rand()", "RAND"),
+ ("CAST(:value AS DATE) - current_date", "CURRENT_DATE"),
+ ],
+)
+def test_non_deterministic_functions_are_reported(
+ transform: str, expected_name: str
+) -> None:
+ """
+ The probe runs at a different moment and in a different session from the
+ chart query, and its result is cached, so anything time- or
+ randomness-dependent freezes a snapshot of probe time into the predicate.
+ """
+ assert expected_name in find_non_deterministic_functions(transform, "hive")
+
+
+def test_niladic_unix_timestamp_is_rejected_but_the_unary_form_is_not() -> None:
+ """
+ On Hive/Impala ``unix_timestamp()`` means "now" while ``unix_timestamp(x)``
+ -- the canonical temporal transform -- is pure. The distinction is the whole
+ reason this check inspects arity rather than just the name.
+ """
+ assert find_non_deterministic_functions("unix_timestamp(:value)", "hive") == set()
+ assert find_non_deterministic_functions(
+ "unix_timestamp(:value) - unix_timestamp()", "hive"
+ )
+
+
+# ---------------------------------------------------------------------------
+# §4.2 — probe evaluation
+# ---------------------------------------------------------------------------
+
+
+def _user(username: str) -> Any:
+ """A stand-in for `override_user`, which only needs `.username` here."""
+ user = MagicMock()
+ user.username = username
+ user.is_anonymous = False
+ return user
+
+
+def _database_returning(values: list[Any]) -> Database:
+ """A real ``Database`` (so the dialect is real) with only ``get_df`` stubbed."""
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ return_value=pd.DataFrame(
+ [values], columns=[f"v{i}" for i in range(len(values))]
+ )
+ )
+ return database
+
+
+def _database_returning_frame(frame: pd.DataFrame) -> Database:
+ """
+ ``_database_returning`` for a probe result whose column dtypes matter.
+
+ The flat-list sibling builds its frame from one Python list, so pandas
+ infers a single dtype and the row-versus-cell distinction cannot be seen.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ return_value=frame
+ )
+ return database
+
+
+def _probe(database: Database) -> MagicMock:
+ """
+ The stubbed ``get_df``, typed for call assertions.
+
+ ``Database.get_df`` is a real method, so mypy reads its declared signature
+ rather than the mock that replaced it and rejects ``.call_args`` and
+ friends.
+ """
+ return cast(MagicMock, database.get_df)
+
+
+def test_evaluate_transform_returns_one_value_per_input(app: Flask) -> None:
+ database = _database_returning([1767225600, 1769904000])
+
+ with app.app_context():
+ result = evaluate_transform(
+ database,
+ None,
+ "default",
+ "unix_timestamp(:value)",
+ ["2026-01-01 00:00:00", "2026-02-01 00:00:00"],
+ )
+
+ assert result == [1767225600, 1769904000]
+ _probe(database).assert_called_once()
+
+
+def test_evaluate_transform_binds_values_rather_than_interpolating(
+ app: Flask,
+) -> None:
+ """
+ Filter values are attacker-controlled (a Gamma user picks them), so they must
+ be bound and escaped, never pasted into the probe SQL.
+ """
+ database = _database_returning(["o''brien"])
+
+ with app.app_context():
+ evaluate_transform(database, None, None, "lower(:value)", ["O'Brien"])
+
+ sql = _probe(database).call_args.kwargs["sql"]
+ assert "O'Brien" not in sql
+ assert "O''Brien" in sql
+
+
+@pytest.mark.parametrize(
+ ("transform", "expected"),
+ [
+ ("lower(:value)", True),
+ ("CAST(:value AS BIGINT)", True),
+ ("date_format(:value, '%Y%m%d')", True),
+ # The cast shorthand: a trailing colon stops SQLAlchemy's bind scan.
+ (":value::bigint", False),
+ ("(:value::date)::text", False),
+ ],
+)
+def test_a_postgres_cast_shorthand_is_not_bindable(
+ transform: str, expected: bool
+) -> None:
+ """
+ `VALUE_PLACEHOLDER_RE` is `:value\b`, which matches inside `:value::bigint`.
+ SQLAlchemy's own scan ends with `(?![:\\w$])`, so the following colon stops
+ it: `text(":value::bigint")` reports a parameter named `valu`, and asking it
+ to bind `value` raises.
+
+ Pinned because the two regexes disagreeing is the whole bug: every
+ write-side gate accepted the transform and the probe then died on an
+ `ArgumentError` that `_probe` swallows.
+ """
+ assert _placeholder_is_bindable(transform) is expected
+
+
+def test_a_cast_shorthand_transform_still_probes(app: Flask) -> None:
+ """
+ The transform is valid SQL, passes every gate, and used to prune nothing:
+ `build_probe_sql` raised, `_probe` swallowed it, and the only symptom was a
+ mapping that silently never mirrored -- with the preview reporting an engine
+ failure for SQL that was never sent.
+ """
+ database = _database_returning([20260115])
+
+ with app.app_context():
+ result = evaluate_transform(
+ database, None, None, ":value::bigint", ["20260115"]
+ )
+
+ assert result == [20260115]
+ assert _probe(database).call_count == 1
+ assert "::bigint" in _probe(database).call_args.kwargs["sql"]
+
+
+def test_a_cast_shorthand_value_is_still_escaped_by_the_dialect(
+ app: Flask,
+) -> None:
+ """
+ The fallback substitutes where the bind path binds, so it has to earn the
+ same guarantee its sibling above pins: the value is rendered by the
+ dialect's literal processor, not pasted in.
+
+ Binding was only ever the vehicle for reaching that processor --
+ `_compile_literal` inlines the result either way -- so this renders first
+ and substitutes second. Same string, different order.
+ """
+ database = _database_returning(["x"])
+
+ with app.app_context():
+ evaluate_transform(database, None, None, ":value::text", ["O'Brien"])
+
+ sql = _probe(database).call_args.kwargs["sql"]
+ assert "O'Brien" not in sql
+ assert "O''Brien" in sql
+
+
+def test_evaluate_transform_dedupes_repeated_values(app: Flask) -> None:
+ """Three inputs, two distinct: the probe evaluates the transform twice."""
+ database = _database_returning(["us", "us"])
+
+ with app.app_context():
+ result = evaluate_transform(
+ database, None, None, "lower(:value)", ["US", "US", "us"]
+ )
+
+ assert result == ["us", "us", "us"]
+ sql = _probe(database).call_args.kwargs["sql"]
+ assert sql.count("lower") == 2
+
+
+def test_evaluate_transform_fails_open_on_a_short_result_row(app: Flask) -> None:
+ """A row narrower than the probe asked for means the results cannot be
+ aligned back to their inputs; pruning is skipped rather than guessed at."""
+ database = _database_returning(["us"])
+
+ with app.app_context():
+ assert (
+ evaluate_transform(database, None, None, "lower(:value)", ["US", "CA"])
+ is None
+ )
+
+
+def test_evaluate_transform_fails_open_on_a_wide_result_row(app: Flask) -> None:
+ """
+ Too many columns is the dangerous direction. A transform whose select list
+ holds two expressions returns 2N columns for N inputs, and reading the first
+ N interleaves the expressions instead of taking one per value -- a predicate
+ built from the wrong values rather than one that is merely short. A frame of
+ `('us', 'x', 'ca', 'x')` read as the first two columns would have yielded
+ `('us', 'x')` and dropped every CA row.
+
+ The transform is a perfectly ordinary `lower(:value)` and the width comes
+ from the stubbed frame, which is the only way to reach the guard: a
+ transform that really does carry two expressions -- `lower(:value), 'x'` --
+ is refused by `stored_expression_error` for not being a single expression,
+ so `get_df` is never called and `None` comes back for an unrelated reason.
+ Asserting the probe *ran* is what separates the two, and it is what makes
+ relaxing the guard from `!=` to `<` fail here rather than pass: four columns
+ for two inputs is not fewer than two.
+ """
+ database = _database_returning(["us", "x", "ca", "x"])
+
+ with app.app_context():
+ assert (
+ evaluate_transform(database, None, None, "lower(:value)", ["US", "CA"])
+ is None
+ )
+
+ assert _probe(database).call_count == 1
+
+
+def test_the_probe_select_carries_the_engine_s_from_clause(app: Flask) -> None:
+ """
+ A `SELECT` with no `FROM` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from. Without this every probe on those engines
+ raises, which `evaluate_transform` swallows -- so the only symptom is a
+ correctly configured mapping that silently never prunes.
+ """
+ assert build_probe_sql("lower(:value)", ["US"]) == "SELECT lower('US') AS v0"
+ assert build_probe_sql("lower(:value)", ["US"], None, " FROM DUAL").endswith(
Review Comment:
This hands `" FROM DUAL"` to `build_probe_sql` directly, so it never exercises the step that reads `select_without_from_suffix` off the engine spec and passes it through `_probe`/`probe_sql_is_evaluable`. If that forwarding were dropped, this test would still pass while Oracle and Db2 stopped pruning (the bare `SELECT ...` fails there and the mapping silently declines). Could a case run `evaluate_transform` with `OracleEngineSpec` and the Db2 spec against a mocked `get_df` and assert the SQL it receives ends in the required one-row table and the result is accepted?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2929 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+class Unmirrorable:
+ """
+ A filter no mirror can stand in for, and why.
+
+ Returned by `ExploreMixin.mirror_probe_request` for a value the engine
+ compares more coarsely than the filter carries, one it cannot render as a
+ literal, one in a time frame the transform would discard, or an ``IN`` list
+ with a member of any of those kinds. An object rather than `None`, because
+ `None` is a filter value in its own right.
+
+ The reason rides along because the preview has to explain the decline to
+ the owner, and the two declines want different advice: "the engine compares
+ less of this value than you typed, so map a column it compares in full" is
+ sound guidance for a `DATE` column and actively misleading for an
+ offset-bearing bound on a `TIMESTAMP` one, which already is such a column.
+ Carried rather than re-derived so the preview's explanation cannot come
+ apart from the chart path's decision.
+
+ Lives here rather than beside that method so the preview can read it too:
+ `superset.models.helpers` imports this module, so these can only cross the
+ boundary in this direction. Both callers recognise the same instances -- a
+ preview that answered "valid" for a request the chart path declines is the
+ drift this is here to prevent.
+ """
+
+ __slots__ = ("reason",)
+
+ def __init__(self, reason: str) -> None:
+ self.reason = reason
+
+ def __repr__(self) -> str:
+ return f"<Unmirrorable {self.reason}>"
+
+
+#: The ordinary decline: whatever the mirror cannot be built from, with the
+#: engine's own comparison resolution as the reason an owner can act on.
+UNMIRRORABLE = Unmirrorable("resolution")
+
+#: A value carrying a UTC offset, declined whatever the column's resolution.
+#: A transform such as ``CAST(:value AS TIMESTAMP)`` drops the offset, so even
+#: an engine that compares the whole instant would be probed in the wrong
+#: frame -- which is not something mapping a different column fixes.
+UNMIRRORABLE_OFFSET = Unmirrorable("offset")
+
+
+def is_unmirrorable(value: Any) -> bool:
+ """Whether `mirror_probe_request` declined this request."""
+ return isinstance(value, Unmirrorable)
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+#: Declared types whose comparison ignores trailing blanks.
+#:
+#: The fixed-width character types, which the SQL standard has compare as
+#: though both sides were padded to the same length -- so ``'US'`` and
+#: ``'US '`` are equal in a ``CHARACTER(3)``, while ``lower()`` of the two is
+#: not. Spelled out rather than matched by prefix because the variable-width
+#: names start with the same letters: ``VARCHAR`` and ``CHARACTER VARYING``
+#: compare the blanks and must not land here.
+PADDED_CHARACTER_TYPES = frozenset(
+ {
+ "CHAR",
+ "NCHAR",
+ # PostgreSQL's own name for ``CHARACTER``, which is what reflection
+ # reports for a ``CHAR(n)`` column there.
+ "BPCHAR",
+ "CHARACTER",
+ "NATIONAL CHAR",
+ "NATIONAL CHARACTER",
+ }
+)
+
+
+def _is_padded_character_type(column: TableColumn) -> bool:
+ """
+ Whether ``column``'s declared type compares without its trailing blanks.
+
+ Read off the declared type rather than the engine spec's resolved one: the
+ specs map ``CHAR`` and ``VARCHAR`` onto the same `sqlalchemy.String`, so
+ the distinction this needs is gone by then. The length suffix is dropped
+ and the name matched against `PADDED_CHARACTER_TYPES`, so an unfamiliar
+ spelling answers ``False`` and the engine-level flag decides as before --
+ this gate adds a decline rather than lifting one. A column with no
+ declared type has nothing to read, and answers the same way.
+ """
+ if not isinstance(column.type, str):
+ return False
+ native = re.sub(r"\s+", " ", column.type.strip().upper())
+ return native.split("(")[0].strip() in PADDED_CHARACTER_TYPES
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ Padding is asked about per column, because it is a property of the *type*
+ rather than of the engine. ``binary_string_comparison`` speaks for an
+ engine's default text comparison, and on PostgreSQL -- which declares it
+ -- a ``CHAR(2)`` still matches a filter for ``'US '`` against a stored
+ ``'US'``, because the standard says a padded character type compares
+ without its trailing blanks. The mirror ``region_key = lower('US ')`` then
+ excludes the row. So a fixed-width character type declines whatever the
+ engine says, and an engine that ignores trailing blanks on its *variable*
+ types says so by not declaring the flag at all (see `RedshiftEngineSpec`).
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ # Ahead of the generic-type question, which a padded type can lose: the
+ # specs map ``CHARACTER`` onto no generic type at all on some engines, and
+ # a fixed-width character type is a string whether or not Superset can say
+ # so from the name.
+ if _is_padded_character_type(column):
+ return False
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error( # noqa: C901
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ And it must be a *read*. Shape is a separate question from effect: a bare
+ scalar expression can still write, so `SQLStatement.is_mutating` is asked
+ too -- the same question SQL Lab and the chart executor ask before letting
+ SQL run. See the gate itself for what that reaches and what it does not.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ # Also ahead of the parse, and for a stronger reason than cost: every gate
+ # below reasons about the parse tree, and this is the one construct that
+ # makes the parse tree describe a different statement from the one the
+ # engine runs. Checked here as well as in `validate_transform` because this
+ # is the door a row written by an earlier release still comes through.
+ if contains_executable_comment(transform):
+ return str(
+ _(
+ "A partition value transform cannot contain a MySQL "
+ "executable comment, which the database executes and every "
+ "validator reads as a comment."
+ )
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The read-only gate, which nothing above implies. The shape gates ask what
+ # the transform *selects*; this asks what evaluating it *does*, and a bare
+ # scalar expression can still write. `nextval(:value)` on PostgreSQL
+ # advances a sequence: one function call, no clause, no sub-query, and not
+ # in the default `DISALLOWED_SQL_FUNCTIONS` either -- so every gate above
+ # passes it and the probe then runs it. `setval` is the same shape, and
+ # `exp.Execute` and the opaque-`exp.Command` forms arrive the same way.
+ #
+ # The large-object writers (`lo_export`, `lowrite`, `lo_from_bytea`, ...)
+ # are caught here too, and the shipped denylist happens to name them as
+ # well -- but that is config an operator can replace, while this is not.
+ #
+ # `is_mutating` is the same question SQL Lab, `get_virtual_table_metadata`
+ # and the chart executor ask before letting SQL run, so a transform is held
+ # to the bar the rest of Superset already sets rather than to one invented
+ # here. Unconditional rather than gated on `Database.allow_dml`: a transform
+ # is a scalar function of `:value` by definition, so there is no legitimate
+ # mutating one, and the probe runs on a cache schedule nobody chose -- a
+ # write would repeat every time the entry expired.
+ #
+ # It bears saying what this does not reach. A user-defined function whose
+ # body writes is a plain call no parser can tell from `lower(:value)`, and
+ # `is_mutating`'s function-name walk is PostgreSQL-only by design, since the
+ # same names are read-only elsewhere. Neither residual is specific to this
+ # feature -- a dataset editor can already have the engine evaluate an
+ # arbitrary expression through a calculated column or a virtual dataset's
+ # SQL -- and closing them means authorizing the preview against the
+ # database, not parsing harder.
+ if statement.is_mutating():
+ return str(
+ _(
+ "A partition value transform cannot change data. It is "
+ "evaluated against the database to check that it mirrors, so "
+ "it has to be a read."
+ )
+ )
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the probe
+ uninspected -- string elements are escaped by the dialect's own literal
+ processor. `probe_sql_is_evaluable` then re-reads the finished query, which
+ is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def _placeholder_is_bindable(transform: str) -> bool:
+ """
+ Whether SQLAlchemy's ``text()`` can see ``:value`` as a bound parameter.
+
+ `VALUE_PLACEHOLDER_RE` is ``:value\b``, which matches the placeholder in a
+ Postgres cast such as ``:value::bigint``. SQLAlchemy's own bind scan is
+ ``(?<![:\\w$]):([\\w$]+)(?![:\\w$])`` -- note the trailing exclusion -- so a
+ following colon stops it: ``text(":value::bigint")`` reports a parameter
+ named ``valu``, and ``.bindparams(bindparam("value"))`` then raises
+ ``ArgumentError``.
+
+ `_probe` swallows that, so the only symptom was a perfectly valid transform
+ whose mapping silently never pruned, and a preview reporting an engine
+ failure for SQL that was never sent. Every write-side gate passes the
+ transform: it parses, it is a bare expression, and the placeholder *is* in
+ an executable position.
+
+ Answered by attempting the bind itself rather than by pattern-matching
+ ``::`` or reading ``text()``'s private parameter map, so this cannot
+ disagree with what `build_probe_sql` is about to do -- on any dialect, or on
+ a SQLAlchemy whose scan changes.
+ """
+ try:
+ sa.text(transform).bindparams(sa.bindparam("value", value=None))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return False
+ return True
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ bindable = _placeholder_is_bindable(transform)
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ elif bindable:
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ rendered = _compile_literal(clause, dialect)
+ else:
+ # `text()` cannot see the placeholder (see
+ # `_placeholder_is_bindable`), so the value is rendered by the
+ # dialect's own literal processor first and substituted as SQL
+ # text. The same two steps in the other order: binding exists to
+ # get the value through that processor, and `_compile_literal`
+ # inlines the result either way, so this is the same string by a
+ # different route -- not a loosening of the "never interpolate a
+ # raw value" rule. `parse_skeleton` substitutes literally, so a
+ # rendered literal containing a backslash is safe here.
+ rendered = parse_skeleton(
+ transform, _compile_literal(sa.literal(value), dialect)
+ )
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Four things have to hold, and all four are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ # Before the parse, because this gate's whole contract is that what the
+ # parse describes is what the engine will run, and an executable comment is
+ # precisely the text where that stops being true. The transform is already
+ # refused for carrying one; this covers the compiled statement, so no later
+ # change to how values are rendered can reintroduce it behind the gates
+ # below.
+ if contains_executable_comment(sql):
+ return False
+
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if not isinstance(statement, SQLStatement):
+ # A dialect whose statements this gate cannot take apart -- KQL -- gets
+ # no probe rather than an unchecked one. It never had one: the clause
+ # inspection below is implemented for SQL statements only, and the
+ # alternative to declining here is an `AttributeError` that `_probe`
+ # swallows into the same outcome, less legibly.
+ return False
+ if statement.has_subquery():
+ return False
+ if statement.get_clause_names() - {"from"}:
+ return False
+ if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+ """
+ The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+ Parsed rather than string-compared so that the comparison in
+ `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+ not parse answers ``None``, which no statement carrying a FROM can match --
+ the probe then declines, which is the right way for an unreadable engine
+ constant to fail.
+ """
+ if not from_suffix.strip():
+ return None
+ try:
+ return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+ except SupersetParseError:
+ return None
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=values is not None and not any(value is None for value in values),
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ from_suffix = database.db_engine_spec.select_without_from_suffix
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ from_suffix,
+ )
+ if not probe_sql_is_evaluable(
+ sql, database.backend, len(distinct), from_suffix
+ ):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _execution_identity(database: Database) -> str | None:
+ """
+ Who the warehouse will run the probe as, when that can vary by caller.
+
+ `_probe_cache_key` keys on the `Database` record, which is the *connection*
+ -- not the identity it is opened under. Two hooks make that identity a
+ function of the Superset user instead:
+
+ * ``impersonate_user`` on the database, which hands the effective username
+ to `db_engine_spec.impersonate_user`;
+ * ``DB_CONNECTION_MUTATOR``, which receives the effective username and may
+ return an entirely different account's URL.
+
+ Under either one, a cached probe result computed under user A's grants was
+ served to user B, and the preview echoed it back in ``emitted_predicate``.
+ A transform wrapping a read-capable function the denylist does not name --
+ Oracle's ``DBMS_XMLGEN.GETXML`` is the worked example -- then leaks across
+ users who were never allowed the same rows.
+
+ Returns ``None`` when neither hook is configured, which is the common case
+ and deliberately leaves the key as it was: the cache exists to keep a
+ synchronous warehouse round trip off the chart-query path, and keying every
+ deployment on the username would cost every deployment the hit rate to fix
+ the two that need it.
+
+ The *Superset* username rather than the resolved warehouse account, because
+ it is the input both hooks branch on, and reading it needs no URL parse and
+ puts no credential in the key.
+ """
+ if not (database.impersonate_user or app.config["DB_CONNECTION_MUTATOR"]):
+ return None
+ return get_username()
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _mirror_verdict_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str:
+ """
+ `_probe_cache_key` without the values.
+
+ Whether a transform can be evaluated at all is a property of the transform
+ and the connection, not of the filter that happened to be probing it, so
+ one chart's answer settles the question for the next one.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ # Whether a transform *can* be evaluated is a property of the
+ # transform and the connection -- but under impersonation the
+ # connection is per-user, and a function one account may call can
+ # be refused to another. See `_execution_identity`.
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_verdict:{digest}"
+
+
+def record_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ *,
+ mirrors: bool,
+) -> None:
+ """
+ Remember whether this transform produced a mirror, for the UI to read.
+
+ Advisory only. Nothing in the query path consults it: a probe that failed
+ once is retried on the next chart exactly as it is today, because declining
+ to prune for a whole cache timeout over one transient engine blip is the
+ trade `evaluate_transform` deliberately refuses -- see the comment where it
+ declines to cache a failure.
+
+ What this is for is the *claim*. `is_transform_active` parses the transform
+ and no more, so a transform the database rejects -- a misspelled function
+ is the common case -- is "active", and the editor's banner and Explore's
+ pruning glyph promise a speed-up that never happens. A promise is exactly
+ the thing that may be withheld on one bad answer and restored on a good
+ one, which is why this is a separate entry from the probe's own results
+ rather than a relaxation of that rule.
+
+ Written by `_run_probe`, so the preview endpoint -- which shares the
+ evaluator -- settles the question before the owner has even saved.
+ """
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(
+ _mirror_verdict_cache_key(database, catalog, schema, transform),
+ mirrors,
+ timeout=timeout,
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform verdict", exc_info=True)
+
+
+def known_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> bool | None:
+ """
+ The last verdict `record_mirror_verdict` stored, or `None` if there is none.
+
+ `None` is the honest answer on a cold cache and is deliberately not `False`:
+ reporting a working mapping as broken until something probes it would
+ trade one wrong claim for another. The alternative -- probing from the
+ read side -- would put a warehouse round trip on every Explore and
+ dashboard load, and a failing transform is not cached at all, so it would
+ be a round trip every single time.
+ """
+ try:
+ verdict = cache_manager.cache.get(
+ _mirror_verdict_cache_key(database, catalog, schema, transform)
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return verdict if isinstance(verdict, bool) else None
+
+
+def _compile_literal(element: Any, dialect: Dialect | None) -> str:
+ """
+ Compile with inline literals, undoing the paramstyle's percent doubling.
+
+ Both ``TextClause`` and literal compilation run the dialect's
+ ``post_process_text``, which doubles every ``%`` whenever the identifier
+ preparer asks it to -- true for MySQL and Postgres and for every spec
+ inheriting their paramstyle. That doubling exists so a later DBAPI
+ parameter-interpolation pass can undo it, and the probe has no such pass:
+ it executes with no bound parameters at all. So a transform of
+ ``date_format(:value, '%Y%m%d')`` reaches the warehouse asking for the
+ literal string ``%%Y%%m%%d``, the probe returns that instead of a date, and
+ the mirrored predicate drops every row the filter keeps.
+
+ The same normalization ``Database.compile_sqla_query`` applies for the same
+ reason. ``_double_percents`` is private and not guaranteed on a third-party
+ dialect, hence the ``getattr`` default.
+ """
+ compiled = str(
+ element.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
+ )
+ if dialect is not None and getattr(
+ dialect.identifier_preparer, "_double_percents", False
+ ):
+ compiled = compiled.replace("%%", "%")
+ return compiled
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be *asked* to stand in for itself, and the transform
+ cannot carry Jinja or call a non-deterministic function. Tier 2
+ (``blocking=False``) is everything that merely leaves the mapping inactive
+ -- including a self-mapping nobody asked for, where the partition column
+ merely happens to be the default datetime column.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column == partition_column:
+ # Asked for explicitly, so report it as the mistake it is.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+ elif not partition_mapped_column and main_dttm_col == partition_column:
+ # Resolved onto itself only because the default datetime column happens
+ # to be the partition column -- a state metadata sync could produce
+ # without anyone asking for it. The mapping is inert either way, since
+ # `resolve_partition_mapping` bails out on it, so this reports and lets
+ # the write through: blocking here means a dataset already in the state
+ # can never be saved again, not even to change its description, and
+ # there is no field whose edit would clear the error first.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "%(name)s is both the partition column and the default "
+ "datetime column, so the mapping points at itself and "
+ "stays inactive. Set a mapped column override, or change "
+ "the default datetime column.",
+ name=partition_column,
+ ),
+ blocking=False,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def drop_unmapped_value_transforms(
+ columns: list[dict[str, Any]] | None,
+ *,
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ names_by_id: dict[int, str] | None = None,
+) -> list[str]:
+ """
+ Null the value transform on every *incoming* column the mapping cannot mirror.
+
+ The write-side twin of `DatasetDAO.clear_unmapped_partition_transforms`,
+ which answers for the model. A mapping has exactly one mirrored column, so
+ at most one column may carry a transform. One parked on any other column is
+ invisible -- no row but the mapped one renders a transform -- and yet it is
+ stored, and it goes live the moment the mapped column resolves back to it.
+ Clearing an override is enough to do that: a null
+ ``partition_mapped_column`` means "follow ``main_dttm_col``".
+
+ Ungated on the feature flag, unlike its model-level twin, and the difference
+ is what each one discards. That one drops stored configuration, so with the
+ flag off it would be pure loss. This one drops only a value the request in
+ hand is asking to write where the invariant says none may live -- and the
+ flag-off window is precisely when such a value gets parked for later, since
+ the editor hides these fields and the model-level pass declines to run.
+
+ Three writers reach the columns with no effective model-level pass between
+ them, which is why this exists at all: the deprecated
+ ``POST /datasource/save/``, which writes straight through
+ `update_from_object` and so never had one; and a
+ ``PUT /api/v1/dataset/<pk>`` or a dataset import made while the flag is
+ off, where the pass runs on both sides of the write and declines on both.
+
+ Mutates the payload in place, because every caller hands its own request
+ dict straight on to the code that writes it. Returns the names it cleared,
+ so the caller can say so in a log: this is a silent correction to a payload
+ whose author may have meant it.
+
+ A column whose payload mentions neither field is left alone. "Incoming" is
+ the whole scope -- a transform already in storage on a column this request
+ says nothing about is the model-level pass's business, under its own flag.
+
+ The mapped column resolves the way every other reader resolves it,
+ ``partition_mapped_column or main_dttm_col``, and resolves to nothing
+ without a partition column -- in which case no column may hold a transform
+ either.
+
+ :param names_by_id: how to read the name off a payload entry that gives
+ only an ``id``. `DatasetDAO._upsert_columns` identifies an existing
+ column by its primary key and lets ``column_name`` be omitted -- the
+ column keeps the name it has -- so without this an ordinary PUT looked
+ like a payload of nameless columns, none of which matched the mapped
+ one, and every transform in it was dropped. Callers whose writer keys
+ on the name instead (`update_from_object`, the importer) pass nothing.
+ An entry this cannot name is left alone rather than guessed at.
+ """
+ mapped_column = (
+ (partition_mapped_column or main_dttm_col) if partition_column else None
+ )
+ cleared: list[str] = []
+ for column in columns or []:
+ name = column.get("column_name")
+ if name is None and names_by_id is not None:
+ column_id = column.get("id")
+ if column_id is not None:
+ name = names_by_id.get(column_id)
+ if name is None or name == mapped_column:
+ continue
+ if column.get("partition_value_transform") or column.get(
+ "partition_transform_is_monotonic"
+ ):
+ column["partition_value_transform"] = None
+ column["partition_transform_is_monotonic"] = False
+ cleared.append(name)
+ return cleared
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if contains_executable_comment(transform):
+ # Blocking, and checked on raw text next to the Jinja gate because no
+ # parse reports it: sqlglot reads `/*!50000 ... */` as comment data
+ # while MySQL and MariaDB execute it, so every shape gate downstream
+ # inspects a statement the engine will not run. See
+ # `EXECUTABLE_COMMENT_RE`.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform cannot contain a MySQL executable "
+ "comment (/*! ... */ or /*M! ... */). Those are comments "
+ "to every validator and statement text to the database, "
+ "so what would run is not what was checked."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_bare_expression(transform, engine):
+ # Blocking, and deliberately placed in `validate_transform` rather than
+ # only at the probe: one issue here closes the PUT, the importer, the
+ # query-time gate through `is_transform_active`, the Explore indicator's
+ # active verdict and the preview endpoint, all of which already consult
+ # this function.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform must be a single SQL expression. It "
+ "cannot carry a FROM, WHERE, GROUP BY or any other clause, "
+ "and it cannot contain a sub-query."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not contains_value_placeholder(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform must contain the :value placeholder, "
+ "which stands for the filter value being mirrored."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not placeholder_is_executable(transform, engine):
+ # Blocking, and for the same reason the shape gate above is: this is
+ # the function the PUT, the importer, `is_transform_active`, the
+ # Explore indicator and the preview all consult, so one issue here
+ # closes every door at once. A placeholder inside a string literal is
+ # a sub-query the engine will run once a filter value closes the quote;
+ # one inside a comment silently eats the probe's own alias.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The :value placeholder must appear where the engine will "
+ "evaluate it. It cannot sit inside a string literal or a "
+ "comment."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if functions := find_non_deterministic_functions(transform, engine):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform calls %(functions)s, whose result "
+ "depends on when and where it runs. The transform is "
+ "evaluated in a separate session and the result is cached, "
+ "so the emitted predicate would freeze a snapshot of that "
+ "moment.",
+ functions=", ".join(sorted(functions)),
+ ),
+ blocking=True,
+ )
+ ]
+
+ return []
+
+
+@lru_cache(maxsize=LRU_CACHE_MAX_SIZE)
+def is_transform_active(transform: str | None, engine: str) -> bool:
+ """
+ Whether Superset will mirror filters through this transform.
+
+ `validate_transform` with the messages discarded, so the Explore indicator
+ cannot advertise a mapping the save path recorded as inactive. Anything
+ cheaper here would be a second, weaker statement of the same rule, free to
+ drift from the one the save path applies.
+
+ Blocking issues count too. Jinja and non-deterministic transforms are
+ rejected on PUT, but `CreateDatasetCommand` and import do not validate the
+ mapping, so one can still reach the database -- and it would never mirror a
+ filter either.
+
+ Memoized because `partition_filter_mapping_summary` is serialized on every
+ Explore and dashboard load and this parses the transform. The key is
+ everything the answer depends on: `validate_transform` reads no session, no
+ locale and no config beyond `SQL_MAX_PARSE_LENGTH`, which bounds the parser
+ rather than changing a verdict within that bound.
+ """
+ return not validate_transform(transform, engine)
+
+
+def preview_partition_mapping( # pylint: disable=too-many-return-statements
+ datasource: SqlaTable,
+ *,
+ mapped_column: str,
+ value_transform: str | None,
+ sample_values: list[str],
+ operator: FilterOperator = FilterOperator.EQUALS,
+ is_monotonic: bool = False,
+ partition_column: str | None = None,
+) -> dict[str, Any]:
+ """
+ Evaluate a candidate mapping and describe the predicate it would emit.
+
+ Shares the evaluator -- and therefore the probe cache -- with the query
+ path, so preview and runtime cannot drift and a previewed transform warms
+ the chart path for free. The predicate itself comes from
+ `build_mirrored_predicates`, the same builder the query path uses, so
+ operator shapes cannot drift either: what the panel shows is what a chart
+ would emit.
+
+ Validation runs first and the engine second: a half-typed transform is by
+ definition unparseable, so most of what a text input produces costs zero
+ queries.
+
+ Every part of the mapping is taken from the request rather than the stored
+ dataset. The editor previews while the owner is still editing -- a mapping
+ that has to be saved before it can be checked is not a preview.
+ """
+ partition_column = partition_column or datasource.partition_column
+ if not partition_column:
+ return {
+ "valid": False,
+ "reason": "unconfigured",
+ "error": _("No partition column is set."),
+ }
+
+ columns_by_name = {str(column.column_name): column for column in datasource.columns}
+ if mapped_column not in columns_by_name:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _("%(name)s is not a column on this dataset.", name=mapped_column),
+ }
+
+ # The bail-out `resolve_partition_mapping` makes at query time, and that
+ # `partition_filter_mapping_summary` repeats for the Explore indicator.
+ # Without it here, preview reports a valid emitted predicate for a mapping
+ # no chart will ever mirror -- the one answer a preview panel must not give.
+ if has_active_advanced_data_type(columns_by_name[mapped_column]):
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _(
+ "%(name)s has an advanced data type, so its filters are "
+ "translated into their own predicate shape and cannot be "
+ "mirrored onto the partition column.",
+ name=mapped_column,
+ ),
+ }
+
+ engine = datasource.database.backend
+ for issue in validate_partition_mapping(
+ column_names=set(columns_by_name),
+ partition_column=str(partition_column),
+ partition_mapped_column=mapped_column,
+ main_dttm_col=datasource.main_dttm_col,
+ transform=value_transform,
+ engine=engine,
+ ):
+ return {
+ "valid": False,
+ # The parse failure is the one an owner sees constantly, and it is
+ # the only one the mockup gives its own headline to.
+ "reason": (
+ "parse"
+ if issue.field == "partition_value_transform"
+ and not is_parseable(value_transform, engine)
+ else "validation"
+ ),
+ "error": str(issue.message),
+ }
+
+ # The policy every other stored expression goes through. The save path
+ # applies it in `UpdateDatasetCommand._validate_partition_mapping`, but
+ # preview evaluates a candidate transform that has not been saved, so
+ # without this the gate had a door around it. See
+ # `stored_expression_error` for what is being kept out and why.
+ if reason := stored_expression_error(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ cast(str, value_transform),
+ ):
+ return {"valid": False, "reason": "validation", "error": reason}
+
+ mapping = PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=mapped_column,
+ value_transform=cast(str, value_transform),
+ is_monotonic=is_monotonic,
+ equality_is_safe=equality_mirrors_safely(
+ columns_by_name[mapped_column], datasource.database.db_engine_spec
+ ),
+ )
+ sample_input = _render_sample_input(
+ datasource, mapped_column, operator, sample_values
+ )
+
+ if operator not in PREVIEWABLE_OPERATORS:
+ # Checked before `mirrors`, which lets `TEMPORAL_RANGE` through when the
+ # transform is declared monotonic -- and the single sample value would
+ # then reach `handle_comparison_filter`, which has no case for a range
+ # and raises. The request schema rejects it too; this keeps the function
+ # honest for any other caller.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is mirrored as a pair of bounds, which "
+ "a preview of a single value cannot describe.",
+ operator=operator.value,
+ ),
+ }
+
+ if operator in MIRRORABLE_ALWAYS and not mapping.equality_is_safe:
+ # Withdrawn by `equality_mirrors_safely`, which no declaration about
+ # ordering can change -- so naming monotonicity here would send the
+ # owner to a checkbox that leaves the answer as it is.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter on this text column is not mirrored: "
+ "the database may treat strings that differ in case or "
+ "trailing spaces as equal, and the mirrored predicate could "
+ "then drop rows the filter keeps.",
+ operator=operator.value,
+ ),
+ }
+
+ if not mapping.mirrors(operator):
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is only mirrored when the transform "
+ "preserves ordering, which this one is not declared to do.",
+ operator=operator.value,
+ ),
+ }
+
+ return _preview_probe(
+ datasource,
+ mapping,
+ columns_by_name[mapped_column],
+ operator,
+ sample_values,
+ sample_input,
+ )
+
+
+def _preview_probe(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ mapped_col: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+ sample_input: str,
+) -> dict[str, Any]:
+ """
+ The half of a preview that needs the warehouse.
+
+ Split out from `preview_partition_mapping` so that the gates which answer
+ from the stored mapping alone stay readable as the single run of guard
+ clauses they are. Everything here has either run a query or decided not to.
+ """
+ value = datasource.mirror_probe_request(
+ operator,
+ _probe_input(datasource, mapped_col, operator, sample_values),
+ mapped_col,
+ )
+ if is_unmirrorable(value):
+ # The same step the chart path applies, so the preview cannot promise a
+ # mirror the query declines -- and it reports the reason that step
+ # recorded rather than deriving one of its own, which is what let the
+ # offset case be explained as a precision loss it is not.
+ if value.reason == "offset":
+ # The transform is fine and the column may well compare the whole
+ # instant; what cannot be mirrored is the frame. Advising a
+ # different column here would send the owner after a column they
+ # already have.
+ return {
+ "valid": False,
+ "reason": "offset",
+ "sample_input": sample_input,
+ "error": _(
+ "A filter value carrying a UTC offset is not mirrored: a "
+ "transform is evaluated in the database's own time frame, "
+ "so the mirrored predicate could ask for a partition the "
+ "matching rows are not in. Write the bound without an "
+ "offset to mirror this filter.",
+ ),
+ }
+ # The transform is fine and the engine evaluates it, the filter just
+ # carries more of the value than the engine compares on this column --
+ # which is the column's type talking, not a broken expression.
+ return {
+ "valid": False,
+ "reason": "resolution",
+ "sample_input": sample_input,
+ "error": _(
+ "This engine compares less of a %(operator)s value on "
+ "%(column)s than the filter carries, so there is no mirror a "
+ "predicate on the partition column could stand in for. Map a "
+ "column the engine compares in full to mirror this operator.",
+ operator=operator.value,
+ column=mapped_col.column_name,
+ ),
+ }
+ errors: list[str] = []
+ type_errors: list[str] = []
+ predicates = build_mirrored_predicates(
+ datasource,
+ mapping,
+ [(operator, value)],
+ errors=errors,
+ type_errors=type_errors,
+ )
+ if type_errors:
+ # Its own reason, because "the database would not evaluate this" and
+ # "it evaluated and answered with the wrong kind of thing" are
+ # different problems with different fixes, and the owner is the only
+ # one who can tell which transform they meant to write.
+ return {
+ "valid": False,
+ "reason": "type",
+ "sample_input": sample_input,
+ "error": type_errors[0],
+ }
+ if not predicates:
+ return {
+ "valid": False,
+ "reason": "engine",
+ "sample_input": sample_input,
+ "error": (
+ _(
+ "The transform could not be evaluated against the "
+ "database: %(reason)s",
+ reason=errors[0],
+ )
+ if errors
+ else _("The transform could not be evaluated against the database.")
+ ),
+ }
+
+ return {
+ "valid": True,
+ "sample_input": sample_input,
+ "emitted_predicate": _render_predicate(datasource, predicates[0]),
+ }
+
+
+def _probe_input(
+ datasource: SqlaTable,
+ column: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+) -> Any:
+ """
+ The sample values as the query path would bind them.
+
+ The request carries samples as strings, and the probe is keyed on exactly
+ what it is handed, so passing them through raw asks the engine a different
+ question from the one a chart asks. A sample of ``2025`` on a numeric
+ column has to arrive as the integer the chart compares: under a transform
+ of ``typeof(:value)`` the raw string previewed ``'text'`` where the chart
+ emitted ``'integer'``. And because `_probe_cache_key` keys on each value's
+ ``repr``, the two also missed each other's cache entirely -- so the "a
+ previewed transform warms the chart path for free" claim in
+ `preview_partition_mapping`'s docstring did not actually hold.
+
+ Coerced by `filter_values_handler`, the same function the query path uses,
+ rather than by a second implementation of the same rules. Everything the
+ query path then does to the coerced value -- rendering an expression as a
+ literal, widening a bound, declining a comparison the engine resolves too
+ coarsely -- is `ExploreMixin.mirror_probe_request`'s, and the caller hands
+ this result straight to it.
+
+ Ranges are not previewable (see `PREVIEWABLE_OPERATORS`), so the bound
+ conversion `_collect_partition_mirror_range` applies -- a ``datetime`` into
+ the column's stored representation -- has no counterpart here.
+
+ An array column is the exception to `filter_values_handler`: its predicate
+ is built from the raw value, parsed into elements and rendered as the
+ engine's own array literal, so the chart path probes that literal
+ (`ExploreMixin._array_mirror_probe_value`) and this does too. Passing the
+ handled text instead previewed ``length('[1, 2]')`` for a filter whose
+ query probes ``length(array(1, 2))``.
+
+ Answers with a value, or `None` where an engine spec claims array columns
+ without an array literal -- which `mirror_probe_request` then declines, as
+ the chart path declines it. Otherwise `UNMIRRORABLE` is
+ `mirror_probe_request`'s to return, and the caller hands this straight to it.
+ """
+ is_list = operator == FilterOperator.IN
+ column_spec = datasource.db_engine_spec.get_column_spec(native_type=column.type)
+ if (
+ column_spec
+ and column_spec.generic_type == utils.GenericDataType.MULTI_VALUE
+ and operator in MIRRORABLE_ALWAYS
+ ):
+ # `=` and `IN` are the previewable operators the array branch builds a
+ # literal for; a bound on an array column binds the handled value on
+ # the chart path too, so it falls through to the same here.
+ return datasource._array_mirror_probe_value( # noqa: SLF001
+ sample_values if is_list else sample_values[0],
+ operator,
+ datasource.db_engine_spec.get_array_element_type(column.type),
+ datasource.db_engine_spec,
+ )
+ handled = datasource.filter_values_handler(
+ # `list[str]` is not a `list[FilterValue]` to mypy, invariantly, even
+ # though every `str` is a `FilterValue`.
+ values=cast(FilterValues, sample_values if is_list else sample_values[0]),
+ operator=operator,
+ target_generic_type=(
+ column_spec.generic_type if column_spec else utils.GenericDataType.STRING
+ ),
+ target_native_type=column.type,
+ is_list_target=is_list,
+ db_engine_spec=datasource.db_engine_spec,
+ db_extra=datasource.db_extra,
+ )
+ # No `ColumnElement` conversion here: an epoch-milliseconds sample comes back
+ # as engine SQL rather than a value, and `mirror_probe_request` renders it --
+ # the same step, on the same values, as for a chart filter.
+ return handled
+
+
+def _render_sample_input(
+ datasource: SqlaTable,
+ mapped_column: str,
+ operator: FilterOperator,
+ values: list[str],
+) -> str:
+ """
+ The filter being previewed, written the way an owner would read it.
+
+ Display-only -- it is never executed -- but it is still read as SQL, so the
+ column is quoted and the values are rendered by the dialect rather than
+ concatenated raw. A column named ``order date`` would otherwise come out as
+ two bare words.
+ """
+ quoted = datasource.quote_identifier(mapped_column)
+ if operator == FilterOperator.IN:
+ rendered = ", ".join(
+ _render_literal(datasource.database, value) for value in values
+ )
+ return f"{quoted} IN ({rendered})"
+ return (
+ f"{quoted} {operator.value} {_render_literal(datasource.database, values[0])}"
+ )
+
+
+def _render_predicate(datasource: SqlaTable, predicate: ColumnElement[Any]) -> str:
+ """
+ Compile a mirrored predicate to the text a reader would see in View query.
+
+ Every value in it is a probed constant by this point, so ``literal_binds``
+ renders the same literals the chart query carries.
+ """
+ return _compile_literal(predicate, _dialect_for(datasource.database)).replace(
+ "\n", " "
+ )
+
+
+def _render_literal(database: Database, value: Any) -> str:
+ """
+ Render a value the way it appears in the generated SQL.
+
+ Compiled by the dialect rather than formatted by hand. `str()` would render
+ a NULL as the Python repr `None` and leave a date unquoted, neither of which
+ is SQL, and hand-rolled quote-doubling would only ever have been right for
+ strings.
+ """
+ return _compile_literal(sa.literal(value), _dialect_for(database))
+
+
+def build_mirrored_predicates(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ requests: list[tuple[FilterOperator, Any]],
+ *,
+ errors: list[str] | None = None,
+ type_errors: list[str] | None = None,
+) -> list[ColumnElement[Any]]:
+ """
+ Turn collected ``(operator, value)`` mirror requests into predicates.
+
+ ``requests`` is expected to be deduplicated by the caller. Every value is
+ resolved in a single probe round trip -- one per chart query at most -- then
+ emitted as a literal constant, so "View query" shows the reader an ordinary
+ ``WHERE`` clause rather than an inline expression.
+
+ A strict bound is emitted non-strictly; see `mirror_operator`. That happens
+ here, at the one point where a ``FilterOperator`` becomes SQL, rather than
+ at the collection sites in `ExploreMixin`: the preview endpoint calls this
+ directly, so this is what keeps the predicate the editor shows an owner and
+ the predicate the chart carries from disagreeing.
+
+ :param errors: optional sink; see `evaluate_transform`.
+ :param type_errors: optional sink for a probe result the partition column
+ cannot hold -- see `probed_value_type_error`. Separate from ``errors``
+ because the two say different things to an owner: that one is "the
+ database would not evaluate this", and this one is "it evaluated, and
+ answered with the wrong kind of thing".
+ """
+ if not requests:
+ return []
+
+ partition_column = next(
+ (
+ column
+ for column in datasource.columns
+ if column.column_name == mapping.partition_column
+ ),
+ None,
+ )
+ if partition_column is None:
+ return []
+
+ # Flatten every value that needs probing into one list, remembering how many
+ # each request consumed so the results can be handed back out.
+ flat: list[Any] = []
+ spans: list[tuple[FilterOperator, int, int]] = []
+ for operator, value in requests:
+ values = list(value) if operator == FilterOperator.IN else [value]
+ spans.append((operator, len(flat), len(values)))
+ flat.extend(values)
+
+ evaluated = evaluate_transform(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ mapping.value_transform,
+ flat,
+ errors=errors,
+ )
+ if evaluated is None:
+ return []
+
+ if not _bounds_are_ordered(evaluated, spans):
+ return []
+
+ # Declining here is the last chance to decline at all: once these
+ # predicates are in the statement, a value the partition column cannot
+ # hold fails the whole chart rather than its pruning.
+ if reason := probed_value_type_error(partition_column, evaluated):
+ logger.warning(
+ "Partition transform returned a value the partition column cannot "
+ "hold; queries will not prune: %s",
+ reason,
+ )
+ if type_errors is not None:
+ type_errors.append(reason)
+ # Deliberately *not* recorded as a mirror verdict. The transform
+ # evaluated perfectly; what failed is the comparison against this
+ # dataset's partition column -- and `_mirror_verdict_cache_key` is
+ # keyed on database, catalog, schema and transform, with no partition
+ # column in it. Recorded, this dataset-specific outcome answered for
+ # every other dataset sharing the transform: `CAST(:value AS text)`
+ # mirroring happily onto a text key in dataset A was reported
+ # `evaluable: false` -- and its pruning indicator hidden -- because
+ # someone previewed the same transform against a numeric key in
+ # dataset B. A probe cache hit on A never rewrites the verdict, so it
+ # stayed wrong until the entry expired.
+ return []
+
+ sqla_col = datasource.convert_tbl_column_to_sqla_col(partition_column)
+ predicates = _predicates_from_probe(
+ sqla_col, datasource.db_engine_spec, evaluated, spans
+ )
+ if not predicates:
+ return []
+
+ # A comparison against a NULL partition value is NULL, so a row parked in a
+ # NULL partition is dropped by the mirror even when the real filter matches
+ # it -- Hive and Impala's default partition, or a transform that returns
+ # NULL for an input it cannot convert. The mirror only has to be no
+ # narrower than the filter it stands in for, so admitting NULL partitions
+ # keeps those rows. Engines still prune; they read one extra partition.
+ return [sa.or_(sa.and_(*predicates), sqla_col.is_(None))]
+
+
+def _predicates_from_probe(
+ sqla_col: ColumnElement[Any],
+ db_engine_spec: type[BaseEngineSpec],
+ evaluated: list[Any],
+ spans: list[tuple[FilterOperator, int, int]],
+) -> list[ColumnElement[Any]]:
+ """
+ One predicate on the partition column per surviving mirror request.
+
+ A request whose probe answered `None` for any of its values is skipped
+ rather than emitted: `col = NULL` is `NULL`, so it would drop every row the
+ filter keeps. A strict bound is emitted non-strictly; see `mirror_operator`.
+ """
+ predicates: list[ColumnElement[Any]] = []
+ for operator, start, length in spans:
+ chunk = evaluated[start : start + length]
+ if any(value is None for value in chunk):
+ continue
+ if operator == FilterOperator.IN:
+ # The probe answers per value, so a transform over a mixed-number
+ # filter can answer with a mixed-number partition key -- and
+ # `in_` infers the bind type from the first element it is handed.
+ # Without this, probe results of `[33, 29.02]` emit
+ # `IN (33, 29)` and prune away the partition holding `29.02`.
+ predicates.append(sqla_col.in_(normalize_mixed_numbers(chunk)))
+ else:
+ predicates.append(
+ db_engine_spec.handle_comparison_filter(
+ sqla_col, mirror_operator(operator), chunk[0]
+ )
+ )
+ return predicates
+
+
+#: Operators whose value is the lower end of a range, and whose upper-end twins.
+#:
+#: Shared with `ExploreMixin._mirror_probe_input`, which rounds a bound *outward*
+#: where the engine resolves it more coarsely than the filter carries -- backward
+#: for a lower bound, forward for an upper one. Which end an operator names is
+#: the only thing separating the two directions in either caller, so the two have
+#: to agree on it rather than each classify for itself.
+LOWER_BOUND_OPERATORS = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+}
+UPPER_BOUND_OPERATORS = {
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+#: What Python type a probe result may have, per generic type of the partition
+#: column it is about to be compared against.
+#:
+#: Only the types a mismatch can actually break a query with are listed. An
+#: unresolvable column type is absent because there is nothing to check
+#: against, and ``MULTI_VALUE`` because this module does not mirror onto an
+#: array partition key at all.
+#: ``numbers.Number`` rather than ``(int, float)``: Postgres answers
+#: ``extract(epoch from ...)`` with a `Decimal`, which is the single commonest
+#: transform this feature has, and an engine is free to answer with any number
+#: type its driver prefers. What the check is for is a *string* where a number
+#: belongs, and every numeric type is equally not that.
+_PROBE_RESULT_TYPES: dict[utils.GenericDataType, tuple[type, ...]] = {
+ utils.GenericDataType.NUMERIC: (numbers.Number,),
+ utils.GenericDataType.BOOLEAN: (bool,),
+ # A day key such as ``to_char(:value, 'YYYYMMDD')`` is legitimately text,
+ # so ``str`` is admitted -- but only for text *this* engine reads as an
+ # instant. `_reads_as_temporal` is the second half of this entry.
+ utils.GenericDataType.TEMPORAL: (datetime, date, str),
+ # Text, and not a number rendered as one. Not every engine accepts a number
+ # in a text comparison: Postgres refuses ``character varying = integer``,
+ # Trino ``varchar = bigint`` and BigQuery ``STRING = INT64``, all of which
+ # fail the whole chart once the predicate is in the statement. SQLite is
+ # worse -- it raises nothing and compares across storage classes as never
+ # equal, so the mirror drops every row rather than losing pruning, which is
+ # the one outcome this feature may not have. An owner whose partition key
+ # really is text writes the cast into the transform.
+ utils.GenericDataType.STRING: (str,),
+}
+
+
+#: The extended ISO 8601 date, which every engine reads as a date.
+#:
+#: Used to tell an ISO value apart from a merely ISO-*parseable* one:
+#: `datetime.fromisoformat` also accepts the basic forms -- ``20260115``,
+#: ``20260706100811`` -- and those are exactly what an engine may not read.
+#: BigQuery coerces a STRING literal to ``DATE`` only in the canonical
+#: ``YYYY-MM-DD`` form, so admitting the basic forms everywhere emitted
+#: ``part_date = '20260115'`` there and failed the chart.
+_ISO_DATE_PREFIX_RE = re.compile(r"^\d{4}-\d{2}-\d{2}")
+
+
+def _reads_as_temporal(value: str, db_engine_spec: type[BaseEngineSpec]) -> bool:
+ """
+ Whether this engine would read this text as a date or timestamp.
+
+ `_PROBE_RESULT_TYPES` admits ``str`` for a temporal partition column
+ because a day key such as ``to_char(:value, 'YYYYMMDD')`` is legitimately
+ text -- but it admitted *every* string, so a transform that answers with
+ ordinary text passed the gate and failed the chart instead. On PostgreSQL a
+ ``VARCHAR`` mapped column under ``lower(:value)`` probes ``'US'`` to
+ ``'us'`` and emits ``p = 'us'`` against a ``DATE`` key, which the engine
+ refuses once the predicate is already in the statement -- so a chart that
+ worked before the mapping returns an error rather than losing its pruning.
+
+ Which text counts is per engine beyond the extended ISO forms, because the
+ day key this feature exists for is not universal: PostgreSQL reads
+ ``'20260115'`` as a date, BigQuery coerces a STRING literal to ``DATE``
+ only in the canonical ``YYYY-MM-DD`` form, and Trino wants an explicit
+ cast. So an engine names what it reads in
+ `BaseEngineSpec.temporal_literal_formats` and says nothing by default,
+ which declines and costs only the pruning.
+
+ Answered by parsing, not by asking the engine: the check runs on the
+ chart-query path, where a second round trip is the cost this module spends
+ its effort avoiding. Parsing is also the conservative direction -- anything
+ unrecognised declines.
+ """
+ if _ISO_DATE_PREFIX_RE.match(value):
Review Comment:
Any text that starts with an ISO date is accepted as a temporal value here, for every engine, while `temporal_literal_formats` is only consulted for the non-ISO forms. On Trino, a TIMESTAMP partition key with a monotonic `date_format(CAST(:value AS TIMESTAMP), '%Y-%m-%d %H:%i:%s')` probes to `'2026-01-01 00:00:00'`, passes this gate, and the query then carries `p >= '2026-01-01 00:00:00'`; Trino does not coerce a varchar literal to a timestamp or date, so the chart errors instead of just skipping the mirror. The docstring above already says Trino wants an explicit cast. Should the ISO acceptance also be gated on something the engine spec declares, so an engine that doesn't read bare ISO text declines?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4236241864
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/DatasourceEditor.tsx:
##########
@@ -1359,15 +1673,63 @@ function DatasourceEditor({
const newCols = await fetchSyncedColumns(datasource, signal);
const columnChanges = updateColumns(
- datasource.columns,
+ currentColumns,
Review Comment:
`currentColumns` is captured before `await fetchSyncedColumns(...)`, and the result then replaces `databaseColumns` wholesale. If the owner starts "Sync columns from source" with an active implicit mapping and clicks "Remove mapping" while the request is pending, the unchanged-column response merges against the stale snapshot, restores the transform and monotonicity flag, and silently re-activates the mapping that was removed; saving persists it. Adding `currentColumns` to the dependency list does not help an invocation already in flight. Could the merge read the latest column state when the response arrives (e.g. via a ref or functional state update)?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2770 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+#: Returned by `ExploreMixin.mirror_probe_request` for a filter no mirror can
+#: stand in for: one the engine compares more coarsely than the value carries, a
+#: value it cannot render as a literal, or an ``IN`` list with a member of
+#: either kind. A sentinel rather than `None`, because `None` is a filter value
+#: in its own right.
+#:
+#: Lives here rather than beside that method so the preview can read it too:
+#: `superset.models.helpers` imports this module, so the sentinel can only cross
+#: the boundary in this direction. Both callers have to recognise the same
+#: object -- a preview that answered "valid" for a request the chart path
+#: declines is the drift this is here to prevent.
+UNMIRRORABLE = object()
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
Review Comment:
The docstring says trailing-space-insensitive `CHAR` comparison is covered, but this returns the engine-wide flag for every string column, and `PostgresBaseEngineSpec` sets it to `True` (so `RedshiftEngineSpec` inherits it too). With PostgreSQL `country CHAR(2)`, a text partition key and transform `lower(:value)`, the filter `country = 'US '` still matches the row, but the probe yields `'us '` and the added `region_key = 'us '` predicate drops it. Redshift VARCHAR ignores trailing spaces the same way, so a length-based transform hits it too. Should padded character types (and Redshift) decline equality here instead of relying on the engine-level flag?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4261226914
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/usePartitionMappingPreview.ts:
##########
@@ -0,0 +1,170 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { SupersetClient, getClientErrorObject } from '@superset-ui/core';
+import { t } from '@apache-superset/core/translation';
+import { useDebounceValue } from 'src/hooks/useDebounceValue';
+import type { PartitionMappingPreview } from './types';
+import { transformCanPreview } from './utils';
+
+interface PreviewRequest {
+ datasetId?: number;
+ mappedColumn: string;
+ partitionColumn: string;
+ valueTransform: string;
+ sampleValues: string[];
+ operator: string;
+ isMonotonic: boolean;
+ /** Skip entirely when the section isn't showing a mapping. */
+ enabled: boolean;
+}
+
+/**
+ * Preview the predicate a transform would emit, debounced.
+ *
+ * The endpoint fires a real warehouse query, so the transform is debounced
+ * before it leaves the browser, and a transform that cannot work is not sent at
+ * all. Neither is a guard -- the server keeps a per-user, per-dataset budget of
+ * its own, and remains the authority on whether a transform is usable. The
+ * point is that a half-written transform should not spend that budget and leave
+ * none for the finished one.
+ */
+export function usePartitionMappingPreview({
+ datasetId,
+ mappedColumn,
+ partitionColumn,
+ valueTransform,
+ sampleValues,
+ operator,
+ isMonotonic,
+ enabled,
+}: PreviewRequest) {
+ const [preview, setPreview] = useState<PartitionMappingPreview | null>(null);
+ const [loading, setLoading] = useState(false);
+ // Which request the displayed state belongs to. `AbortController` alone is
+ // not enough: aborting settles nothing, so a handler still runs and has to
+ // ask whether it is still the current one. See the effect below.
+ const latestRequest = useRef(0);
+
+ const debouncedTransform = useDebounceValue(valueTransform, 500);
+ // `sampleValues` is a fresh array on every render, so depending on it
+ // directly would refire the effect -- and spend the preview budget -- on
+ // every keystroke elsewhere in the row. Depend on its serialized form and
+ // hand the effect a value whose identity tracks that same key.
+ const sampleKey = JSON.stringify(sampleValues);
+ const samples = useMemo<string[]>(() => JSON.parse(sampleKey), [sampleKey]);
+
+ useEffect(() => {
+ const transform = debouncedTransform?.trim();
+ // Claimed before the early return as well, so a request already in flight
+ // cannot come back and overwrite what this run decided.
+ latestRequest.current += 1;
+ const requestId = latestRequest.current;
+
+ if (
+ !enabled ||
+ !datasetId ||
+ !mappedColumn ||
+ !transformCanPreview(transform, mappedColumn, partitionColumn)
+ ) {
+ setPreview(null);
+ // The spinner belongs to a request this run has just superseded. Its own
+ // handlers see the abort and stop short of clearing it, so clearing it
+ // here is the only thing that does -- otherwise clearing the transform
+ // mid-flight left the panel spinning for good.
+ setLoading(false);
+ return undefined;
+ }
+
+ const controller = new AbortController();
+ setLoading(true);
+
+ SupersetClient.post({
+ endpoint: `/api/v1/dataset/${datasetId}/partition_mapping/preview/`,
Review Comment:
This posts to the saved dataset's preview endpoint, which resolves the mapped/partition column against the persisted columns, while the editor validates against its unsaved state. Add a column at the source, hit "Sync columns from source", and map onto the new column before saving: the editor accepts it, but the preview reports that the column doesn't exist, so a valid candidate is shown as broken (and after changing the database/schema it can show "Valid" against the old source). Should the preview either send the candidate columns/source or say that it needs the changes saved first?
##########
UPDATING.md:
##########
@@ -150,6 +150,54 @@ reattached to a reachable container by layout repair.
instead; the response sets `managed_externally: true`. Read-only tools and
certification inspection are unaffected.
+- Refreshing a dataset's columns from its source -- the "Sync columns from
+ source" button, and a `PUT /api/v1/dataset/<id>?override_columns=true` --
+ no longer resets **Is dimension** and **Is filterable** on columns that
+ already exist. Those two flags were set unconditionally on every column the
+ source reported, so a save that synced columns reverted whatever the dataset
+ owner had chosen for them. A newly discovered column still arrives with both
+ enabled. A deployment that relied on a resync to restore those defaults has
+ to set them explicitly.
+
+- `DISALLOWED_SQL_FUNCTIONS` now names the whole PostgreSQL XML family, plus the
+ two full-text search functions that share its blind spot. Seven shapes were
+ missing -- `schema_to_xml`, `schema_to_xmlschema`,
+ `schema_to_xml_and_xmlschema`, `database_to_xml_and_xmlschema`,
+ `table_to_xmlschema`, `ts_rewrite` and `ts_stat` -- which, being scalar calls
+ with no FROM clause and no sub-query, cleared every gate that reasons about
+ table references. `ts_rewrite` and `ts_stat` run their text argument as a
+ query, so the statement they execute is a string with no clause of its own for
+ such a gate to see. The same reasoning adds a new `oracle` entry naming
+ `getxml`, `getxmltype`, `newcontext` and `newcontextfromhierarchy`, the
+ `DBMS_XMLGEN` / `DBMS_XMLQUERY` calls that run a query handed to them as
+ text, and `dburitype`, which reads a table by path string; they are listed by
Review Comment:
The Oracle note lists `getxml`, `getxmltype`, `newcontext`, `newcontextfromhierarchy` and `dburitype`, but `config.py` also denylists `geturi`, `xdburitype` and `httpuritype`. An operator who uses `URIFACTORY.GETURI(...)` in SQL Lab or a chart will read this note, see nothing about that function, and find it refused after upgrading — even with `PARTITION_FILTER_MAPPING` off. Should those three names be added to the list here?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,3041 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: The opening and closing delimiters of each kind of Jinja block. The probe
+#: would render these in a different context at a different time from the chart
+#: query, so a transform holding one is rejected at save time.
+JINJA_BLOCK_DELIMITERS = (("{{", "}}"), ("{%", "%}"), ("{#", "#}"))
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: A PostgreSQL Unicode-escaped identifier, ``U&"..."``.
+#:
+#: The second construct that breaks the premise above, and in the same way:
+#: ``U&"\\0071uery_to_xml"(...)`` parses as an anonymous function whose name is
+#: the *literal* ``\\0071uery_to_xml``, so the function denylist is matching a
+#: name the engine never sees -- PostgreSQL decodes the escape and runs
+#: ``query_to_xml``, handing a dataset owner rows from outside their RLS scope
+#: through the preview's ``emitted_predicate``.
+#:
+#: Normalizing the escapes and re-checking would be the other repair, and is
+#: worse: it means reimplementing one engine's identifier decoding well enough
+#: to be a security boundary. Refusing the construct is exact, and costs
+#: nothing real -- a transform is a scalar function of ``:value``, and there is
+#: no reason to name a function or column through an escape sequence.
+#:
+#: Refused on every engine, like the executable comment, so a transform stored
+#: on SQLite cannot detonate when the dataset is re-pointed at PostgreSQL. The
+#: ``&`` may be separated from the ``U`` by nothing at all, but whitespace or a
+#: comment between the prefix and the string is not accepted by PostgreSQL
+#: either, so the strict form is the whole surface.
+#:
+#: Matched in raw text, so the prefix is refused inside a string literal too.
+#: That is the same trade the executable comment makes and has the same
+#: justification: a gate whose contract is to fire *before* the parse cannot
+#: ask the parse whether the text was quoted. ``concat(:value, 'u&"x"')`` is
+#: refused, which costs an owner nothing anyone writes.
+UNICODE_ESCAPED_IDENTIFIER_RE = re.compile(r'\bU&"', re.IGNORECASE)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+class Unmirrorable:
+ """
+ A filter no mirror can stand in for, and why.
+
+ Returned by `ExploreMixin.mirror_probe_request` for a value the engine
+ compares more coarsely than the filter carries, one it cannot render as a
+ literal, one in a time frame the transform would discard, or an ``IN`` list
+ with a member of any of those kinds. An object rather than `None`, because
+ `None` is a filter value in its own right.
+
+ The reason rides along because the preview has to explain the decline to
+ the owner, and the two declines want different advice: "the engine compares
+ less of this value than you typed, so map a column it compares in full" is
+ sound guidance for a `DATE` column and actively misleading for an
+ offset-bearing bound on a `TIMESTAMP` one, which already is such a column.
+ Carried rather than re-derived so the preview's explanation cannot come
+ apart from the chart path's decision.
+
+ Lives here rather than beside that method so the preview can read it too:
+ `superset.models.helpers` imports this module, so these can only cross the
+ boundary in this direction. Both callers recognise the same instances -- a
+ preview that answered "valid" for a request the chart path declines is the
+ drift this is here to prevent.
+ """
+
+ __slots__ = ("reason",)
+
+ def __init__(self, reason: str) -> None:
+ self.reason = reason
+
+ def __repr__(self) -> str:
+ return f"<Unmirrorable {self.reason}>"
+
+
+#: The ordinary decline: whatever the mirror cannot be built from, with the
+#: engine's own comparison resolution as the reason an owner can act on.
+UNMIRRORABLE = Unmirrorable("resolution")
+
+#: A value carrying a UTC offset, declined whatever the column's resolution.
+#: A transform such as ``CAST(:value AS TIMESTAMP)`` drops the offset, so even
+#: an engine that compares the whole instant would be probed in the wrong
+#: frame -- which is not something mapping a different column fixes.
+UNMIRRORABLE_OFFSET = Unmirrorable("offset")
+
+
+def is_unmirrorable(value: Any) -> bool:
+ """Whether `mirror_probe_request` declined this request."""
+ return isinstance(value, Unmirrorable)
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+#: Declared types whose comparison ignores trailing blanks.
+#:
+#: The fixed-width character types, which the SQL standard has compare as
+#: though both sides were padded to the same length -- so ``'US'`` and
+#: ``'US '`` are equal in a ``CHARACTER(3)``, while ``lower()`` of the two is
+#: not. Spelled out rather than matched by prefix because the variable-width
+#: names start with the same letters: ``VARCHAR`` and ``CHARACTER VARYING``
+#: compare the blanks and must not land here.
+PADDED_CHARACTER_TYPES = frozenset(
+ {
+ "CHAR",
+ "NCHAR",
+ # PostgreSQL's own name for ``CHARACTER``, which is what reflection
+ # reports for a ``CHAR(n)`` column there.
+ "BPCHAR",
+ "CHARACTER",
+ "NATIONAL CHAR",
+ "NATIONAL CHARACTER",
+ }
+)
+
+
+def _is_padded_character_type(column: TableColumn) -> bool:
+ """
+ Whether ``column``'s declared type compares without its trailing blanks.
+
+ Read off the declared type rather than the engine spec's resolved one: the
+ specs map ``CHAR`` and ``VARCHAR`` onto the same `sqlalchemy.String`, so
+ the distinction this needs is gone by then. The length suffix is dropped
+ and the name matched against `PADDED_CHARACTER_TYPES`, so an unfamiliar
+ spelling answers ``False`` and the engine-level flag decides as before --
+ this gate adds a decline rather than lifting one. A column with no
+ declared type has nothing to read, and answers the same way.
+ """
+ if not isinstance(column.type, str):
+ return False
+ native = re.sub(r"\s+", " ", column.type.strip().upper())
+ return native.split("(")[0].strip() in PADDED_CHARACTER_TYPES
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ Padding is asked about per column, because it is a property of the *type*
+ rather than of the engine. ``binary_string_comparison`` speaks for an
+ engine's default text comparison, and on PostgreSQL -- which declares it
+ -- a ``CHAR(2)`` still matches a filter for ``'US '`` against a stored
+ ``'US'``, because the standard says a padded character type compares
+ without its trailing blanks. The mirror ``region_key = lower('US ')`` then
+ excludes the row. So a fixed-width character type declines whatever the
+ engine says, and an engine that ignores trailing blanks on its *variable*
+ types says so by not declaring the flag at all (see `RedshiftEngineSpec`).
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ # Ahead of the generic-type question, which a padded type can lose: the
+ # specs map ``CHARACTER`` onto no generic type at all on some engines, and
+ # a fixed-width character type is a string whether or not Superset can say
+ # so from the name.
+ if _is_padded_character_type(column):
+ return False
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_unicode_escaped_identifier(transform: str | None) -> bool:
+ """Whether the transform names something through a ``U&"..."`` escape.
+
+ See `UNICODE_ESCAPED_IDENTIFIER_RE`. Answered on raw text for the same
+ reason as the comment above: the parse reports a name the engine does not
+ use, which is exactly what makes the denylist blind to it.
+ """
+ return (
+ bool(transform)
+ and UNICODE_ESCAPED_IDENTIFIER_RE.search(transform or "") is not None
+ )
+
+
+#: Sequence pseudo-columns, which advance a sequence when they are *read*.
+#:
+#: ``orders_seq.NEXTVAL`` parses as a qualified column reference, not a
+#: function call, so neither `SQLStatement.is_mutating` -- which walks function
+#: names -- nor the function denylist can see it. The probe would then run
+#: ``SELECT orders_seq.NEXTVAL + 1 FROM DUAL`` and advance the sequence, again
+#: on every cache expiry, for a dataset editor holding neither SQL Lab nor a
+#: DML grant. Reading one is a write however the parser classifies it.
+#:
+#: The function spelling (``nextval('s')`` on PostgreSQL) is a different shape
+#: and is caught as a function; this is only about the suffix form.
+SEQUENCE_PSEUDO_COLUMNS = frozenset({"nextval", "currval"})
+
+
+def references_sequence_pseudo_column(statement: SQLStatement) -> bool:
+ """Whether the statement reads a sequence pseudo-column.
+
+ See `SEQUENCE_PSEUDO_COLUMNS`. Answered on the parse rather than on raw
+ text, because the name has to be in column position for this to be the
+ construct: a column or alias merely *called* ``nextval`` is not it.
+ """
+ return bool(statement.get_column_names() & SEQUENCE_PSEUDO_COLUMNS)
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """
+ Whether the transform contains a balanced Jinja block.
+
+ A block is an opening delimiter followed, anywhere later, by its closing
+ one -- the same thing ``{{.*?}}`` and its two siblings match under
+ ``re.DOTALL``. Scanned with `str.find` rather than that pattern, because a
+ lazy match retried from every opening delimiter is quadratic in a run of
+ them, and this runs on stored transforms with no length bound of its own:
+ `is_transform_active` reads whatever the column holds. The earliest opening
+ delimiter is the only one worth trying, since any closing delimiter after a
+ later one is also after it.
+ """
+ if not transform:
+ return False
+ for opening, closing in JINJA_BLOCK_DELIMITERS:
+ start = transform.find(opening)
+ if start != -1 and transform.find(closing, start + len(opening)) != -1:
+ return True
+ return False
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error( # noqa: C901
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ And it must be a *read*. Shape is a separate question from effect: a bare
+ scalar expression can still write, so `SQLStatement.is_mutating` is asked
+ too -- the same question SQL Lab and the chart executor ask before letting
+ SQL run. See the gate itself for what that reaches and what it does not.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ # Also ahead of the parse, and for a stronger reason than cost: every gate
+ # below reasons about the parse tree, and this is the one construct that
+ # makes the parse tree describe a different statement from the one the
+ # engine runs. Checked here as well as in `validate_transform` because this
+ # is the door a row written by an earlier release still comes through.
+ if contains_executable_comment(transform):
+ return str(
+ _(
+ "A partition value transform cannot contain a MySQL "
+ "executable comment, which the database executes and every "
+ "validator reads as a comment."
+ )
+ )
+
+ if contains_unicode_escaped_identifier(transform):
+ return str(
+ _(
+ "A partition value transform cannot name anything through a "
+ 'U&"..." escape sequence, which the database decodes and '
+ "every validator reads literally."
+ )
+ )
+
+ # Same door, same reason: the name the denylist below would match is not
+ # the name the engine resolves. See `UNICODE_ESCAPED_IDENTIFIER_RE`.
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The read-only gate, which nothing above implies. The shape gates ask what
+ # the transform *selects*; this asks what evaluating it *does*, and a bare
+ # scalar expression can still write. `nextval(:value)` on PostgreSQL
+ # advances a sequence: one function call, no clause, no sub-query, and not
+ # in the default `DISALLOWED_SQL_FUNCTIONS` either -- so every gate above
+ # passes it and the probe then runs it. `setval` is the same shape, and
+ # `exp.Execute` and the opaque-`exp.Command` forms arrive the same way.
+ #
+ # The large-object writers (`lo_export`, `lowrite`, `lo_from_bytea`, ...)
+ # are caught here too, and the shipped denylist happens to name them as
+ # well -- but that is config an operator can replace, while this is not.
+ #
+ # `is_mutating` is the same question SQL Lab, `get_virtual_table_metadata`
+ # and the chart executor ask before letting SQL run, so a transform is held
+ # to the bar the rest of Superset already sets rather than to one invented
+ # here. Unconditional rather than gated on `Database.allow_dml`: a transform
+ # is a scalar function of `:value` by definition, so there is no legitimate
+ # mutating one, and the probe runs on a cache schedule nobody chose -- a
+ # write would repeat every time the entry expired.
+ #
+ # It bears saying what this does not reach. A user-defined function whose
+ # body writes is a plain call no parser can tell from `lower(:value)`, and
+ # `is_mutating`'s function-name walk is PostgreSQL-only by design, since the
+ # same names are read-only elsewhere. Neither residual is specific to this
+ # feature -- a dataset editor can already have the engine evaluate an
+ # arbitrary expression through a calculated column or a virtual dataset's
+ # SQL -- and closing them means authorizing the preview against the
+ # database, not parsing harder.
+ if statement.is_mutating():
+ return str(
+ _(
+ "A partition value transform cannot change data. It is "
+ "evaluated against the database to check that it mirrors, so "
+ "it has to be a read."
+ )
+ )
+
+ # Not reached by the walk above, which is why it is its own gate: a
+ # sequence pseudo-column is a *column* to the parser and a write to the
+ # engine. See `SEQUENCE_PSEUDO_COLUMNS`.
+ if references_sequence_pseudo_column(statement):
+ return str(
+ _(
+ "A partition value transform cannot read a sequence. "
+ "NEXTVAL advances the sequence every time it is evaluated, "
+ "and the transform is evaluated on a cache schedule."
+ )
+ )
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the probe
+ uninspected -- string elements are escaped by the dialect's own literal
+ processor. `probe_sql_is_evaluable` then re-reads the finished query, which
+ is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def _placeholder_is_bindable(transform: str) -> bool:
+ """
+ Whether SQLAlchemy's ``text()`` can see ``:value`` as a bound parameter.
+
+ `VALUE_PLACEHOLDER_RE` is ``:value\b``, which matches the placeholder in a
+ Postgres cast such as ``:value::bigint``. SQLAlchemy's own bind scan is
+ ``(?<![:\\w$]):([\\w$]+)(?![:\\w$])`` -- note the trailing exclusion -- so a
+ following colon stops it: ``text(":value::bigint")`` reports a parameter
+ named ``valu``, and ``.bindparams(bindparam("value"))`` then raises
+ ``ArgumentError``.
+
+ `_probe` swallows that, so the only symptom was a perfectly valid transform
+ whose mapping silently never pruned, and a preview reporting an engine
+ failure for SQL that was never sent. Every write-side gate passes the
+ transform: it parses, it is a bare expression, and the placeholder *is* in
+ an executable position.
+
+ Answered by attempting the bind itself rather than by pattern-matching
+ ``::`` or reading ``text()``'s private parameter map, so this cannot
+ disagree with what `build_probe_sql` is about to do -- on any dialect, or on
+ a SQLAlchemy whose scan changes.
+ """
+ try:
+ sa.text(transform).bindparams(sa.bindparam("value", value=None))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return False
+ return True
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ bindable = _placeholder_is_bindable(transform)
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ elif bindable:
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ rendered = _compile_literal(clause, dialect)
+ else:
+ # `text()` cannot see the placeholder (see
+ # `_placeholder_is_bindable`), so the value is rendered by the
+ # dialect's own literal processor first and substituted as SQL
+ # text. The same two steps in the other order: binding exists to
+ # get the value through that processor, and `_compile_literal`
+ # inlines the result either way, so this is the same string by a
+ # different route -- not a loosening of the "never interpolate a
+ # raw value" rule. `parse_skeleton` substitutes literally, so a
+ # rendered literal containing a backslash is safe here.
+ rendered = parse_skeleton(
+ transform, _compile_literal(sa.literal(value), dialect)
+ )
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Four things have to hold, and all four are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ # Before the parse, because this gate's whole contract is that what the
+ # parse describes is what the engine will run, and an executable comment is
+ # precisely the text where that stops being true. The transform is already
+ # refused for carrying one; this covers the compiled statement, so no later
+ # change to how values are rendered can reintroduce it behind the gates
+ # below.
+ if contains_executable_comment(sql) or contains_unicode_escaped_identifier(sql):
+ return False
+
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if not isinstance(statement, SQLStatement):
+ # A dialect whose statements this gate cannot take apart -- KQL -- gets
+ # no probe rather than an unchecked one. It never had one: the clause
+ # inspection below is implemented for SQL statements only, and the
+ # alternative to declining here is an `AttributeError` that `_probe`
+ # swallows into the same outcome, less legibly.
+ return False
+ if statement.has_subquery():
+ return False
+ if statement.get_clause_names() - {"from"}:
+ return False
+ if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+ """
+ The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+ Parsed rather than string-compared so that the comparison in
+ `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+ not parse answers ``None``, which no statement carrying a FROM can match --
+ the probe then declines, which is the right way for an unreadable engine
+ constant to fail.
+ """
+ if not from_suffix.strip():
+ return None
+ try:
+ return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+ except SupersetParseError:
+ return None
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
Review Comment:
The mirror verdict is recorded only on a cache miss (`_run_probe`), so a successful cache hit can never undo an earlier `evaluable=false`. With a working cache and `NULLIF(:value, 0)`: filter `n = 2` probes to `2` and caches it (verdict true); `n = 0` probes to NULL and records the whole transform as not evaluable; `n = 2` again is served from cache and still mirrors, but the verdict stays false until the cache entry expires. Explore then hides the pruning glyph and the dataset editor says filters aren't mirrored while the query is in fact pruning. Should a per-input NULL be kept out of the transform-wide verdict, or should cache hits refresh it?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(explore): indicate when a filter is mirrored onto a partition column [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r3939218324
##########
superset-frontend/src/explore/components/controls/DateFilterControl/DateFilterLabel.tsx:
##########
@@ -406,7 +408,12 @@ export default function DateFilterLabel(props: DateFilterControlProps) {
{...props}
onDescriptionHoverChange={setIsDescriptionHovered}
/>
- {popoverContent}
+ {/* The glyph sits outside the popover trigger so clicking it opens the
+ tooltip rather than the time-range editor. */}
+ <Flex align="center" gap={theme.sizeUnit}>
+ {popoverContent}
+ <PartitionPruningIndicator mapping={props.partitionMapping} />
Review Comment:
**Suggestion:** The dataset-wide active mapping is shown without checking the current time range or selected temporal column, so “No filter” and unrelated columns display a glyph without a mirrored SQL predicate. [incorrect condition logic]
**Assessment:** 🟠 `Major` · 🔁 `Occurrence: Sometimes`
[](https://docs.codeant.ai/cli/resolve-pr-comments-skill) [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=c99c992c1bf14a08888005aefa8e4fe6&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=c99c992c1bf14a08888005aefa8e4fe6&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/src/explore/components/controls/DateFilterControl/DateFilterLabel.tsx
**Line:** 415:415
**Comment:**
*Incorrect Condition Logic: The dataset-wide active mapping is shown without checking the current time range or selected temporal column, so “No filter” and unrelated columns display a glyph without a mirrored SQL predicate.
Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
```
</details>
<a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F43870&comment_hash=16afe612b7a4b31306e20b232e495a267f63914e6590410afc8ffffbe445ccf8&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F43870&comment_hash=16afe612b7a4b31306e20b232e495a267f63914e6590410afc8ffffbe445ccf8&reaction=dislike'>👎</a>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4165362486
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/utils.ts:
##########
@@ -0,0 +1,510 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { t } from '@apache-superset/core/translation';
+import type {
+ PartitionMappingColumn,
+ PartitionMappingDatasource,
+ PartitionMappingIssue,
+ PartitionRowState,
+} from './types';
+
+/**
+ * Jinja delimiters.
+ *
+ * A transform is evaluated in a different context and at a different time from
+ * the chart query, so a template would not render the same way -- the backend
+ * rejects one outright. Shared so the check that declines to preview a Jinja
+ * transform and the check that blocks saving it cannot drift apart.
+ */
+const JINJA_PATTERN = /\{\{|\{%|\{#/;
+
+/**
+ * The column whose filters are mirrored.
+ *
+ * `partition_mapped_column` is an explicit override; `null` means "follow the
+ * default datetime column", so re-pointing that column moves the mapping with
+ * it. Mirrors `SqlaTable.partition_filter_mapping_summary` on the backend.
+ */
+export function resolveMappedColumn(
+ datasource: PartitionMappingDatasource,
+): string | null {
+ if (!datasource.partition_column) {
+ return null;
+ }
+ return datasource.partition_mapped_column || datasource.main_dttm_col || null;
+}
+
+/** Whether the mapped column came from `main_dttm_col` rather than an override. */
+export function mappedColumnIsImplicit(
+ datasource: PartitionMappingDatasource,
+): boolean {
+ return Boolean(
+ datasource.partition_column &&
+ !datasource.partition_mapped_column &&
+ datasource.main_dttm_col,
+ );
+}
+
+/**
+ * Whether the mapping will actually mirror anything.
+ *
+ * Drives the choice between the green "filters will automatically apply"
+ * message and the warning that nothing is mirrored yet, so "non-blank text in
+ * the box" is not a good enough test: a transform with no `:value` to
+ * substitute, or one carrying Jinja, is as inert as an empty one and the
+ * backend's own summary reports it inactive. Claiming otherwise tells an owner
+ * their queries are pruning when they are not.
+ *
+ * Shares `transformCanPreview`'s conditions rather than restating them, and is
+ * necessary rather than sufficient for the same reason: an unparseable
+ * expression or a non-deterministic function needs a SQL parser to spot, so the
+ * server stays the authority -- `valueTransformIssues` surfaces what it says at
+ * the transform field itself.
+ */
+export function mappingIsActive(
+ datasource: PartitionMappingDatasource,
+ columns: PartitionMappingColumn[],
+): boolean {
+ const mappedColumnName = resolveMappedColumn(datasource);
+ if (!mappedColumnName || mappedColumnName === datasource.partition_column) {
+ return false;
+ }
+ const mappedColumn = columns.find(
+ column => column.column_name === mappedColumnName,
+ );
+ return transformCanPreview(
Review Comment:
`lint-frontend` and `pre-commit` fail here: oxlint `no-use-before-define`, because `transformCanPreview` is declared below this call. Move its declaration above `mappingIsActive`. That moves ~25 lines, so it doesn't fit a suggestion.
##########
tests/integration_tests/datasets/api_tests.py:
##########
@@ -802,6 +802,7 @@ def test_info_security_dataset(self):
"can_get_or_create_dataset",
"can_warm_up_cache",
"can_get_drill_info",
+ "can_partition_mapping_preview",
Review Comment:
All three Python legs fail `test_info_security_dataset` on this line. Preview is remapped to `"write"` in `method_permission_name`, so `can_partition_mapping_preview` never exists.
```suggestion
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4174200783
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,1314 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` always -- ``T`` is a function
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import re
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLStatement
+from superset.utils import json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: Every entry point enforces it -- the typed column field, the import schema
+#: and the preview request -- because `is_transform_active` parses the stored
+#: value on each Explore load, and an unbounded string would make that parse
+#: the expensive part of rendering a chart.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+def mirrorable_operators(is_monotonic: bool) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ """
+ if is_monotonic:
+ return MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+ return set(MIRRORABLE_ALWAYS)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(self.is_monotonic)
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+ """
+ return VALUE_PLACEHOLDER_RE.sub(_PARSE_STANDIN, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(transform: str, engine: str) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def stored_expression_error(
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ The same subquery, function-denylist and RLS policy every other stored
+ expression goes through, applied to a value transform. It matters more
+ here than the name suggests: `build_probe_sql` binds only `:value` and
+ splices the rest of the transform in as SQL text, which the engine then
+ executes, so an ungated transform is arbitrary SQL. A dataset editor
+ without SQL Lab could store `(SELECT secret FROM protected_table LIMIT 1)
+ || :value` and read the answer back out of the emitted predicate.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
Review Comment:
With `ALLOW_ADHOC_SUBQUERY` on, a sub-query passes here but the RLS-injected SQL is discarded, so the probe reads RLS-hidden rows: preview of `(SELECT secret FROM vault …) || :value` emitted `part = 'zz-HIDDEN-by-RLS_x'`. `DISALLOWED_SQL_FUNCTIONS` isn't checked either.
```suggestion
statement = _parse_skeleton(transform, database.backend)
if statement is not None and statement.has_subquery():
# Allowed under ALLOW_ADHOC_SUBQUERY, but the probe never injects RLS.
return str(_("A partition value transform cannot contain a sub-query."))
denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(database.backend, set())
if statement is not None and denied and statement.check_functions_present(denied):
return str(_("A partition value transform cannot call a disallowed function."))
return None
```
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,1278 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` always -- ``T`` is a function
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import re
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLStatement
+from superset.utils import json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: Every entry point enforces it -- the typed column field, the import schema
+#: and the preview request -- because `is_transform_active` parses the stored
+#: value on each Explore load, and an unbounded string would make that parse
+#: the expensive part of rendering a chart.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+def mirrorable_operators(is_monotonic: bool) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ """
+ if is_monotonic:
+ return MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+ return set(MIRRORABLE_ALWAYS)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(self.is_monotonic)
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+ """
+ return VALUE_PLACEHOLDER_RE.sub(_PARSE_STANDIN, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(transform: str, engine: str) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
Review Comment:
Fixed at `115c194f58` for the default config: import drops it regardless of the flag and the probe declines it (removing either gate fails 6 import / 3 probe tests). The `ALLOW_ADHOC_SUBQUERY` case is a new comment on `stored_expression_error`.
##########
tests/integration_tests/datasets/api_tests.py:
##########
@@ -802,6 +802,7 @@ def test_info_security_dataset(self):
"can_get_or_create_dataset",
"can_warm_up_cache",
"can_get_drill_info",
+ "can_partition_mapping_preview",
Review Comment:
Fixed in `69517c2e4d`; every Python leg is green at `115c194f58`.
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/PartitionColumnFields.tsx:
##########
@@ -0,0 +1,274 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { useMemo } from 'react';
+import { t } from '@apache-superset/core/translation';
+import { css, useTheme } from '@apache-superset/core/theme';
+import { Alert } from '@apache-superset/core/components';
+import {
+ Button,
+ Flex,
+ Icons,
+ InfoTooltip,
+ Label,
+ Select,
+ Tooltip,
+ Typography,
+} from '@superset-ui/core/components';
+import {
+ mappedColumnIsImplicit,
+ mappingIsActive,
+ partitionMappingErrors,
+ resolveMappedColumn,
+ suggestedMappedColumn,
+} from './utils';
+import type {
+ PartitionMappingColumn,
+ PartitionMappingDatasource,
+ PartitionMappingIssue,
+} from './types';
+
+interface PartitionColumnFieldsProps {
+ datasource: PartitionMappingDatasource;
+ columns: PartitionMappingColumn[];
+ onPartitionColumnChange: (columnName: string | null) => void;
+ /** Open the given column's row expand in the Columns table. */
+ onNavigateToColumn: (columnName: string) => void;
+}
+
+/**
+ * "Partition column" and the computed "Maps to partition" (wireframes 1a, 1g).
+ *
+ * "Maps to partition" is deliberately read-only. It reflects
+ * `partition_mapped_column ?? main_dttm_col`, and a peer dropdown would let it
+ * drift from the default datetime column silently. The only way to override it
+ * is from the target column's own row, where a transform has to be supplied
+ * alongside.
+ */
+export default function PartitionColumnFields({
+ datasource,
+ columns,
+ onPartitionColumnChange,
+ onNavigateToColumn,
+}: PartitionColumnFieldsProps) {
+ const theme = useTheme();
+
+ const options = useMemo(
+ () =>
+ columns.map(column => ({
+ value: column.column_name,
+ label: column.column_name,
+ customLabel: (
+ <Flex align="center" gap={theme.sizeUnit}>
+ <span>{column.column_name}</span>
+ {column.type && <Label>{column.type}</Label>}
+ </Flex>
+ ),
+ })),
+ [columns, theme.sizeUnit],
+ );
+
+ const mappedColumn = resolveMappedColumn(datasource);
+ const isImplicit = mappedColumnIsImplicit(datasource);
+ const isActive = mappingIsActive(datasource, columns);
+ const { partition_column: partitionColumn } = datasource;
+
+ // `field` is what the issues carry it for: a message about the partition
+ // column belongs under the partition column, not only in the Save button's
+ // tooltip, where an owner has to guess which of the two selects is at fault.
+ const issues = useMemo(
+ () => partitionMappingErrors(datasource, columns),
+ [datasource, columns],
+ );
+ const issueFor = (field: PartitionMappingIssue['field']) =>
+ issues.find(issue => issue.field === field)?.message;
+
+ // "Map a different column instead" normally opens the currently-mapped
+ // column's row, which is where the picker lives. When the mapped column *is*
+ // the partition column -- the self-mapping the backend rejects, and reachable
+ // in one click because the picker offers every column -- that row renders no
+ // mapping section at all, so the one guided way out of the broken state led
+ // nowhere. Offer a column that is not the partition column instead.
+ const differentColumnTarget =
+ mappedColumn && mappedColumn !== partitionColumn
+ ? mappedColumn
+ : (suggestedMappedColumn(columns, partitionColumn) ?? mappedColumn);
+
+ return (
+ <Flex vertical gap={theme.sizeUnit} data-test="partition-column-fields">
+ <Flex align="center" gap={theme.sizeUnit}>
+ <Typography.Text>{t('Partition column')}</Typography.Text>
+ <InfoTooltip
+ tooltip={t(
+ 'The physical column the engine partitions on. Filters on the mapped column are mirrored onto it so the engine can prune partitions.',
+ )}
+ />
+ </Flex>
+ <Select
+ ariaLabel={t('Partition column')}
+ options={options}
+ value={partitionColumn ?? undefined}
+ onChange={value => onPartitionColumnChange((value as string) ?? null)}
+ onClear={() => onPartitionColumnChange(null)}
+ placeholder={t('None')}
+ allowClear
+ data-test="partition-column-select"
+ />
+ {issueFor('partition_column') && (
+ <Typography.Text type="danger" data-test="partition-column-error">
+ {issueFor('partition_column')}
+ </Typography.Text>
+ )}
+ <Typography.Text type="secondary">
+ {t(
+ "Column used for partition pruning on this table. Selecting one hides it from Explore's dimension and filter pickers by default.",
+ )}
+ </Typography.Text>
+
+ {partitionColumn && (
+ <Flex vertical gap={theme.sizeUnit} data-test="maps-to-partition">
+ <Flex align="center" gap={theme.sizeUnit}>
+ <Typography.Text type="secondary">
+ {t('Maps to partition')}
+ </Typography.Text>
+ <InfoTooltip
+ tooltip={t(
+ 'The column whose filters are mirrored. It follows the default datetime column unless a different column holds the mapping.',
+ )}
+ />
+ </Flex>
+
+ {mappedColumn ? (
+ <>
+ <Flex align="center" gap={theme.sizeUnit}>
+ <Label>{mappedColumn}</Label>
+ {isImplicit && (
+ <>
+ <Typography.Text type="secondary">
+ {t('Default datetime column')}
+ </Typography.Text>
+ <Tooltip
+ title={t(
+ 'Set from the default datetime column above, so re-pointing that column moves the mapping with it.',
+ )}
+ >
+ <Icons.LockOutlined
+ iconSize="s"
+ iconColor={theme.colorTextTertiary}
+ />
+ </Tooltip>
+ </>
+ )}
+ </Flex>
+ {issueFor('partition_mapped_column') && (
+ <Typography.Text
+ type="danger"
+ data-test="partition-mapped-column-error"
+ >
+ {issueFor('partition_mapped_column')}
+ </Typography.Text>
+ )}
+ <Typography.Text type="secondary">
+ {t(
+ 'Filters on this column are mirrored onto the partition column.',
+ )}{' '}
+ <Button
+ buttonStyle="link"
+ onClick={() => onNavigateToColumn(differentColumnTarget)}
Review Comment:
Fixed in `2fc5ac8c89`; `lint-frontend` (oxlint + tsc) is green at `115c194f58`.
##########
superset-frontend/src/explore/components/controls/FilterControl/AdhocFilterOption/AdhocFilterOption.test.tsx:
##########
@@ -108,3 +108,115 @@ test('should render the Popover on clicking the right caret', async () => {
await userEvent.click(rightCaret);
expect(screen.getByRole('tooltip')).toBeInTheDocument();
});
+
+// A monotonic transform, so ranges mirror alongside equality.
+const MONOTONIC_MAPPING = {
+ partition_column: 'dt_epoch',
+ mapped_column: 'value',
+ active: true,
+ is_monotonic: true,
+ mirrorable_operators: ['<', '<=', '==', '>', '>=', 'IN', 'TEMPORAL_RANGE'],
+};
+
+const withMapping = (
+ mapping: Record<string, unknown> | null,
+ adhocFilter = simpleAdhocFilter,
+) =>
+ setup({
+ ...mockedProps,
+ adhocFilter,
+ datasource: { partition_filter_mapping: mapping },
+ });
+
+const glyph = () => screen.queryByTestId('partition-pruning-indicator');
+
+test('a filter on the mapped column carries the partition pruning glyph', () => {
+ // Wireframe 1d: the chart author never configured any of this and only sees
+ // an explanation of why the query got faster.
+ render(withMapping(MONOTONIC_MAPPING));
+
+ expect(glyph()).toBeInTheDocument();
+});
+
+test('a filter on any other column carries no glyph', () => {
+ render(
+ withMapping({ ...MONOTONIC_MAPPING, mapped_column: 'some_other_column' }),
+ );
+
+ expect(glyph()).not.toBeInTheDocument();
+});
+
+test('an inactive mapping leaves the chip alone', () => {
+ render(withMapping({ ...MONOTONIC_MAPPING, active: false }));
+
+ expect(glyph()).not.toBeInTheDocument();
+});
+
+test('a negated filter on the mapped column carries no glyph', () => {
+ // The query path never mirrors a negation -- the transform need not be
+ // injective, so `value != 10` would mirror to a predicate that drops rows the
+ // original filter keeps. Labelling it would promise a speed-up the SQL does
+ // not contain.
+ render(
+ withMapping(
+ MONOTONIC_MAPPING,
+ simpleAdhocFilter.duplicateWith({ operator: '!=' }),
+ ),
+ );
+
+ expect(glyph()).not.toBeInTheDocument();
+});
+
+test('a range filter waits on the monotonicity declaration', () => {
+ render(
+ withMapping({
+ ...MONOTONIC_MAPPING,
+ is_monotonic: false,
+ mirrorable_operators: ['==', 'IN'],
+ }),
+ );
+
+ expect(glyph()).not.toBeInTheDocument();
+});
+
+test('an equality filter mirrors under a non-monotonic transform', () => {
+ render(
+ withMapping(
+ {
+ ...MONOTONIC_MAPPING,
+ is_monotonic: false,
+ mirrorable_operators: ['==', 'IN'],
+ },
+ simpleAdhocFilter.duplicateWith({ operator: '==' }),
+ ),
+ );
+
+ expect(glyph()).toBeInTheDocument();
+});
+
+test('a free-form SQL filter on the mapped column carries no glyph', () => {
+ // It lands in `extras.where`, where the backend sees no operator to mirror.
+ render(
+ withMapping(
+ MONOTONIC_MAPPING,
+ new AdhocFilter({
+ expressionType: ExpressionTypes.Sql,
+ sqlExpression: 'value > 10',
+ clause: Clauses.Where,
+ }),
+ ),
+ );
+
+ expect(glyph()).not.toBeInTheDocument();
+});
+
+test('a filter with no comparator yet carries no glyph', () => {
+ render(
+ withMapping(
+ MONOTONIC_MAPPING,
+ simpleAdhocFilter.duplicateWith({ comparator: '' }),
+ ),
+ );
+
+ expect(glyph()).not.toBeInTheDocument();
+});
Review Comment:
Fixed in `ff786951f8`; all `sharded-jest-tests` shards are green at `115c194f58`.
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/utils.ts:
##########
@@ -0,0 +1,510 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { t } from '@apache-superset/core/translation';
+import type {
+ PartitionMappingColumn,
+ PartitionMappingDatasource,
+ PartitionMappingIssue,
+ PartitionRowState,
+} from './types';
+
+/**
+ * Jinja delimiters.
+ *
+ * A transform is evaluated in a different context and at a different time from
+ * the chart query, so a template would not render the same way -- the backend
+ * rejects one outright. Shared so the check that declines to preview a Jinja
+ * transform and the check that blocks saving it cannot drift apart.
+ */
+const JINJA_PATTERN = /\{\{|\{%|\{#/;
+
+/**
+ * The column whose filters are mirrored.
+ *
+ * `partition_mapped_column` is an explicit override; `null` means "follow the
+ * default datetime column", so re-pointing that column moves the mapping with
+ * it. Mirrors `SqlaTable.partition_filter_mapping_summary` on the backend.
+ */
+export function resolveMappedColumn(
+ datasource: PartitionMappingDatasource,
+): string | null {
+ if (!datasource.partition_column) {
+ return null;
+ }
+ return datasource.partition_mapped_column || datasource.main_dttm_col || null;
+}
+
+/** Whether the mapped column came from `main_dttm_col` rather than an override. */
+export function mappedColumnIsImplicit(
+ datasource: PartitionMappingDatasource,
+): boolean {
+ return Boolean(
+ datasource.partition_column &&
+ !datasource.partition_mapped_column &&
+ datasource.main_dttm_col,
+ );
+}
+
+/**
+ * Whether the mapping will actually mirror anything.
+ *
+ * Drives the choice between the green "filters will automatically apply"
+ * message and the warning that nothing is mirrored yet, so "non-blank text in
+ * the box" is not a good enough test: a transform with no `:value` to
+ * substitute, or one carrying Jinja, is as inert as an empty one and the
+ * backend's own summary reports it inactive. Claiming otherwise tells an owner
+ * their queries are pruning when they are not.
+ *
+ * Shares `transformCanPreview`'s conditions rather than restating them, and is
+ * necessary rather than sufficient for the same reason: an unparseable
+ * expression or a non-deterministic function needs a SQL parser to spot, so the
+ * server stays the authority -- `valueTransformIssues` surfaces what it says at
+ * the transform field itself.
+ */
+export function mappingIsActive(
+ datasource: PartitionMappingDatasource,
+ columns: PartitionMappingColumn[],
+): boolean {
+ const mappedColumnName = resolveMappedColumn(datasource);
+ if (!mappedColumnName || mappedColumnName === datasource.partition_column) {
+ return false;
+ }
+ const mappedColumn = columns.find(
+ column => column.column_name === mappedColumnName,
+ );
+ return transformCanPreview(
Review Comment:
Fixed in `ff786951f8`; `lint-frontend` is green at `115c194f58`.
##########
superset/migrations/versions/2026-09-23_00-01_a7f3c2e91d84_add_partition_filter_mapping.py:
##########
@@ -0,0 +1,101 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""add partition filter mapping
+
+Adds the four columns behind the ``PARTITION_FILTER_MAPPING`` feature:
+
+- ``tables.partition_column`` -- the physical column the engine partitions on
+- ``tables.partition_mapped_column`` -- explicit override for the column whose
+ filters are mirrored; NULL means "follow ``main_dttm_col``"
+- ``table_columns.partition_value_transform`` -- the ``:value`` expression
+- ``table_columns.partition_transform_is_monotonic`` -- gates range operators
+
+The Continuum shadow tables get the same columns so dataset version history and
+restore keep working.
+
+Revision ID: a7f3c2e91d84
+Revises: 95d8a99c822e
+Create Date: 2026-08-31 22:30:00.000000
+
+"""
+
+import sqlalchemy as sa
+
+from superset.migrations.shared.utils import add_columns, drop_columns
+
+# revision identifiers, used by Alembic.
+revision = "a7f3c2e91d84"
+down_revision = "95d8a99c822e"
Review Comment:
Fixed: `down_revision` is `884a2115ebd3`, still master's only head, and `enforce-single-migration-head` is green at `115c194f58`.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #43870:
URL: https://github.com/apache/superset/pull/43870#issuecomment-5953131250
### ⚠️ Possible DB migration conflict
@hughhhh the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
To check and, if needed, fix this:
1. Rebase this branch onto the latest `master`.
2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #43870:
URL: https://github.com/apache/superset/pull/43870#issuecomment-5985174888
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers an incremental AI Review.
- `/review full` - Manually triggers a full AI Review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4331610830
##########
superset/views/datasource/utils.py:
##########
@@ -217,12 +232,85 @@ def get_samples( # pylint: disable=too-many-arguments
sample_data["page"] = page
sample_data["per_page"] = per_page
- sample_data["total_count"] = count_star_data["data"][0]["COUNT(*)"]
+ if skip_count:
+ _set_lower_bound_total(
+ sample_data, row_offset, row_limit, probed=not via_cursor
+ )
+ else:
+ sample_data["total_count"] = count_star_data["data"][0]["COUNT(*)"]
+ sample_data["total_count_is_lower_bound"] = False
return sample_data
except (IndexError, KeyError) as exc:
raise DatasetSamplesFailedError from exc
+def _count_star_query_context(
+ datasource: Datasource,
+ payload: SamplesPayloadSchema | None,
+ form_data: dict[str, Any] | None,
+ force: bool,
+) -> QueryContext:
+ count_star_metric = {
+ "metrics": [
+ {
+ "expressionType": "SQL",
+ "sqlExpression": "COUNT(*)",
+ "label": "COUNT(*)",
+ }
+ ]
+ }
+ return QueryContextFactory().create(
+ datasource={
+ "type": datasource.type,
+ "id": datasource.id,
+ },
+ queries=[{**payload, **count_star_metric} if payload else count_star_metric],
+ form_data=form_data,
+ result_type=ChartDataResultType.FULL,
+ force=force,
+ )
+
+
+def _get_count_star_data(
+ count_star_instance: QueryContext | None,
+) -> dict[str, Any]:
+ """Run the count query, or return an empty payload when it was skipped."""
+ if count_star_instance is None:
+ return {}
+
+ count_star_instance.raise_for_access()
+ count_star_data = count_star_instance.get_payload()["queries"][0]
+ if count_star_data.get("status") == QueryStatus.FAILED:
+ raise DatasetSamplesFailedError(count_star_data.get("error"))
+ return count_star_data
+
+
+def _set_lower_bound_total(
+ sample_data: dict[str, Any], row_offset: int, row_limit: int, probed: bool
+) -> None:
+ """
+ Report the total as "the rows up to and including this page".
+
+ The rows query asked for one probe row past the page. If it came back there
+ is at least one more page, so the probe is trimmed and the total flagged as
+ a lower bound; if it did not, this page is the last one and the total is
+ exact. The cursor path pages with an exact page size and has no probe row
+ (``probed=False``), so a full page is taken to mean there may be more.
+ """
+ data = sample_data.get("data") or []
+ page_size = row_limit or app.config["SAMPLES_ROW_LIMIT"]
+ if probed:
+ has_more = len(data) > page_size
Review Comment:
When the page size reaches SQL_MAX_ROW, QueryObjectFactory caps away the lookahead row. A full page is then reported as an exact total, so Drill Detail disables Next even when more rows exist.
```suggestion
has_more = len(data) > page_size or (
len(data) == page_size
and page_size >= apply_max_row_limit(page_size + 1)
)
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #43870:
URL: https://github.com/apache/superset/pull/43870#issuecomment-6281424334
### ⚠️ Possible DB migration conflict
@hughhhh the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
To check and, if needed, fix this:
1. Rebase this branch onto the latest `master`.
2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "hughhhh (via GitHub)" <gi...@apache.org>.
hughhhh commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4319678672
##########
tests/unit_tests/datasets/partition_mapping_preview_test.py:
##########
@@ -0,0 +1,1071 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+The partition mapping preview endpoint.
+
+This route fires a real warehouse query from a text input in the dataset
+editor, so the order of its guards is the point: parse and denylist checks run
+*before* anything reaches the engine, which is what keeps a half-typed
+expression from costing a query at all.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+from unittest.mock import MagicMock, patch
+
+import pytest
+from flask import Flask
+from sqlalchemy.orm.session import Session
+
+from superset import db
+
+PROBE = "superset.connectors.sqla.partition_mapping.evaluate_transform"
+
+
+@pytest.fixture(autouse=True)
+def enable_partition_filter_mapping(app: Flask) -> Any:
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = True
+ yield
+ del app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"]
+
+
+@pytest.fixture(autouse=True)
+def real_cache(app: Flask) -> Any:
+ """
+ The test app runs a null cache, which would make the rate limiter a no-op.
+ """
+ from flask_caching import Cache
+
+ from superset.extensions import cache_manager
+
+ cache = Cache(config={"CACHE_TYPE": "SimpleCache", "CACHE_DEFAULT_TIMEOUT": 300})
+ cache.init_app(app)
+ original = cache_manager._cache # noqa: SLF001
+ cache_manager._cache = cache # noqa: SLF001
+ yield
+ cache_manager._cache = original # noqa: SLF001
+
+
+@pytest.fixture(autouse=True)
+def allow_editorship(mocker: Any) -> Any:
Review Comment:
Fixed. `test_preview_refuses_a_caller_who_cannot_edit_the_dataset` uses the real `SupersetSecurityManager.raise_for_editorship` rather than the autouse mock, asserts a 403, and booby-traps the probe so a 403 that still reached the engine would fail.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4365591270
##########
superset/models/helpers.py:
##########
@@ -4552,36 +4661,777 @@ def dttm_sql_literal(self, dttm: datetime, col: "TableColumn") -> str:
return f"""'{dttm.strftime("%Y-%m-%d %H:%M:%S.%f")}'"""
- def get_time_filter( # pylint: disable=too-many-arguments # noqa: C901
+ def _mirror_probe_value(self, dttm: datetime, col: Optional["TableColumn"]) -> Any:
+ """
+ ``dttm`` in the mapped column's own stored representation.
+
+ The predicate this mirror stands in for compares the column against
+ `dttm_sql_literal(dttm, col)`, so the transform has to be probed with
+ the same value. On a column stored as an epoch integer, ``T`` is a
+ function of an integer: probing it with a `datetime` either returns
+ something unrelated to the partition keys or raises, and a raise costs
+ the dataset its pruning silently.
+
+ Only the ``python_date_format`` branches of `dttm_sql_literal` are
+ reproduced, because only those produce a *value*. `convert_dttm` yields
+ engine-specific SQL text, which cannot be bound as a parameter; its own
+ divergence from the probe is handled by widening the bounds instead
+ (`_engine_literal_resolution`).
+
+ In `dttm_sql_literal`'s own order, though: it asks ``convert_dttm``
+ first and reaches the format only when the engine answers nothing. A
+ column can carry both -- a TIMESTAMP with a ``%Y%m%d``
+ ``python_date_format``, or an entry in
+ ``python_date_format_by_column_name`` -- and applying the format
+ unconditionally probed a value the real predicate never compares.
+ ``event_time >= '2026-01-01 00:00:00'`` mirrored as
+ ``partition_col >= '20260101'``, and a January 15 row keyed
+ ``2026-01-15`` sorts below that string, so the chart lost a row the
+ filter keeps.
+
+ Where the engine does answer, the `datetime` is returned unchanged and
+ the widening path takes over -- which is exactly what already happens
+ for every temporal column that carries no format at all.
+ """
+ if col is None:
+ return dttm
+
+ if col.type and self.db_engine_spec.convert_dttm(
+ col.type, dttm, db_extra=self.db_extra
+ ):
+ # The format is unreachable in `dttm_sql_literal` for this column,
+ # so reproducing it here would describe a different bound.
+ return dttm
Review Comment:
When the engine answers `convert_dttm` for a `DATE` column, the filter compares against the date-only literal (`'2026-01-01'` on SQLite), but this returns the widened `datetime`, which the probe binds as `'2026-01-01 00:00:00.000000'`. With a `DATE` column `event_date`, a text partition key `p = CAST(event_date AS TEXT)` and a monotonic `CAST(:value AS TEXT)` transform, a January range mirrors as `p >= '2026-01-01 00:00:00.000000'`, which sorts above the key `'2026-01-01'` and drops every January 1 row the filter keeps. Could the probe use the same rendering the engine gives the original bound (for example the date itself when the literal carries no time of day)?
##########
UPDATING.md:
##########
@@ -287,6 +287,49 @@ reattached to a reachable container by layout repair.
instead; the response sets `managed_externally: true`. Read-only tools and
certification inspection are unaffected.
+- `DISALLOWED_SQL_FUNCTIONS` now names the whole PostgreSQL XML family, plus the
+ two full-text search functions that share its blind spot. Seven shapes were
+ missing -- `schema_to_xml`, `schema_to_xmlschema`,
+ `schema_to_xml_and_xmlschema`, `database_to_xml_and_xmlschema`,
+ `table_to_xmlschema`, `ts_rewrite` and `ts_stat` -- which, being scalar calls
+ with no FROM clause and no sub-query, cleared every gate that reasons about
+ table references. `ts_rewrite` and `ts_stat` run their text argument as a
+ query, so the statement they execute is a string with no clause of its own for
+ such a gate to see. The same reasoning adds a new `oracle` entry naming
+ `getxml`, `getxmltype`, `newcontext` and `newcontextfromhierarchy`, the
+ `DBMS_XMLGEN` / `DBMS_XMLQUERY` calls that run a query handed to them as
+ text, and the URI readers that name a table by path string -- `dburitype`,
+ `xdburitype`, `httpuritype` and `geturi`, the last reached through
+ `URIFACTORY.GETURI(...)`. They are listed by bare name because that is what
+ the parser sees for a package-qualified call.
+
+ The denylist is shared with SQL Lab and Charts, so a
+ deployment relying on any of these functions there will now see it refused --
+ including a deployment that never enables `PARTITION_FILTER_MAPPING`, since
+ the denylist is not gated on the feature flag. Override
+ `DISALLOWED_SQL_FUNCTIONS` in `superset_config.py` if that is intended.
+
+- A partition value transform is now refused if it changes data --
+ `nextval(:value)`, a stored-procedure call, a PostgreSQL large-object writer.
+ The transform is evaluated against the engine to check that it mirrors, and
+ that evaluation is cached and repeated, so it has to be a read. The check is
+ the same `is_mutating` gate SQL Lab and chart queries already apply, and it
+ covers transforms already in storage: one stored by an earlier version simply
+ stops mirroring rather than failing a query.
+
+- Only the mapped column may carry a partition value transform, and that is now
+ enforced on every write rather than only inside `UpdateDatasetCommand`. A
+ transform arriving on any other column is dropped -- by the deprecated
+ `POST /datasource/save/`, and by `PUT /api/v1/dataset/<pk>` and dataset import
+ even when `PARTITION_FILTER_MAPPING` is off. An API client that was storing one there
Review Comment:
This says a transform sent on a non-mapped column is dropped and the field reads `null` afterwards, including with the flag off, and `partition-filter-mapping.mdx` repeats it. But `drop_unmapped_value_transforms()` deliberately keeps an unchanged echo of the stored value (`stored_by_name`), which is exactly what a GET-then-PUT, a legacy save, or an overwrite import sends. An operator who follows this note to clear a parked transform by re-saving the dataset will still find it there. Could both places state the unchanged-echo exception and say how to clear it (send `null`)?
##########
superset/datasets/api.py:
##########
@@ -2064,6 +2165,134 @@ def get(self, id_or_uuid: str, **kwargs: Any) -> Response:
entity_concurrency_token(SqlaTable, table.id, table.uuid),
)
+ @expose("/<int:pk>/partition_mapping/preview/", methods=("POST",))
+ @protect()
+ @safe
+ @statsd_metrics
+ @event_logger.log_this_with_context(
+ action=lambda self, *args, **kwargs: (
+ f"{self.__class__.__name__}.partition_mapping_preview"
+ ),
+ log_to_statsd=False,
+ )
+ def partition_mapping_preview(self, pk: int) -> Response:
+ """Preview the predicate a partition value transform would emit.
+ ---
+ post:
+ summary: Preview a partition filter mapping
+ description: >-
+ Evaluate a partition value transform at sample values and return
+ the predicate that would be appended to queries. The predicate is
+ built by the same code the query path uses, so the preview cannot
+ drift from what a chart emits. Parse and denylist checks run
+ before anything reaches the engine, so an unparseable transform
+ costs no query.
+ parameters:
+ - in: path
+ schema:
+ type: integer
+ name: pk
+ description: The dataset ID
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/PartitionMappingPreviewSchema'
+ responses:
+ 200:
+ description: Preview result
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ result:
+ type: object
+ properties:
+ valid:
+ type: boolean
+ reason:
+ type: string
+ description: >-
+ Why the mapping is not valid. Absent when it is.
+ The editor branches on this to decide how to
+ present the failure.
+ enum:
+ - unconfigured
+ - validation
+ - parse
+ - operator
+ - resolution
+ - offset
+ - escaping
+ - transform_escaping
+ - engine
+ - type
Review Comment:
`_preview_probe()` also returns HTTP 200 with `reason: "shape"` when the range and text probes emit different predicates (for example an Oracle `TO_DATE(:value, 'YYYY-MM-DD HH24:MI:SS')` transform on a temporal sample), but `shape` is not in this enum, the generated `openapi.json` entry, or the TypeScript union. A client generated from the spec with a strict enum would reject that response. Could `shape` be added to all three and the spec regenerated?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "hughhhh (via GitHub)" <gi...@apache.org>.
hughhhh commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4367734426
##########
superset/models/helpers.py:
##########
@@ -4552,36 +4661,777 @@ def dttm_sql_literal(self, dttm: datetime, col: "TableColumn") -> str:
return f"""'{dttm.strftime("%Y-%m-%d %H:%M:%S.%f")}'"""
- def get_time_filter( # pylint: disable=too-many-arguments # noqa: C901
+ def _mirror_probe_value(self, dttm: datetime, col: Optional["TableColumn"]) -> Any:
+ """
+ ``dttm`` in the mapped column's own stored representation.
+
+ The predicate this mirror stands in for compares the column against
+ `dttm_sql_literal(dttm, col)`, so the transform has to be probed with
+ the same value. On a column stored as an epoch integer, ``T`` is a
+ function of an integer: probing it with a `datetime` either returns
+ something unrelated to the partition keys or raises, and a raise costs
+ the dataset its pruning silently.
+
+ Only the ``python_date_format`` branches of `dttm_sql_literal` are
+ reproduced, because only those produce a *value*. `convert_dttm` yields
+ engine-specific SQL text, which cannot be bound as a parameter; its own
+ divergence from the probe is handled by widening the bounds instead
+ (`_engine_literal_resolution`).
+
+ In `dttm_sql_literal`'s own order, though: it asks ``convert_dttm``
+ first and reaches the format only when the engine answers nothing. A
+ column can carry both -- a TIMESTAMP with a ``%Y%m%d``
+ ``python_date_format``, or an entry in
+ ``python_date_format_by_column_name`` -- and applying the format
+ unconditionally probed a value the real predicate never compares.
+ ``event_time >= '2026-01-01 00:00:00'`` mirrored as
+ ``partition_col >= '20260101'``, and a January 15 row keyed
+ ``2026-01-15`` sorts below that string, so the chart lost a row the
+ filter keeps.
+
+ Where the engine does answer, the `datetime` is returned unchanged and
+ the widening path takes over -- which is exactly what already happens
+ for every temporal column that carries no format at all.
+ """
+ if col is None:
+ return dttm
+
+ if col.type and self.db_engine_spec.convert_dttm(
+ col.type, dttm, db_extra=self.db_extra
+ ):
+ # The format is unreachable in `dttm_sql_literal` for this column,
+ # so reproducing it here would describe a different bound.
+ return dttm
+
+ tf = col.python_date_format
+ if not tf and self.db_extra:
+ tf = self.db_extra.get("python_date_format_by_column_name", {}).get(
+ col.column_name
+ )
+ if not tf:
+ return dttm
+
+ if tf in EPOCH_FORMATS:
+ dttm_tz_aware = dttm
+ if dttm_tz_aware.tzinfo is None:
+ dttm_tz_aware = dttm_tz_aware.replace(tzinfo=timezone.utc)
+ return int(dttm_tz_aware.timestamp()) * EPOCH_FORMATS[tf]
+ return dttm.strftime(tf)
+
+ def _engine_literal_resolution(
+ self, dttm: datetime, col: Optional["TableColumn"]
+ ) -> LiteralResolution:
+ """
+ How much of ``dttm`` survives into this engine's literal for ``col``.
+
+ The real predicate compares `dttm_sql_literal(dttm, col)`, so whatever
+ that literal throws away is a bound the engine never sees. A mirror
+ derived from the full precision then describes a *narrower* range than
+ the predicate it stands in for -- and narrower means it drops rows the
+ filter keeps.
+
+ Two things get thrown away in practice:
+
+ - the sub-second part. SQLite renders a timestamp with
+ ``timespec="seconds"``.
+ - the time of day entirely. Every engine spec with a ``types.Date``
+ branch renders ``dttm.date().isoformat()``, so Presto, Trino,
+ BigQuery and some two dozen others answer `DATE '2026-01-01'` for a
+ bound of 10:00 -- and `T(DATE '2026-01-01')` is below the mirror's
+ own lower bound, so the whole first day is dropped.
+
+ Detected rather than enumerated per engine, because the branch depends
+ on the column's type as well as the spec: instants differing only in the
+ part under test render as the same text exactly when the engine has
+ thrown that part away.
+
+ The day test uses two fixed times of day rather than ``dttm`` and one
+ alternative, so a bound that happens to sit on the hour the alternative
+ uses cannot read as "no time at all". Neither probe sits at midnight on
+ purpose: SQLite renders a DATE column at exactly midnight as a bare
+ date, so a midnight probe would differ from its alternative for a
+ reason that has nothing to do with resolution.
+
+ Likewise both sub-second probes carry a non-zero remainder. Comparing
+ against ``dttm`` truncated to the second looks like the obvious test and
+ is wrong for the same formatting-boundary reason.
+
+ A non-temporal column has no answer here, and asking anyway gets a wrong
+ one. SQLite's ``convert_dttm`` renders for ``types.String`` as well as
+ for the date types, so a ``VARCHAR`` mapped column reads as
+ second-resolution -- and a filter value that happens to *look* like an
+ instant then has its bound rounded as though the engine had truncated
+ it. On a VARCHAR ``code`` mapped onto a VARCHAR ``p`` by ``:value``,
+ ``code < '2026-07-06T10:08:11.500000'`` was mirrored as
+ ``p <= '2026-07-06 10:08:12.000000'``; a space sorts before ``T``, so a
+ row holding ``2026-07-06T09:00:00`` fell outside the mirror while
+ matching the filter.
+
+ The guard lives here rather than in each caller so this and
+ `_column_literal_resolution` cannot disagree about which column is
+ coarse -- which is the same reason that helper delegates to this one.
+
+ "Temporal" is the column's generic type, not just its ``is_dttm`` flag.
+ `get_time_filter` renders a bound through ``convert_dttm`` for any
+ ``DATE`` column, flagged or not, so a ``DATE`` column left unflagged
+ still compares a bare day -- and skipping the resolution check there
+ would hand the probe 10:00 for a bound the engine reads as midnight.
+ """
+ if col is None or not col.type or col.type_generic != GenericDataType.TEMPORAL:
+ return LiteralResolution.FULL
+
+ def render(moment: datetime) -> Optional[str]:
+ return self.db_engine_spec.convert_dttm(
+ col.type, moment, db_extra=self.db_extra
+ )
+
+ try:
+ early = render(dttm.replace(hour=1, minute=2, second=3, microsecond=444444))
+ late = render(
+ dttm.replace(hour=22, minute=33, second=44, microsecond=555555)
+ )
+ if early is not None and early == late:
+ return LiteralResolution.DAY
+
+ # Flooring to the second is a no-op on a bound that has no
+ # sub-second part, so there is nothing to detect.
+ if not dttm.microsecond:
+ return LiteralResolution.FULL
+
+ first = render(dttm.replace(microsecond=111111))
+ second = render(dttm.replace(microsecond=222222))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return LiteralResolution.FULL
+
+ if first is not None and first == second:
+ return LiteralResolution.SECOND
+ return LiteralResolution.FULL
+
+ def _round_bounds_outward(
self,
- time_col: "TableColumn",
+ start_dttm: Optional[datetime],
+ end_dttm: Optional[datetime],
+ col: Optional["TableColumn"],
+ ) -> tuple[Optional[datetime], Optional[datetime]]:
+ """
+ The bounds widened to whatever the engine's literal actually resolves to.
+
+ Rounding outward is never narrower than the predicate being mirrored,
+ which is the only property the mirror has to hold.
+ """
+ resolutions = {
+ self._engine_literal_resolution(bound, col)
+ for bound in (start_dttm, end_dttm)
+ if bound is not None
+ }
+
+ if LiteralResolution.DAY in resolutions:
+ # The engine compares a bare date, so the real predicate's lower
+ # bound is the start of that day and its upper bound admits the
+ # whole of the day before. Anything finer excludes rows it keeps.
+ if start_dttm is not None:
+ start_dttm = start_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ )
+ if end_dttm is not None and end_dttm != end_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ ):
+ end_dttm = end_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ ) + timedelta(days=1)
+ elif LiteralResolution.SECOND in resolutions:
+ if start_dttm is not None:
+ start_dttm = start_dttm.replace(microsecond=0)
+ if end_dttm is not None and end_dttm.microsecond:
+ end_dttm = end_dttm.replace(microsecond=0) + timedelta(seconds=1)
+
+ return start_dttm, end_dttm
+
+ def _literal_is_coarser_than(
+ self, dttm: datetime, col: Optional["TableColumn"]
+ ) -> bool:
+ """
+ Whether the engine's literal for ``dttm`` throws away part of it.
+
+ Unlike a range, an equality cannot be widened outward, so the only safe
+ answer when the engine compares less than the full value is to decline
+ the mirror.
+ """
+ resolution = self._engine_literal_resolution(dttm, col)
+ if resolution is LiteralResolution.DAY:
+ return dttm != dttm.replace(hour=0, minute=0, second=0, microsecond=0)
+ if resolution is LiteralResolution.SECOND:
+ return bool(dttm.microsecond)
+ return False
+
+ def _column_literal_resolution(
+ self, col: Optional["TableColumn"]
+ ) -> LiteralResolution:
+ """
+ How much of *any* value this engine compares on ``col``.
+
+ `_engine_literal_resolution` answers about a particular instant, which
+ is what a mirror derived from one needs. Two callers have no instant to
+ ask about -- the summary the Explore glyph reads, and a filter value
+ `_instant_from_filter_value` cannot read as an instant at all -- and
+ both need the column's own answer. Through one helper so that the glyph
+ and the query path cannot disagree about which column is coarse, which
+ is the same reason `mirrorable_operators` is computed once.
+
+ A non-temporal column has no answer, and asking anyway gets a wrong one:
+ SQLite's ``convert_dttm`` renders for ``types.String`` as well as for the
+ date types, so a reference instant makes a ``VARCHAR`` mapped column look
+ second-resolution -- and ``country = 'US'``, the text half of this
+ feature, reads as a value the engine compares coarsely.
+
+ That guard is `_engine_literal_resolution`'s, not this function's. It
+ used to be here, on the belief that the per-instant callers never met
+ the case because they arrive only with a value that parsed as an
+ instant -- which is untrue of a text column holding ISO-shaped text,
+ where the value parses and the column is still not temporal.
+ """
+ return self._engine_literal_resolution(_RESOLUTION_REFERENCE_INSTANT, col)
+
+ def _round_bound_outward(
+ self,
+ instant: datetime,
+ col: Optional["TableColumn"],
+ *,
+ is_upper: bool,
+ ) -> datetime:
+ """
+ One bound widened to whatever the engine resolves ``col`` to.
+
+ `_round_bounds_outward` answers for a since/until pair, because a time
+ range is the shape it was written for. A single comparison is one end of
+ such a pair with the other end absent, and the widening is per-end
+ already -- a lower bound moves back, an upper bound forward.
+
+ Narrowing the return type is the other half of the point: a bound handed
+ in non-`None` comes back non-`None`, and saying so here saves every
+ caller from re-establishing it.
+ """
+ start_dttm, end_dttm = self._round_bounds_outward(
+ None if is_upper else instant,
+ instant if is_upper else None,
+ col,
+ )
+ rounded = end_dttm if is_upper else start_dttm
+ return rounded if rounded is not None else instant
+
+ def _in_column_number_type(self, value: Any, col: Optional["TableColumn"]) -> Any:
+ """
+ A numeric ``value`` in the number type the mapped column stores.
+
+ The engine compares a number against the column in the column's own
+ domain, so ``n = '1.0'`` on an integer ``n`` matches the row holding
+ ``1``. `filter_values_handler` hands over ``1.0``, though, and a
+ transform whose output depends on the representation --
+ ``CAST(:value AS TEXT)`` answers ``'1.0'`` where the row's key is
+ ``'1'`` -- then mirrors to a partition value no matching row holds.
+ Probing at the value the column would hold keeps ``T(col) = T(v)``.
+
+ Integer columns only. A non-integral value on an integer column is
+ returned unchanged -- it matches no row, so its mirror cannot drop one.
+
+ Nothing is converted for an approximate or exact decimal column, even
+ though ``1`` and ``1.0`` are the same number to a ``REAL``. What the
+ transform sees is the *literal*, and how an engine renders one is not
+ something the engine spec exposes: on PostgreSQL ``CAST(1.0 AS TEXT)``
+ is ``'1.0'`` while the ``REAL`` column holding that value renders as
+ ``'1'``, so coercing the value to ``float`` mirrored onto a partition
+ key no matching row holds -- the same failure this helper exists to
+ stop, in the other direction. A ``DECIMAL`` column says it louder,
+ since its text also depends on a scale the spec does not carry. For
+ both, the rendering stays the owner's assumption, like
+ ``p = T(mapped_col)`` itself.
+ """
+ if (
+ col is None
+ or not col.type
+ or isinstance(value, bool)
+ or not isinstance(value, (int, float, Decimal))
+ ):
+ return value
+ try:
+ column_spec = self.db_engine_spec.get_column_spec(
+ col.type, db_extra=self.db_extra
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return value
+ if column_spec is None:
+ return value
+ sqla_type = column_spec.sqla_type
+ type_class = sqla_type if isinstance(sqla_type, type) else type(sqla_type)
+ if issubclass(type_class, sa.Integer):
+ if isinstance(value, int):
+ return value
+ try:
+ return int(value) if value == int(value) else value
+ except (OverflowError, ValueError):
+ # Infinity and NaN have no integer, and match no integer row.
+ return value
+ return value
+
+ def _mirror_probe_input(
+ self,
+ operator: utils.FilterOperator,
+ value: Any,
+ col: Optional["TableColumn"],
+ ) -> Any:
+ """
+ ``value`` in the representation the mirror may probe the transform at.
+
+ A simple filter on a temporal column carries a *string*.
+ `filter_values_handler` rewrites only an all-digit value, which it reads
+ as epoch milliseconds, so ``'2026-07-06 10:08:11'`` reaches here exactly
+ as the chart author typed it and is bound as text. The engine compares
+ that text against the column under its own cast, and on a ``DATE``
+ column the cast drops the time of day: the filter keeps the whole of
+ 2026-07-06 while a mirror probed at 10:08:11 keeps one instant of it,
+ which is narrower than the predicate it stands in for.
+
+ So the text is read back into the instant it denotes -- the only way
+ `_engine_literal_resolution`, which answers about a `datetime`, reaches
+ a filter value at all -- and where the engine compares less of that
+ instant than the filter carries, what to do about it is a property of
+ the *operator*:
+
+ * a bound rounds outward, through the helper the range collector uses.
+ Reading one extra bucket at the edge is the trade this feature makes
+ everywhere else too -- see `mirror_operator` -- and the original
+ predicate is still in the query to exclude the rows that bucket adds.
+ * an equality, or one member of an ``IN`` list, has nowhere to widen to.
+ These entries are ``AND``-ed onto the query, so "or the day either
+ side" is not something this sink can express, and the request is
+ declined with `_UNMIRRORABLE`. The query is then correct and unpruned,
+ which is the one failure mode this feature is allowed.
+
+ An instant carrying a UTC offset is declined for every operator, a
+ bound included. Rounding one outward would first have to place it in the
+ frame the partition column was written in, and guessing that frame is
+ how a mirror ends up a whole offset narrower than the filter -- see the
+ load-bearing assumption in
+ `superset.connectors.sqla.partition_mapping`.
+
+ A *string* `_instant_from_filter_value` cannot read at all is declined on
+ the same terms, and for the same reason one more step back: there is no
+ instant to round. ``'07/06/2026 10:08:11'`` is not ISO 8601, so the
+ parser leaves it alone -- and Postgres casts that same text to a DATE and
+ keeps the whole of July 6 while the probe, handed the string verbatim,
+ evaluates the transform at 10:08:11 and asks for a partition key no row
+ holds. That is exactly the narrowing the ISO-only parser was written to
+ prevent, reached through a value it declines to read, so the decline has
+ to travel with it. Which costs a non-ISO *date* its pruning too, because
+ telling July 6 from June 7 is the guess that started this.
+
+ Only a string. `_as_probe_input` has already run, so the engine SQL
+ `filter_values_handler` returns for an epoch-millisecond bound arrives
+ here as a `RawProbeValue` rather than text -- and that literal was
+ rendered by the engine at the engine's own resolution, so it is the one
+ thing on this path with nothing left to resolve. The escaping gate has
+ run too, on the value as it arrived; a string this method *returns* is a
+ fresh one, which is why `evaluate_transform` asks again.
+
+ Where the engine compares the whole instant, a string is returned
+ exactly as it arrived -- down to the type the probe binds and the cache
+ key it lands on, because every query that was already correct has to
+ stay byte-for-byte correct. A `datetime` is still converted, which it
+ has always needed: on a column stored as an epoch integer the transform
+ is a function of an integer, and a `datetime` is not the value the real
+ predicate compares.
+ """
+ value = self._in_column_number_type(value, col)
+ parsed = _instant_from_filter_value(value)
+ if parsed is None:
+ if (
+ isinstance(value, str)
+ and self._column_literal_resolution(col) is not LiteralResolution.FULL
+ ):
+ return _UNMIRRORABLE
+ return value
+
+ # Ahead of the full-resolution return: a transform such as
+ # `CAST(:value AS TIMESTAMP)` drops the offset, so even an engine that
+ # compares the whole instant would probe it in the wrong frame. Its own
+ # reason, because mapping a column the engine compares in full -- the
+ # advice the resolution decline carries -- does not help here.
+ if parsed.tzinfo is not None:
+ return _UNMIRRORABLE_OFFSET
+
+ if self._engine_literal_resolution(parsed, col) is LiteralResolution.FULL:
+ return (
+ self._mirror_probe_value(parsed, col)
+ if isinstance(value, datetime)
+ else value
+ )
+
+ if operator in LOWER_BOUND_OPERATORS:
+ instant = self._round_bound_outward(parsed, col, is_upper=False)
+ elif operator in UPPER_BOUND_OPERATORS:
+ instant = self._round_bound_outward(parsed, col, is_upper=True)
+ elif self._literal_is_coarser_than(parsed, col):
+ return _UNMIRRORABLE
+ else:
+ instant = parsed
+
+ if instant == parsed and not isinstance(value, datetime):
+ return value
+ return self._mirror_probe_value(instant, col)
+
+ def _collect_partition_mirror_range(
+ self,
+ mapping: Optional["PartitionMapping"],
+ sink: list[tuple[utils.FilterOperator, Any]],
+ column_name: str,
start_dttm: Optional[sa.DateTime],
end_dttm: Optional[sa.DateTime],
- time_grain: Optional[str] = None,
- label: Optional[str] = "__time",
- template_processor: Optional[BaseTemplateProcessor] = None,
- ) -> Optional[ColumnElement]:
- col = (
- time_col.get_timestamp_expression(
- time_grain=time_grain,
- label=label,
- template_processor=template_processor,
+ widen_bounds_by: Optional[relativedelta] = None,
+ ) -> None:
+ """
+ Record a time range for mirroring onto the partition column.
+
+ The bounds are adjusted first, by the same helper `get_time_filter` uses:
+ the mirrored predicate has to describe the same instants as the
+ timestamp predicate it stands in for, or the pruning is wrong by exactly
+ the dataset's timezone offset -- silently.
+
+ Either bound may be `None` for an open-ended range, in which case only
+ the bound that exists is mirrored.
+
+ Both bounds are recorded with the operators the real predicate uses,
+ `>=` and `<`. Relaxing the strict one is `mirror_operator`'s job, at the
+ single point where an operator becomes SQL -- which is also the point
+ the preview endpoint goes through.
+
+ `widen_bounds_by` is one grain bucket width, passed when the filter this
+ stands in for compares a *truncated* column. The real predicate then
+ keeps rows the raw bounds exclude, and widening both ends by one bucket
+ is the smallest range guaranteed to contain all of them -- see the "Time
+ grains" section of `superset.connectors.sqla.partition_mapping`.
+
+ A widened range can also be wide enough to fail `_bounds_are_ordered`
+ against a tighter filter on the same column. That fails open -- no
+ mirroring, no pruning, no dropped rows.
+ """
+ if mapping is None or column_name != mapping.mapped_column:
+ return
+ if not mapping.mirrors(utils.FilterOperator.TEMPORAL_RANGE):
+ return
+
+ # Resolve the column so the offset adjustment sees the same type
+ # `get_time_filter` does -- an offset the column's type cannot represent
+ # is dropped, and the mirrored bounds have to agree with the originals.
+ mapped_col = next(
+ (col for col in self.columns if col.column_name == column_name), None
+ )
+ start_dttm, end_dttm = self.adjust_time_bounds(start_dttm, end_dttm, mapped_col)
+
+ # Adjust first, then widen. `adjust_time_bounds` moves the naive UI
+ # bounds into the frame the column is *stored* in, and the grain
+ # truncation in the real predicate happens in that same frame, so the
+ # bucket width has to be added there too. The two commute for the
+ # hour-offset branch but not for the `ZoneInfo` one, where widening
+ # across a DST boundary first lands an hour out.
+ if widen_bounds_by is not None:
+ if start_dttm is not None:
+ start_dttm -= widen_bounds_by
+ if end_dttm is not None:
+ end_dttm += widen_bounds_by
+
+ # Then round outward, to whatever the engine's literal resolves to.
+ start_dttm, end_dttm = self._round_bounds_outward(
+ start_dttm, end_dttm, mapped_col
+ )
+
+ # Converted last. The widening and rounding above are `datetime`
+ # arithmetic, and the stored representation may be an integer.
+ if start_dttm is not None:
+ sink.append(
+ (
+ utils.FilterOperator.GREATER_THAN_OR_EQUALS,
+ self._mirror_probe_value(start_dttm, mapped_col),
+ )
)
- if time_grain
- else self.convert_tbl_column_to_sqla_col(
- time_col, label=label, template_processor=template_processor
+ if end_dttm is not None:
+ sink.append(
+ (
+ utils.FilterOperator.LESS_THAN,
+ self._mirror_probe_value(end_dttm, mapped_col),
+ )
)
+
+ def _array_mirror_probe_value(
+ self,
+ value: Any,
+ operator: utils.FilterOperator,
+ element_type: Optional[utils.GenericDataType],
+ db_engine_spec: builtins.type["BaseEngineSpec"],
+ ) -> Any:
+ """
+ The array literal the real predicate compares, ready to probe with.
+
+ On an array column the predicate is not built from `eq` at all: the
+ branch below reads the raw `val`, parses the pasted literal into
+ elements, coerces them to the array's element type and asks the engine
+ spec for its own array syntax. Mirroring `eq` would probe the transform
+ at a value the query never compares, so this reproduces that chain
+ instead -- the mirror then probes exactly what the predicate holds.
+
+ The result is SQL text rather than a value, because an array literal is
+ an expression; `RawProbeValue` carries it and `build_probe_sql`
+ substitutes rather than binds. Returns `None` when the engine spec
+ claims multi-value columns without implementing a literal for them, or
+ when an element has no literal the dialect can render -- a nested array
+ such as ``[[1, 2]]`` -- which costs the query its pruning and nothing
+ else.
+
+ An element the driver and the engine would not spell the same way
+ declines with `_UNMIRRORABLE_ESCAPING` instead, which the preview can
+ explain. It has to be asked here: once the elements are inside the
+ engine's own array syntax there is no single value left for
+ `value_round_trips` to compare a parse against.
+ """
+
+ def literal(entry: Any) -> Any:
+ elements = coerce_array_values(parse_array_literal(entry), element_type)
+ if not all(
+ value_round_trips(self.database, element) for element in elements
+ ):
+ return _UNMIRRORABLE_ESCAPING
+ return raw_probe_value(
+ self.database,
+ db_engine_spec.array_literal(elements),
+ )
+
+ try:
+ if operator in {utils.FilterOperator.IN, utils.FilterOperator.NOT_IN}:
+ candidates = (
+ list(value) if isinstance(value, (list, tuple)) else [value]
+ )
+ members = tuple(literal(candidate) for candidate in candidates)
+ # One element's problem is the whole list's, for the reason
+ # `mirror_probe_request` gives: mirroring the rest would be
+ # narrower than the filter.
+ return next(
+ (member for member in members if is_unmirrorable(member)),
+ members,
+ )
+ return literal(value)
+ except (NotImplementedError, sa.exc.CompileError):
+ return None
+
+ def _as_probe_input(self, value: Any) -> Any:
+ """
+ ``value`` in a form `build_probe_sql` can put into the probe.
+
+ `filter_values_handler` returns engine SQL rather than a value for an
+ epoch-millisecond bound on a temporal column -- what drill-to-detail and
+ cross-filters send -- and SQL cannot be the value of a bind parameter.
+ Carrying it as text lets the probe substitute it instead, exactly as the
+ preview path's own coercion does and as an array literal needs.
+
+ Text rather than the expression itself also matters for caching: the
+ probe cache keys on `repr` of each value, and a `ColumnClause`'s default
+ `repr` carries its memory address, so every request would miss.
+
+ Returns `_UNRENDERABLE` when the engine cannot render the literal, which
+ costs the query its pruning and nothing else -- the same thing the probe
+ itself does on failure.
+
+ Rendering is only half of what has to hold about a literal: whether the
+ engine reads the rendered text back as the value the filter compares is
+ asked separately, by `mirror_probe_request` through
+ `partition_mapping.value_round_trips`.
+ """
+
+ def rendered(entry: Any) -> Any:
+ if isinstance(entry, ColumnElement):
+ return raw_probe_value(self.database, entry)
+ return entry
+
+ try:
+ if isinstance(value, (list, tuple)):
+ return type(value)(rendered(item) for item in value)
+ return rendered(value)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ logger.warning(
+ "Could not render a filter value for the partition mirror; "
+ "queries will not prune",
+ exc_info=True,
+ )
+ return _UNRENDERABLE
+
+ def _collect_partition_mirror_filter(
+ self,
+ mapping: Optional["PartitionMapping"],
+ sink: list[tuple[utils.FilterOperator, Any]],
+ column_name: str,
+ operator: utils.FilterOperator,
+ value: Any,
+ ) -> None:
+ """
+ Record a structured filter for mirroring onto the partition column.
+
+ Only operators the mapping declares safe are recorded; see the operator
+ matrix in `superset.connectors.sqla.partition_mapping`.
+
+ The value itself is resolved by `mirror_probe_request`, which the preview
+ endpoint calls too so that the two cannot answer differently.
+ """
+ if mapping is None or column_name != mapping.mapped_column:
+ return
+ if not mapping.mirrors(operator):
+ return
+
+ mapped_col = next(
+ (col for col in self.columns if col.column_name == column_name), None
)
+ probe_value = self.mirror_probe_request(operator, value, mapped_col)
+ if is_unmirrorable(probe_value):
+ return
+ sink.append((operator, probe_value))
+
+ def mirror_probe_request(
+ self,
+ operator: utils.FilterOperator,
+ value: Any,
+ col: Optional["TableColumn"],
+ ) -> Any:
+ """
+ ``value`` as the mirror may probe the transform at, or an `Unmirrorable`.
+
+ The whole of what has to happen to a filter value before it can be
+ probed, in one place because two callers need it: the chart query path,
+ and the dataset editor's preview endpoint. The preview used to coerce the
+ value and then probe it directly, so it reported a mirror for a request
+ the chart path declines -- an owner was shown a valid predicate on a
+ `DATE` mapped column whose equality filters never mirror at all.
+
+ Routing per *value* rather than per Python type is what makes a bound
+ widen and an equality decline whichever shape the value arrived in -- a
+ `datetime` from drill-to-detail, or the raw string a simple filter binds.
+ """
+ # A decline the caller already made, passed through: the array branch
+ # and the preview's own coercion both answer with an `Unmirrorable` of
+ # their own, and re-reading it as a filter value here would lose the
+ # reason the preview is about to explain.
+ if is_unmirrorable(value):
+ return value
+
+ # First, and ahead of anything that reads the value as an instant: a
+ # value `filter_values_handler` already turned into engine SQL is
+ # carried as text from here on, and the probe has to receive exactly
+ # that literal -- it is what the real predicate compares, so there is
+ # nothing left to resolve about it. Idempotent, so a caller that has
+ # already rendered its own values may still come through here.
+ value = self._as_probe_input(value)
+ if value is _UNRENDERABLE:
+ return UNMIRRORABLE
+
+ # Then, before any of the resolution rules: whether this database's
+ # driver and engine would write the value down the same way. They do
+ # not always -- see `partition_mapping.literal_round_trips` -- and a
+ # value they disagree about is either probed as something nobody
+ # filtered on or, where it closes its own quote, read as SQL. Its own
+ # reason, because nothing about the column, the operator or the
+ # transform is what went wrong, so none of the advice the resolution
+ # branch carries applies.
+ #
+ # One member is the whole list's problem, as below: mirroring the rest
+ # would be narrower than the filter.
+ candidates = value if isinstance(value, (list, tuple)) else [value]
+ if not all(
+ value_round_trips(self.database, candidate) for candidate in candidates
+ ):
+ return UNMIRRORABLE_ESCAPING
+
+ if operator == utils.FilterOperator.IN:
+ if not isinstance(value, (list, tuple)) or not value:
+ return UNMIRRORABLE
+ if any(item is None for item in value):
+ # A `None` in the list widens the real predicate to
+ # `col IS NULL OR col IN (...)`. Mirroring only the non-null
+ # members would be *narrower* than the original filter and
+ # would drop rows it keeps. Checked before the conversion
+ # below, which passes a `None` straight through and could not
+ # be told apart from a value afterwards.
+ return UNMIRRORABLE
+ members = tuple(
+ self._mirror_probe_input(operator, item, col) for item in value
+ )
+ if declined := next(
+ (member for member in members if is_unmirrorable(member)), None
+ ):
+ # One member the engine compares more coarsely than the mirror
+ # can be built from is the whole list's problem: dropping just
+ # that member is the same narrowing the `None` guard above
+ # refuses. So the list declines entire, carrying the first
+ # member's reason -- the one an owner reading the preview would
+ # have to fix first anyway.
+ return declined
+ return members
+
+ if value is None:
+ return UNMIRRORABLE
+ return self._mirror_probe_input(operator, value, col)
+
+ def _build_partition_mirror_predicates(
+ self,
+ mapping: "PartitionMapping",
+ requests: list[tuple[utils.FilterOperator, Any]],
+ ) -> list[ColumnElement]:
+ """
+ Resolve collected mirror requests into predicates on the partition column.
+
+ Requests are deduplicated first: a chart can reach both collection points
+ for the same column -- a `granularity` time filter *and* a
+ `TEMPORAL_RANGE` ad-hoc filter on the same column is a routine Explore
+ configuration -- and emitting the predicate twice is harmless SQL but
+ makes "View query" surprising.
+ """
+ if not requests:
+ return []
+
+ deduped: list[tuple[utils.FilterOperator, Any]] = []
+ seen: set[Any] = set()
+ for operator, value in requests:
+ # Keyed on the operator the mirror is *emitted* with, not the one
+ # collected: a strict bound and its non-strict twin on the same
+ # value build the same predicate, so they are the same request.
+ key = (
+ mirror_operator(operator),
+ value if isinstance(value, Hashable) else repr(value),
+ )
+ if key not in seen:
+ seen.add(key)
+ deduped.append((operator, value))
+
+ return build_mirrored_predicates(cast("SqlaTable", self), mapping, deduped)
Review Comment:
Thanks, my bug. Fixed in [83f0660f2a](https://github.com/apache/superset/pull/43870/commits/83f0660f2a): the lookup only reads a `Mapping` and treats any failure as "may hold a time of day", and the chart path (and preview) now fail open on any error building the mirror.
##########
superset/datasets/api.py:
##########
@@ -2064,6 +2165,134 @@ def get(self, id_or_uuid: str, **kwargs: Any) -> Response:
entity_concurrency_token(SqlaTable, table.id, table.uuid),
)
+ @expose("/<int:pk>/partition_mapping/preview/", methods=("POST",))
+ @protect()
+ @safe
+ @statsd_metrics
+ @event_logger.log_this_with_context(
+ action=lambda self, *args, **kwargs: (
+ f"{self.__class__.__name__}.partition_mapping_preview"
+ ),
+ log_to_statsd=False,
+ )
+ def partition_mapping_preview(self, pk: int) -> Response:
Review Comment:
Fixed in [83f0660f2a](https://github.com/apache/superset/pull/43870/commits/83f0660f2a): the check moved into `build_mirrored_predicates`, so charts run it too. Each date/timestamp is also asked as text in the same probe (still one round trip), bypassing the gates that declined it at 10:47:23, and a disagreement drops the mirror.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "hughhhh (via GitHub)" <gi...@apache.org>.
hughhhh commented on PR #43870:
URL: https://github.com/apache/superset/pull/43870#issuecomment-5943828536
## Review comments carried over from the five-PR stack
Partition filter mapping shipped as five stacked PRs (#43757, #43758, #43759,
#43891, #43870) and was then collapsed into one: #43870, re-pointed at `master`.
Closing the four parents orphans their review threads, so every thread from
**Joe** (`sadpandajoe`) and **Evan** (`rusackas`) that GitHub still showed as
unresolved is reproduced here, with a link back to the original and what became
of it.
Most are marked *addressed*: the fix landed in the review pass of 2026-10-01 and
the thread is unresolved only because nobody clicked Resolve. The exceptions say
so in their own words.
**47 threads — 46 addressed, 1 left as a stated limitation.**
## PR #43757 — model, migration and validation
*closed as superseded by #43870. 1 unresolved thread.*
### `superset/connectors/sqla/models.py`:1987
[thread](https://github.com/apache/superset/pull/43757#discussion_r3947007438) · hughhhh, sadpandajoe
> A nonblank transform that fails validation (for example, one without `:value`) is deliberately saved as inactive, but this summary marks it active anyway. Should the summary use the same validation result so the Explore indicator does not report a mapping that will never mirror filters?
**Addressed** in `17a5f68312 (earlier pass)` — `models.py` calls `is_transform_active`; pinned by `test_activity_is_exactly_the_absence_of_issues`
## PR #43758 — query-time mirroring
*closed as superseded by #43870. 2 unresolved threads.*
### `superset/models/helpers.py`:5832
[thread](https://github.com/apache/superset/pull/43758#discussion_r3946865281) · sadpandajoe
> This can silently remove rows whenever a mapped Hive or Impala column has a supported NULL/special partition: the original filter can match the row, but the appended partition comparison cannot. Should mappings reject that case or preserve those rows before adding this predicate?
**Addressed** in `1987cb8cfd (earlier pass)` — every mirror is wrapped in `OR partition_col IS NULL`
### `superset/models/helpers.py` *(outdated)*
[thread](https://github.com/apache/superset/pull/43758#discussion_r3946874912) · sadpandajoe
> This mirrors the raw range even when the real predicate uses `flt_grain` and filters a truncated timestamp expression. For a weekly upper bound, rows later in the final week still match `DATE_TRUNC(...) < until` but the raw partition predicate excludes them. Should grain-bearing filters skip mirroring (or use bounds that preserve the truncated predicate)?
**Addressed** in `1987cb8cfd + 3d028a015a (earlier pass)` — grained non-ranges skip mirroring; grained ranges widen both bounds
## PR #43759 — preview endpoint and editor plumbing
*closed as superseded by #43870. 6 unresolved threads.*
### `superset/datasets/api.py` *(outdated)*
[thread](https://github.com/apache/superset/pull/43759#discussion_r3942064511) · sadpandajoe
> This read-then-set counter is not atomic. Concurrent preview requests can all read the same value below the limit, each write the same incremented value, and all reach the warehouse probe, so a burst can bypass the query-load guard this endpoint relies on. Could this use an atomic cache increment/limit operation and cover concurrent requests?
**Addressed** in `d9125ebe19 (earlier pass) + 17f8f28b41` — `add`+`inc`, and the window now comes from a bucketed key
### `superset/datasets/api.py` *(outdated)*
[thread](https://github.com/apache/superset/pull/43759#discussion_r4054141949) · codeant-ai-for-open-source, sadpandajoe
> Agreed—the current `inc()` still resets the expiry on SimpleCache and other read-modify-write backends, using the default cache timeout rather than 60 seconds. With the one-day default, retries after the budget is spent keep renewing a day-long lockout; could the fixed-window behavior be enforced for supported backends or the Redis-only requirement be explicit?
**Addressed** in `17f8f28b41` — the window is carried by a per-window key, so a backend whose `inc` restamps its own default lifetime can only affect the window it belongs to. A `SimpleCache` test drives two adjacent windows.
### `superset/connectors/sqla/partition_mapping.py`:948
[thread](https://github.com/apache/superset/pull/43759#discussion_r4155597487) · sadpandajoe
> A successful integer probe returns a NumPy scalar from the pandas row, but `sa.literal()` cannot infer its SQL type, so the canonical epoch transform raises `CompileError` here and preview returns 500. Could the probed scalar be normalized or rendered with an explicit type, with coverage through a real DataFrame result rather than a mocked Python `int`?
**Addressed** in `17f8f28b41` — `_to_python_scalar` at the probe boundary; the test patches `Database.get_df`
### `superset-frontend/src/components/Datasource/DatasourceModal/index.tsx`:243
[thread](https://github.com/apache/superset/pull/43759#discussion_r4155597505) · sadpandajoe
> The Dataset List editor loads `/api/v1/dataset/{id}`, whose column response omits both transform fields, so an unrelated save now sends `null`/`false` and overwrites an existing mapping, silently disabling pruning. Could those fields be included in the GET response and the GET→edit→PUT round trip be covered?
**Addressed** in `earlier pass` — both fields are in `show_select_columns` / `show_columns`
### `superset/connectors/sqla/partition_mapping.py`:914
[thread](https://github.com/apache/superset/pull/43759#discussion_r4155597514) · sadpandajoe
> A dataset editor without SQL Lab can submit a scalar subquery as the unsaved transform and receive its warehouse result in `emitted_predicate`; this path never applies the subquery/RLS checks used for stored expressions. Could the shared SQL policy and row-level-security validation run before the probe, so preview cannot read rows the editor is not authorized to retrieve?
**Addressed** in `17f8f28b41` — `validate_stored_expression` runs before the probe
### `superset/datasets/api.py`:216
[thread](https://github.com/apache/superset/pull/43759#discussion_r4155597527) · sadpandajoe
> If the Redis key expires after `add()` returns false but before `inc()`, `INCR` recreates it without a TTL. That counter then never resets, so this user eventually gets permanent 429s for the dataset; could creation/increment/expiry be atomic or missing expiry be repaired?
**Addressed** in `17f8f28b41` — same per-window key: a TTL-less counter can only affect its own window
## PR #43891 — editor UI and docs
*closed as superseded by #43870. 22 unresolved threads.*
### `docs/admin_docs/configuration/partition-filter-mapping.mdx` *(outdated)*
[thread](https://github.com/apache/superset/pull/43891#discussion_r3938586515) · sadpandajoe
> Hive and Impala both support special partitions for NULL partition-key values. A mapped filter such as `event_time >= ...` then appends `dt_epoch >= ...` and drops those matching rows, so this feature can return an incomplete chart result. Should this explicitly reject/handle NULL partition values (and update the documentation) rather than assert they cannot occur?
**Addressed** in `1987cb8cfd (earlier pass)` — every mirror is wrapped in `OR partition_col IS NULL`
### `superset/connectors/sqla/partition_mapping.py`:1070
[thread](https://github.com/apache/superset/pull/43891#discussion_r3939219865) · codeant-ai-for-open-source, sadpandajoe
> `TEMPORAL_RANGE` is allowed by the preview schema, but this path forwards the single transformed value to `handle_comparison_filter`, whose base implementation only handles scalar comparison operators and raises `ValueError` for `TEMPORAL_RANGE`. Should the preview either reject this operator or build both range bounds with the same temporal-range path as chart queries?
**Addressed** in `6113387c98` — `PREVIEWABLE_OPERATORS` excludes it, in both the request schema and the function
### `superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/PartitionMappingSection.tsx`:81
[thread](https://github.com/apache/superset/pull/43891#discussion_r4129728947) · sadpandajoe
> In `usePartitionMappingPreview.ts`, neither the success handler (`.then()`, line 93) nor the early-return guard (lines 66–74) checks whether the in-flight request is still the current one, so the preview panel this returns can get stuck or show stale data. If `transformCanPreview` starts failing while a request is pending (for example the owner clears the transform), the pending request's `.catch`/`.finally` both skip `setLoading(false)` because `controlle
**Addressed** in `6113387c98` — request-id check in `.then`/`.catch`/`.finally`, and `loading` cleared on the early return
### `superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/PartitionMappingSection.tsx`:81
[thread](https://github.com/apache/superset/pull/43891#discussion_r4129728956) · sadpandajoe
> `usePartitionMappingPreview.ts` uses a literal NUL byte as an array delimiter (`sampleValues.join('\0')` at line 62, `sampleKey.split('\0')` at line 87). That's why `git diff`/GitHub render that file as "Binary files differ" instead of text — every future change to it will show the same way, hiding it from normal diff and blame tooling. Could the delimiter be something that isn't a valid string character in practice (or the round-trip through a string key
**Addressed** in `6113387c98` — `JSON.stringify` key plus a `useMemo`; the file diffs as text again
### `superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/PartitionColumnFields.tsx` *(outdated)*
[thread](https://github.com/apache/superset/pull/43891#discussion_r4129728963) · sadpandajoe
> None of the four new `Typography.Link` action triggers this section introduces have an `href` — here, and also at line 171 and line 200 in this file, plus `PartitionMappingSection.tsx:106`. Ant Design's `Typography.Link` without `href` renders an `<a>` that's outside the natural tab order and doesn't respond to Enter/Space, so a keyboard-only user can't reach "Map a different column instead", "Customize the value transform", "Map a column", or "Move mappin
**Addressed** in `6113387c98` — all four are link-styled `Button`s, with keyboard tests
### `superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/utils.ts`:77
[thread](https://github.com/apache/superset/pull/43891#discussion_r4129728972) · sadpandajoe
> This treats any non-blank `partition_value_transform` as an active mapping, but the backend's own `partition_filter_mapping_summary` (models.py) requires `is_transform_active()` — parseable and passing the denylist — before calling a mapping active. `PartitionColumnFields.tsx` uses this frontend `isActive` to choose between the green "Filters on X will automatically apply..." message and the "No value transform is set" warning, so a transform that's non-bl
**Addressed** in `6113387c98` — `mappingIsActive` shares `transformCanPreview`'s conditions
### `superset/datasets/api.py`:2231
[thread](https://github.com/apache/superset/pull/43891#discussion_r4129728980) · sadpandajoe
> The response schema documents `sample_input`, `emitted_predicate`, `error`, and `valid`, but not `reason` — even though every invalid result this endpoint returns now includes one of `parse`, `validation`, `operator`, `engine`, or `unconfigured` (see `preview_partition_mapping` in `partition_mapping.py`), and the frontend's `PartitionMappingPreview` type reads and branches on it. Generated OpenAPI clients have no typed way to see this field. Could `reason`
**Addressed** in `6113387c98` — `reason` documented with its enum; spec regenerated
### `docs/admin_docs/configuration/partition-filter-mapping.mdx` *(outdated)*
[thread](https://github.com/apache/superset/pull/43891#discussion_r4129728988) · sadpandajoe
> This names the zero-argument `unix_timestamp()`, but the paragraph right above says that form is rejected at save time — the one that can actually be saved and used is `unix_timestamp(:value)`, which is the one whose result actually depends on session timezone. Could the warning name `unix_timestamp(:value)` instead, so it's clear which usable transform needs care?
**Addressed** in `6113387c98` — the docs name `unix_timestamp(:value)`
### `superset/connectors/sqla/partition_mapping.py`:1065
[thread](https://github.com/apache/superset/pull/43891#discussion_r4137611386) · sadpandajoe
> `mapping.mirrors(operator)` only rejects `TEMPORAL_RANGE` when the transform is *not* declared monotonic. When `is_monotonic=True`, a `TEMPORAL_RANGE` preview passes this guard, then falls into `value = sample_values[0]` (a single scalar, since only `IN` takes the list branch) and reaches `handle_comparison_filter(col, TEMPORAL_RANGE, value)`, which has no case for that operator and raises `ValueError` — a 500 with a valid transform and a monotonic declara
**Addressed** in `6113387c98` — `PREVIEWABLE_OPERATORS` excludes it, in both the request schema and the function
### `superset/connectors/sqla/partition_mapping.py` *(outdated)*
[thread](https://github.com/apache/superset/pull/43891#discussion_r4137611395) · sadpandajoe
> This query-time gate checks blank/placeholder/Jinja/parseable but not non-deterministic functions, while `is_transform_active()` (used for the UI's active/inactive indicator) also runs that check. `CreateDatasetCommand`/import do not validate the mapping at all, so an imported or pre-existing dataset can carry a transform like `rand() + 0*:value`: the editor reports it inactive, but this function still lets it reach the probe, so a chart query mirrors a fr
**Addressed** in `7951536198` — `_transform_is_usable` deleted; the query-time gate is `is_transform_active`
### `superset/connectors/sqla/partition_mapping.py`:612
[thread](https://github.com/apache/superset/pull/43891#discussion_r4137611403) · sadpandajoe
> Nothing here rejects a transform whose SELECT list has more than one expression (e.g. `lower(:value), :value`). For an `IN` filter with N distinct values, `build_probe_sql` compiles N pairs of columns into one row, but this only ever reads `row.iloc[0..len(distinct)-1]` — the first `len(distinct)` columns of the *first* value's own row, not one column per distinct value. For a 2-value `IN` filter that becomes both returned values coming from the first inpu
**Addressed** in `7951536198` — `is_parseable` requires one select expression; the probe guard is `!=`
### `superset/datasets/api.py`:217 *(outdated)*
[thread](https://github.com/apache/superset/pull/43891#discussion_r4137611417) · sadpandajoe
> `add` and `inc` aren't atomic together: if the key is about to expire, `add` can return `False` (key still present) but then expire before this `inc` runs. Redis's `INCR` on a now-missing key creates it fresh with no TTL, so the counter keeps incrementing but never expires again. Once it's past `limit`, `_consume_preview_rate_limit` returns `False` permanently for that user/dataset instead of resetting after `PREVIEW_RATE_LIMIT_WINDOW` — previews stay 429'
**Addressed** in `17f8f28b41` — same per-window key: a TTL-less counter can only affect its own window
### `superset/connectors/sqla/partition_mapping.py`:507 *(outdated)*
[thread](https://github.com/apache/superset/pull/43891#discussion_r4137611434) · sadpandajoe
> Only `:value` is bound as a parameter here — the rest of `transform` is raw SQL text that gets compiled and executed as-is, and nothing in `validate_transform`/`validate_partition_mapping` rejects a transform containing a subquery (only blank/Jinja/parseable/placeholder/non-determinism are checked). A user with dataset-editor access but no read access to another table could set a transform such as `(SELECT secret FROM protected_table LIMIT 1) || :value` an
**Addressed** in `17f8f28b41` — `validate_stored_expression` runs before the probe
### `superset/commands/dataset/update.py`:316 *(outdated)*
[thread](https://github.com/apache/superset/pull/43891#discussion_r4137611447) · sadpandajoe
> This runs before `DatasetDAO.clear_dangling_partition_mapping` (called later, from `update_columns` during `run()`), and validates the *current* `partition_mapped_column`/`partition_column` against the submitted column list. So an `override_columns=true` sync that legitimately drops the currently-mapped column fails validation with a blocking error before the cleanup this PR added ever gets a chance to run — exactly the "clobbered, blocked or orphaned" cas
**Addressed** in `0b4ba99bdc` — validation reads the post-cleanup mapping when a column payload is present
### `superset/connectors/sqla/partition_mapping.py` *(outdated)*
[thread](https://github.com/apache/superset/pull/43891#discussion_r4137611458) · sadpandajoe
> This builds a bare `SELECT <expr> AS v0, ...` with no `FROM`. Not every supported engine accepts a `FROM`-less `SELECT` — Oracle requires `FROM DUAL` (Superset's own Oracle engine spec already special-cases this elsewhere). On Oracle, a syntactically valid, correctly-declared transform would fail every probe, so the preview reports an engine error and the chart query path never prunes, even though the mapping is otherwise fine. Should this route through an
**Addressed** in `7951536198` — `select_without_from_suffix` on the engine spec
### `superset-frontend/src/components/Datasource/components/DatasourceEditor/DatasourceEditor.tsx`:1408
[thread](https://github.com/apache/superset/pull/43891#discussion_r4137611469) · sadpandajoe
> This only clears the transform on `resolveMappedColumn(datasource)` — whichever column is *currently* effective (the explicit override if set, else `main_dttm_col`) — then nulls `partition_mapped_column`. If an owner previously had an implicit mapping on `main_dttm_col` with its own transform, then explicitly overrode to a different column with a separate transform, clicking "Remove mapping" only clears the explicit column's transform. Once the override is
**Addressed** in `earlier pass` — `clearMappingTransforms` clears every column
### `superset/datasets/api.py`:2173 *(outdated)*
[thread](https://github.com/apache/superset/pull/43891#discussion_r4137611478) · sadpandajoe
> This new method isn't added to the class's `method_permission_name` mapping, so `@protect()` requires its own `can_partition_mapping_preview` permission rather than inheriting from `can_write`. A custom role that already has `can_write` on Dataset — enough to save a mapping via this same PUT-based flow — is denied when calling preview, unless an operator separately grants the new permission. Could `partition_mapping_preview` map to `write` in `method_permi
**Addressed** in `17f8f28b41` — mapped to `write`
### `superset/datasets/api.py`:2245 *(outdated)*
[thread](https://github.com/apache/superset/pull/43891#discussion_r4137611495) · sadpandajoe
> The 429 response here points at `#/components/responses/400` ("Bad request"), but a throttled caller gets a rate-limit response, not a bad-request one — and the endpoint's own editorship check can also return a 403, which isn't documented in this response list at all. A generated API client would show a throttled caller as having sent bad input, and wouldn't know a 403 is possible. Could the 429 reference the correct shared response and a 403 entry be adde
**Addressed** in `17f8f28b41` — 429 documented properly, and a 403 added
### `superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/utils.ts` *(outdated)*
[thread](https://github.com/apache/superset/pull/43891#discussion_r4137611508) · sadpandajoe
> Non-temporal columns always get sample values `['US', 'CA']` regardless of the mapped column's actual type. For an integer-typed mapped column with a transform like `CAST(:value AS INTEGER)`, these string samples fail to evaluate and preview reports a transform error, even though a real `IN (2025, 2026)` filter on that column would mirror successfully. Could the sample values be derived from the column's declared type instead of a temporal/non-temporal bin
**Addressed** in `6113387c98` — samples follow the column's declared type
### `superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/PartitionColumnFields.tsx` *(outdated)*
[thread](https://github.com/apache/superset/pull/43891#discussion_r4137611522) · sadpandajoe
> This navigates to `mappedColumn` — the column *currently* mapped — not a different one. When the effective mapped column is the implicit default datetime column and it also equals the partition column (the self-mapping state backend validation rejects), this link opens the partition column's own row, whose mapping section is defined to show nothing for the partition column itself. The one guided path meant to help an owner out of this state leads to a dead
**Addressed** in `6113387c98` — falls back to `suggestedMappedColumn` on a self-mapping
### `superset-frontend/src/components/Datasource/components/DatasourceEditor/DatasourceEditor.tsx` *(outdated)*
[thread](https://github.com/apache/superset/pull/43891#discussion_r4137611529) · sadpandajoe
> Clicking a "customize the value transform"-style link for the same column twice in a row (e.g. after manually collapsing that row) calls this with the same `columnName` both times. Nothing resets `columnToReveal` (or `columnSearchTerm`) to `null` when a row collapses, so the second call sets `setColumnToReveal(columnName)` to the value it already holds — React bails out of the state update, the consumer relying on `expandedColumnName={columnToReveal}` neve
**Addressed** in `6113387c98` — the reveal request carries a nonce — **no test**, see the commit message
### `superset/config.py` *(outdated)*
[thread](https://github.com/apache/superset/pull/43891#discussion_r4137611535) · sadpandajoe
> This says "no query consumer emits the mirrored predicate yet," but this PR wires `resolve_partition_mapping`/`build_mirrored_predicates` into the chart-query path (`superset/models/helpers.py`), so enabling the flag now does change query SQL, not just storage/validation. An operator enabling this flag on the strength of this description would be surprised that charts start mirroring filters immediately. Could the comment be updated to reflect that the que
**Addressed** in `7951536198` — flag description rewritten; `feature-flags.json` regenerated
## PR #43870 — Explore pruning indicator
*re-pointed at `master`; this is the surviving PR. 16 unresolved threads.*
### `superset-frontend/src/explore/components/controls/DateFilterControl/DateFilterLabel.tsx`:429
[thread](https://github.com/apache/superset/pull/43870#discussion_r3939218324) · codeant-ai-for-open-source, sadpandajoe
> Agreed—the standalone time control renders any active mapping even for `No filter` or a different temporal column, so the query has no matching partition predicate. Could this gate the glyph on an actual mapped time range?
**Addressed** in `earlier pass` — gated by `timeRangePartitionMapping`
### `superset-frontend/src/explore/components/PartitionPruningIndicator/index.tsx`:132
[thread](https://github.com/apache/superset/pull/43870#discussion_r3939838584) · sadpandajoe
> This labels every active mapped-column filter as mirrored, but the query path also rejects unsupported operators (and range filters for non-monotonic transforms). For example, a `country != 'US'` chip gets the glyph even though no partition predicate is emitted. Could this consume an applicability contract that includes the operator and monotonicity?
**Addressed** in `earlier pass` — `mirrorable_operators` gate in `isMirroredFilter`
### `superset-frontend/packages/superset-ui-chart-controls/src/shared-controls/sharedControls.tsx`:265
[thread](https://github.com/apache/superset/pull/43870#discussion_r3970149881) · sadpandajoe
> Changing the time range is handled by `SET_FIELD_VALUE`, which evaluates this mapper against the pre-action form data; and this control does not opt into render-time recalculation. After switching a mapped range to `No filter` (or the reverse), `partitionMapping` can therefore retain its old value and leave the glyph opposite the generated SQL. Could this opt into recalculation and add a field-update regression case?
**Addressed** in `earlier pass` — `shouldMapStateToProps` plus `validationDependencies`
### `superset/daos/dataset.py` *(outdated)*
[thread](https://github.com/apache/superset/pull/43870#discussion_r4129803967) · sadpandajoe
> This runs on every `DatasetDAO.update()` call, including one that only changes an unrelated field like `description` -- there's no check that `attributes` actually touches partition/mapping state. Any dataset that already has a `partition_value_transform` stored on a column other than the current mapped one (a state the client editor alone couldn't fully prevent before this PR) will have that value silently and permanently cleared the next time anything ab
**Addressed** in `1e132aefc9` — gated on `PARTITION_MAPPING_ATTRIBUTES`
### `superset/daos/dataset.py`:553
[thread](https://github.com/apache/superset/pull/43870#discussion_r4129803968) · sadpandajoe
> `model.columns` here is whatever was already materialized earlier in this same `update()` call by `_upsert_columns`/`_override_columns`, which insert new rows via `db.session.add(TableColumn(..., table_id=model.id))` rather than appending to that relationship collection -- so a column added and given `partition_value_transform` in the same request as this call is invisible to this loop, and its transform is never cleared. Since that's exactly the "stray tr
**Addressed** in `1e132aefc9` — `flush()` + `expire(model, ['columns'])` before the loop
### `superset-frontend/src/explore/components/PartitionPruningIndicator/index.tsx`:224
[thread](https://github.com/apache/superset/pull/43870#discussion_r4129803970) · sadpandajoe
> This can show the pruning glyph on a filter the query path does not actually mirror. Two concrete cases: (1) a filter with an applied time grain (drill-to-detail) is explicitly excluded from mirroring in `models/helpers.py` ("Mirroring it raw would keep only the bucket's first instant"), but `MirrorCandidateFilter` carries no grain information, so a grained equality filter is always treated as mirrored here; (2) an `IN` filter containing the `<NULL>` senti
**Addressed** in `1e132aefc9` — the grain rides on the candidate, and `<NULL>` is recognised
### `superset-frontend/packages/superset-ui-chart-controls/src/shared-controls/sharedControls.tsx`:251
[thread](https://github.com/apache/superset/pull/43870#discussion_r4129803977) · sadpandajoe
> `mirrorsMainDttm` doesn't check that a temporal column is even selected. The backend only collects this `always_filter_main_dttm` mirror inside the `if granularity:` branch (`models/helpers.py`), so with no granularity selected the query never adds it -- but here the glyph shows purely from `always_filter_main_dttm && main_dttm_col === mapping.mapped_column`, regardless of `formData.granularity_sqla`. Could this also require a selected granularity before m
**Addressed** in `1e132aefc9` — `mirrorsMainDttm` requires a selected granularity
### `superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/useDebouncedCommit.ts`:88
[thread](https://github.com/apache/superset/pull/43870#discussion_r4129803986) · sadpandajoe
> This can't tell an echo of its own last commit from a genuinely new external value, so it can still drop a keystroke: if `commit` fires and the resulting prop update (say "AB") arrives after the owner has already typed further ("ABC"), this resets `localValue` back to "AB", discarding the extra keystroke -- the next character then commits on top of the reverted text. The new round-trip test only re-syncs after typing has already finished, so this specific
**Addressed** in `1e132aefc9` — the last committed value is recorded; the test flushes with Enter mid-typing
### `superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/types.ts`:73
[thread](https://github.com/apache/superset/pull/43870#discussion_r4129803989) · sadpandajoe
> `field` is asserted in the tests but neither production consumer reads it -- `DatasourceEditor`'s validation maps straight to `.message`, and `PartitionMappingSection` renders `.message` without checking `.field`. Could this wire `field` into error placement at the named input, or drop it so it isn't carrying metadata nothing uses?
**Addressed** in `1e132aefc9` — wired into placement at both selects
### `superset-frontend/src/explore/components/PartitionPruningIndicator/index.tsx` *(outdated)*
[thread](https://github.com/apache/superset/pull/43870#discussion_r4137602283) · sadpandajoe
> `hasMirrorableValue` treats an empty string as not mirrorable (`comparator !== ''`), but the backend's mirror collector (`_collect_partition_mirror_filter` in `superset/models/helpers.py`) only excludes `None`, not `''`. A valid `column == ''` filter is mirrored server-side while Explore hides the indicator for it. Could this align with the backend's null-only exclusion?
**Addressed** in `1e132aefc9` — aligned with the backend; the test that pinned it the wrong way was flipped
### `superset-frontend/src/explore/components/PartitionPruningIndicator/index.tsx`:191
[thread](https://github.com/apache/superset/pull/43870#discussion_r4137602299) · sadpandajoe
> A virtual dataset's SQL can consume a filter via a Jinja `get_filters('col', remove_filter=True)` (or `get_time_filter(..., remove_filter=True)`) template call; the query builder then skips both the filter's own predicate and any partition mirror for that column entirely (`should_skip_filter` in `superset/models/helpers.py`). This function only looks at the filter's own shape, so it still shows the glyph for a filter on the mapped column that produces no S
**Left as a known limitation**, written down where the check lives: `removed_filters` is built during query generation and is not in `form_data`, so the browser cannot know. The glyph is advisory; "View query" is the authority.
### `superset/connectors/sqla/partition_mapping.py` *(outdated)*
[thread](https://github.com/apache/superset/pull/43870#discussion_r4137602310) · sadpandajoe
> This trusts `_transform_is_usable` as the gate for real query-time mirroring, but that function (below) doesn't call `find_non_deterministic_functions`, while `validate_transform` (used both for PUT-time validation and for `is_transform_active`, which drives the Explore indicator) treats a non-deterministic function as blocking. Since import and `CreateDatasetCommand` don't run `validate_partition_mapping`, a transform calling e.g. `NOW()` can reach the da
**Addressed** in `7951536198` — `_transform_is_usable` deleted; the query-time gate is `is_transform_active`
### `superset-frontend/packages/superset-ui-chart-controls/src/shared-controls/sharedControls.tsx` *(outdated)*
[thread](https://github.com/apache/superset/pull/43870#discussion_r4137602318) · sadpandajoe
> This checks `formData?.time_range === NO_TIME_RANGE`, but when `time_range` is simply absent from `form_data` (e.g. a legacy saved chart predating this control, or before defaults populate the state), the value is `undefined` rather than the sentinel, so this falls through to the mirrors-check below instead of returning null. Could a missing `time_range` be treated the same as `NO_TIME_RANGE` here?
**Addressed** in `1e132aefc9` — a missing `time_range` counts as `NO_TIME_RANGE`
### `superset-frontend/src/explore/components/PartitionPruningIndicator/index.tsx` *(outdated)*
[thread](https://github.com/apache/superset/pull/43870#discussion_r4137602324) · sadpandajoe
> The tooltip's explanation is reachable only by mouse hover: the icon sits in a non-focusable `<span>` with no accessible name, so a keyboard or screen-reader user has no way to discover why the glyph is there. Could this add a focusable target with an accessible label (e.g. an `aria-label` matching the tooltip text)?
**Addressed** in `1e132aefc9` — a text-variant `Button` with an `aria-label`
### `superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/useDebouncedCommit.ts`:54
[thread](https://github.com/apache/superset/pull/43870#discussion_r4137602330) · sadpandajoe
> This comment says the commit callback reads the column's monotonic flag to decide what to write, but `commit` here is just the plain `(next: string) => void` passed in by the caller -- this hook doesn't reference monotonicity anywhere. Looks like a leftover from an earlier, more specific version of this code; could this be corrected or removed?
**Addressed** in `1e132aefc9` — the stale claim is gone
### `superset/daos/dataset.py`:553
[thread](https://github.com/apache/superset/pull/43870#discussion_r4137602342) · sadpandajoe
> Concretely: `_upsert_columns` and `_override_columns` attach a brand-new column via `db.session.add(TableColumn(..., table_id=model.id))` rather than through the `columns` relationship, and both already read `model.columns` earlier in the same call to build their by-id/by-name maps. When that collection was loaded before the insert, the new row isn't reflected in it when this loop runs right after -- so a single request that both adds a column with a `part
**Addressed** in `1e132aefc9` — `flush()` + `expire(model, ['columns'])` before the loop
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4202018871
##########
docs/admin_docs/configuration/partition-filter-mapping.mdx:
##########
@@ -0,0 +1,298 @@
+---
+title: Partition Filter Mapping
+hide_title: true
+sidebar_position: 15
+version: 1
+---
+
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing,
+software distributed under the License is distributed on an
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+KIND, either express or implied. See the License for the
+specific language governing permissions and limitations
+under the License.
+-->
+
+# Partition Filter Mapping
+
+Tables on Hadoop-family engines are often partitioned on a *technical* column — an epoch
+integer, a lowercased region key — that no analyst would ever filter on. Unless a query
+carries a predicate on that column, the engine scans every partition.
+
+Partition filter mapping makes this a dataset setting instead of a per-chart chore. A
+dataset owner names the partition column, the business column whose filters should be
+mirrored onto it, and a value transform. Superset then appends an equivalent predicate on
+the partition column to every query. Chart authors change nothing; queries prune.
+
+:::caution Experimental
+This feature is behind the `PARTITION_FILTER_MAPPING` feature flag and is off by default.
+:::
+
+## Enabling it
+
+```python
+FEATURE_FLAGS = {
+ "PARTITION_FILTER_MAPPING": True,
+}
+```
+
+Configure it as a **static boolean**. `FEATURE_FLAGS` also accepts per-request callables,
Review Comment:
`FEATURE_FLAGS` values aren't evaluated per request: `FeatureFlagManager` returns configured values unchanged unless `GET_FEATURE_FLAGS_FUNC` / `IS_FEATURE_ENABLED_FUNC` is set. An operator who follows this and sets the flag to `lambda: False` gets a truthy function object, not `False`. Could this point at those two callbacks as the dynamic mechanisms and say they must return the same value for every user?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2395 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+#: Returned by `ExploreMixin.mirror_probe_request` for a filter no mirror can
+#: stand in for: one the engine compares more coarsely than the value carries, a
+#: value it cannot render as a literal, or an ``IN`` list with a member of
+#: either kind. A sentinel rather than `None`, because `None` is a filter value
+#: in its own right.
+#:
+#: Lives here rather than beside that method so the preview can read it too:
+#: `superset.models.helpers` imports this module, so the sentinel can only cross
+#: the boundary in this direction. Both callers have to recognise the same
+#: object -- a preview that answered "valid" for a request the chart path
+#: declines is the drift this is here to prevent.
+UNMIRRORABLE = object()
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error(
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the probe
+ uninspected -- string elements are escaped by the dialect's own literal
+ processor. `probe_sql_is_evaluable` then re-reads the finished query, which
+ is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ else:
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ rendered = _compile_literal(clause, dialect)
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Four things have to hold, and all four are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if not isinstance(statement, SQLStatement):
+ # A dialect whose statements this gate cannot take apart -- KQL -- gets
+ # no probe rather than an unchecked one. It never had one: the clause
+ # inspection below is implemented for SQL statements only, and the
+ # alternative to declining here is an `AttributeError` that `_probe`
+ # swallows into the same outcome, less legibly.
+ return False
+ if statement.has_subquery():
+ return False
+ if statement.get_clause_names() - {"from"}:
+ return False
+ if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+ """
+ The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+ Parsed rather than string-compared so that the comparison in
+ `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+ not parse answers ``None``, which no statement carrying a FROM can match --
+ the probe then declines, which is the right way for an unreadable engine
+ constant to fail.
+ """
+ if not from_suffix.strip():
+ return None
+ try:
+ return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+ except SupersetParseError:
+ return None
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=values is not None and not any(value is None for value in values),
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ from_suffix = database.db_engine_spec.select_without_from_suffix
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ from_suffix,
+ )
+ if not probe_sql_is_evaluable(
+ sql, database.backend, len(distinct), from_suffix
+ ):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
Review Comment:
The shape gates here inspect sqlglot's parse of the SQL, but this executes the original text, and sqlglot treats a MySQL executable comment as plain comment data: `1 /*!50000 + (SELECT secret_number FROM vault LIMIT 1) */` parses with no sub-query, while MySQL runs the hidden `SELECT`. An owner with write access to a dataset but no SQL Lab or access to `vault` could put `(:value /*!50000 + (SELECT secret_number FROM vault LIMIT 1) */)` in a transform, call the preview endpoint, and read `secret_number + 1` back in `emitted_predicate`, with no RLS applied to the hidden sub-query.
Could the transform/probe validation reject `/*!` comments (or execute exactly the normalized SQL that was inspected) so the gates and the engine see the same statement?
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/usePartitionMappingPreview.ts:
##########
@@ -0,0 +1,153 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { SupersetClient, getClientErrorObject } from '@superset-ui/core';
+import { t } from '@apache-superset/core/translation';
+import { useDebounceValue } from 'src/hooks/useDebounceValue';
+import type { PartitionMappingPreview } from './types';
+import { transformCanPreview } from './utils';
+
+interface PreviewRequest {
+ datasetId?: number;
+ mappedColumn: string;
+ partitionColumn: string;
+ valueTransform: string;
+ sampleValues: string[];
+ operator: string;
+ isMonotonic: boolean;
+ /** Skip entirely when the section isn't showing a mapping. */
+ enabled: boolean;
+}
+
+/**
+ * Preview the predicate a transform would emit, debounced.
+ *
+ * The endpoint fires a real warehouse query, so the transform is debounced
+ * before it leaves the browser, and a transform that cannot work is not sent at
+ * all. Neither is a guard -- the server keeps a per-user, per-dataset budget of
+ * its own, and remains the authority on whether a transform is usable. The
+ * point is that a half-written transform should not spend that budget and leave
+ * none for the finished one.
+ */
+export function usePartitionMappingPreview({
+ datasetId,
+ mappedColumn,
+ partitionColumn,
+ valueTransform,
+ sampleValues,
+ operator,
+ isMonotonic,
+ enabled,
+}: PreviewRequest) {
+ const [preview, setPreview] = useState<PartitionMappingPreview | null>(null);
+ const [loading, setLoading] = useState(false);
+ // Which request the displayed state belongs to. `AbortController` alone is
+ // not enough: aborting settles nothing, so a handler still runs and has to
+ // ask whether it is still the current one. See the effect below.
+ const latestRequest = useRef(0);
+
+ const debouncedTransform = useDebounceValue(valueTransform, 500);
+ // `sampleValues` is a fresh array on every render, so depending on it
+ // directly would refire the effect -- and spend the preview budget -- on
+ // every keystroke elsewhere in the row. Depend on its serialized form and
+ // hand the effect a value whose identity tracks that same key.
+ const sampleKey = JSON.stringify(sampleValues);
+ const samples = useMemo<string[]>(() => JSON.parse(sampleKey), [sampleKey]);
+
+ useEffect(() => {
+ const transform = debouncedTransform?.trim();
+ // Claimed before the early return as well, so a request already in flight
+ // cannot come back and overwrite what this run decided.
+ latestRequest.current += 1;
+ const requestId = latestRequest.current;
+
+ if (
+ !enabled ||
+ !datasetId ||
+ !mappedColumn ||
+ !transformCanPreview(transform, mappedColumn, partitionColumn)
+ ) {
+ setPreview(null);
+ // The spinner belongs to a request this run has just superseded. Its own
+ // handlers see the abort and stop short of clearing it, so clearing it
+ // here is the only thing that does -- otherwise clearing the transform
+ // mid-flight left the panel spinning for good.
+ setLoading(false);
+ return undefined;
+ }
+
+ const controller = new AbortController();
+ setLoading(true);
+
+ SupersetClient.post({
+ endpoint: `/api/v1/dataset/${datasetId}/partition_mapping/preview/`,
+ jsonPayload: {
+ mapped_column: mappedColumn,
+ // The candidate, not the saved one: the owner is previewing a mapping
+ // they have not committed yet.
+ partition_column: partitionColumn,
+ value_transform: transform,
+ sample_values: samples,
+ operator,
+ is_monotonic: isMonotonic,
+ },
+ signal: controller.signal,
+ })
+ .then(({ json }) => {
+ // This hits a live warehouse query, so responses can arrive out of
+ // order. Without this an older one overwrites the current preview and
+ // reports "Valid" for a transform the input no longer holds.
+ if (requestId !== latestRequest.current) {
+ return;
+ }
+ setPreview(json.result as PartitionMappingPreview);
+ })
+ .catch(async error => {
+ if (requestId !== latestRequest.current) {
+ return;
+ }
+ const clientError = await getClientErrorObject(error);
+ setPreview({
+ valid: false,
+ error:
+ clientError.message ||
Review Comment:
A transform longer than 1,024 characters that contains `:value` makes the preview schema return HTTP 400 with an object-valued `message` (`{value_transform: [...]}`). `getClientErrorObject` keeps that object in `message` and puts the normalized text in `error`, but this prefers `message`, so `PartitionMappingSection` passes an object to `Alert description` and React throws "Objects are not valid as a React child" instead of showing the validation error.
Could this prefer `clientError.error` (or only use `message` when it is a string)?
##########
UPDATING.md:
##########
@@ -24,6 +24,24 @@ assists people when migrating to a new version.
## Next
+- Refreshing a dataset's columns from its source -- the "Sync columns from
+ source" button, and a `PUT /api/v1/dataset/<id>?override_columns=true` --
+ no longer resets **Is dimension** and **Is filterable** on columns that
+ already exist. Those two flags were set unconditionally on every column the
+ source reported, so a save that synced columns reverted whatever the dataset
+ owner had chosen for them. A newly discovered column still arrives with both
+ enabled. A deployment that relied on a resync to restore those defaults has
+ to set them explicitly.
+
+- `DISALLOWED_SQL_FUNCTIONS` now names the whole PostgreSQL XML family. Four
Review Comment:
The note lists only the four newly denied XML functions, but this PR also adds `ts_rewrite` and `ts_stat` to the default PostgreSQL `DISALLOWED_SQL_FUNCTIONS` (`superset/config.py`). A deployment that runs `ts_stat(...)` full-text statistics in SQL Lab will see those queries start failing after upgrade, even with `PARTITION_FILTER_MAPPING` off, with no warning here. Could the note name both functions too?
##########
tests/unit_tests/datasets/partition_mapping_preview_test.py:
##########
@@ -0,0 +1,1071 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+The partition mapping preview endpoint.
+
+This route fires a real warehouse query from a text input in the dataset
+editor, so the order of its guards is the point: parse and denylist checks run
+*before* anything reaches the engine, which is what keeps a half-typed
+expression from costing a query at all.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+from unittest.mock import MagicMock, patch
+
+import pytest
+from flask import Flask
+from sqlalchemy.orm.session import Session
+
+from superset import db
+
+PROBE = "superset.connectors.sqla.partition_mapping.evaluate_transform"
+
+
+@pytest.fixture(autouse=True)
+def enable_partition_filter_mapping(app: Flask) -> Any:
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = True
+ yield
+ del app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"]
+
+
+@pytest.fixture(autouse=True)
+def real_cache(app: Flask) -> Any:
+ """
+ The test app runs a null cache, which would make the rate limiter a no-op.
+ """
+ from flask_caching import Cache
+
+ from superset.extensions import cache_manager
+
+ cache = Cache(config={"CACHE_TYPE": "SimpleCache", "CACHE_DEFAULT_TIMEOUT": 300})
+ cache.init_app(app)
+ original = cache_manager._cache # noqa: SLF001
+ cache_manager._cache = cache # noqa: SLF001
+ yield
+ cache_manager._cache = original # noqa: SLF001
+
+
+@pytest.fixture(autouse=True)
+def allow_editorship(mocker: Any) -> Any:
Review Comment:
Every preview endpoint test runs with `raise_for_editorship` patched out here, and `test_preview_is_authorized_as_a_write` only checks permission-map metadata, so deleting the `raise_for_editorship(dataset)` call in the preview route leaves the suite green. Could we add one POST where a user who can read but doesn't own/edit the dataset (real editorship check, not the autouse mock) gets a 403 and `get_df` is never called?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2395 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+#: Returned by `ExploreMixin.mirror_probe_request` for a filter no mirror can
+#: stand in for: one the engine compares more coarsely than the value carries, a
+#: value it cannot render as a literal, or an ``IN`` list with a member of
+#: either kind. A sentinel rather than `None`, because `None` is a filter value
+#: in its own right.
+#:
+#: Lives here rather than beside that method so the preview can read it too:
+#: `superset.models.helpers` imports this module, so the sentinel can only cross
+#: the boundary in this direction. Both callers have to recognise the same
+#: object -- a preview that answered "valid" for a request the chart path
+#: declines is the drift this is here to prevent.
+UNMIRRORABLE = object()
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error(
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the probe
+ uninspected -- string elements are escaped by the dialect's own literal
+ processor. `probe_sql_is_evaluable` then re-reads the finished query, which
+ is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ else:
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ rendered = _compile_literal(clause, dialect)
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Four things have to hold, and all four are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if not isinstance(statement, SQLStatement):
+ # A dialect whose statements this gate cannot take apart -- KQL -- gets
+ # no probe rather than an unchecked one. It never had one: the clause
+ # inspection below is implemented for SQL statements only, and the
+ # alternative to declining here is an `AttributeError` that `_probe`
+ # swallows into the same outcome, less legibly.
+ return False
+ if statement.has_subquery():
+ return False
+ if statement.get_clause_names() - {"from"}:
+ return False
+ if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+ """
+ The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+ Parsed rather than string-compared so that the comparison in
+ `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+ not parse answers ``None``, which no statement carrying a FROM can match --
+ the probe then declines, which is the right way for an unreadable engine
+ constant to fail.
+ """
+ if not from_suffix.strip():
+ return None
+ try:
+ return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+ except SupersetParseError:
+ return None
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=values is not None and not any(value is None for value in values),
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ from_suffix = database.db_engine_spec.select_without_from_suffix
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ from_suffix,
+ )
+ if not probe_sql_is_evaluable(
+ sql, database.backend, len(distinct), from_suffix
+ ):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _mirror_verdict_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str:
+ """
+ `_probe_cache_key` without the values.
+
+ Whether a transform can be evaluated at all is a property of the transform
+ and the connection, not of the filter that happened to be probing it, so
+ one chart's answer settles the question for the next one.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_verdict:{digest}"
+
+
+def record_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ *,
+ mirrors: bool,
+) -> None:
+ """
+ Remember whether this transform produced a mirror, for the UI to read.
+
+ Advisory only. Nothing in the query path consults it: a probe that failed
+ once is retried on the next chart exactly as it is today, because declining
+ to prune for a whole cache timeout over one transient engine blip is the
+ trade `evaluate_transform` deliberately refuses -- see the comment where it
+ declines to cache a failure.
+
+ What this is for is the *claim*. `is_transform_active` parses the transform
+ and no more, so a transform the database rejects -- a misspelled function
+ is the common case -- is "active", and the editor's banner and Explore's
+ pruning glyph promise a speed-up that never happens. A promise is exactly
+ the thing that may be withheld on one bad answer and restored on a good
+ one, which is why this is a separate entry from the probe's own results
+ rather than a relaxation of that rule.
+
+ Written by `_run_probe`, so the preview endpoint -- which shares the
+ evaluator -- settles the question before the owner has even saved.
+ """
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(
+ _mirror_verdict_cache_key(database, catalog, schema, transform),
+ mirrors,
+ timeout=timeout,
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform verdict", exc_info=True)
+
+
+def known_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> bool | None:
+ """
+ The last verdict `record_mirror_verdict` stored, or `None` if there is none.
+
+ `None` is the honest answer on a cold cache and is deliberately not `False`:
+ reporting a working mapping as broken until something probes it would
+ trade one wrong claim for another. The alternative -- probing from the
+ read side -- would put a warehouse round trip on every Explore and
+ dashboard load, and a failing transform is not cached at all, so it would
+ be a round trip every single time.
+ """
+ try:
+ verdict = cache_manager.cache.get(
+ _mirror_verdict_cache_key(database, catalog, schema, transform)
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return verdict if isinstance(verdict, bool) else None
+
+
+def _compile_literal(element: Any, dialect: Dialect | None) -> str:
+ """
+ Compile with inline literals, undoing the paramstyle's percent doubling.
+
+ Both ``TextClause`` and literal compilation run the dialect's
+ ``post_process_text``, which doubles every ``%`` whenever the identifier
+ preparer asks it to -- true for MySQL and Postgres and for every spec
+ inheriting their paramstyle. That doubling exists so a later DBAPI
+ parameter-interpolation pass can undo it, and the probe has no such pass:
+ it executes with no bound parameters at all. So a transform of
+ ``date_format(:value, '%Y%m%d')`` reaches the warehouse asking for the
+ literal string ``%%Y%%m%%d``, the probe returns that instead of a date, and
+ the mirrored predicate drops every row the filter keeps.
+
+ The same normalization ``Database.compile_sqla_query`` applies for the same
+ reason. ``_double_percents`` is private and not guaranteed on a third-party
+ dialect, hence the ``getattr`` default.
+ """
+ compiled = str(
+ element.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
+ )
+ if dialect is not None and getattr(
+ dialect.identifier_preparer, "_double_percents", False
+ ):
+ compiled = compiled.replace("%%", "%")
+ return compiled
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be *asked* to stand in for itself, and the transform
+ cannot carry Jinja or call a non-deterministic function. Tier 2
+ (``blocking=False``) is everything that merely leaves the mapping inactive
+ -- including a self-mapping nobody asked for, where the partition column
+ merely happens to be the default datetime column.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column == partition_column:
+ # Asked for explicitly, so report it as the mistake it is.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+ elif not partition_mapped_column and main_dttm_col == partition_column:
+ # Resolved onto itself only because the default datetime column happens
+ # to be the partition column -- a state metadata sync could produce
+ # without anyone asking for it. The mapping is inert either way, since
+ # `resolve_partition_mapping` bails out on it, so this reports and lets
+ # the write through: blocking here means a dataset already in the state
+ # can never be saved again, not even to change its description, and
+ # there is no field whose edit would clear the error first.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "%(name)s is both the partition column and the default "
+ "datetime column, so the mapping points at itself and "
+ "stays inactive. Set a mapped column override, or change "
+ "the default datetime column.",
+ name=partition_column,
+ ),
+ blocking=False,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_bare_expression(transform, engine):
+ # Blocking, and deliberately placed in `validate_transform` rather than
+ # only at the probe: one issue here closes the PUT, the importer, the
+ # query-time gate through `is_transform_active`, the Explore indicator's
+ # active verdict and the preview endpoint, all of which already consult
+ # this function.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform must be a single SQL expression. It "
+ "cannot carry a FROM, WHERE, GROUP BY or any other clause, "
+ "and it cannot contain a sub-query."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not contains_value_placeholder(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform must contain the :value placeholder, "
+ "which stands for the filter value being mirrored."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not placeholder_is_executable(transform, engine):
+ # Blocking, and for the same reason the shape gate above is: this is
+ # the function the PUT, the importer, `is_transform_active`, the
+ # Explore indicator and the preview all consult, so one issue here
+ # closes every door at once. A placeholder inside a string literal is
+ # a sub-query the engine will run once a filter value closes the quote;
+ # one inside a comment silently eats the probe's own alias.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The :value placeholder must appear where the engine will "
+ "evaluate it. It cannot sit inside a string literal or a "
+ "comment."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if functions := find_non_deterministic_functions(transform, engine):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform calls %(functions)s, whose result "
+ "depends on when and where it runs. The transform is "
+ "evaluated in a separate session and the result is cached, "
+ "so the emitted predicate would freeze a snapshot of that "
+ "moment.",
+ functions=", ".join(sorted(functions)),
+ ),
+ blocking=True,
+ )
+ ]
+
+ return []
+
+
+@lru_cache(maxsize=LRU_CACHE_MAX_SIZE)
+def is_transform_active(transform: str | None, engine: str) -> bool:
+ """
+ Whether Superset will mirror filters through this transform.
+
+ `validate_transform` with the messages discarded, so the Explore indicator
+ cannot advertise a mapping the save path recorded as inactive. Anything
+ cheaper here would be a second, weaker statement of the same rule, free to
+ drift from the one the save path applies.
+
+ Blocking issues count too. Jinja and non-deterministic transforms are
+ rejected on PUT, but `CreateDatasetCommand` and import do not validate the
+ mapping, so one can still reach the database -- and it would never mirror a
+ filter either.
+
+ Memoized because `partition_filter_mapping_summary` is serialized on every
+ Explore and dashboard load and this parses the transform. The key is
+ everything the answer depends on: `validate_transform` reads no session, no
+ locale and no config beyond `SQL_MAX_PARSE_LENGTH`, which bounds the parser
+ rather than changing a verdict within that bound.
+ """
+ return not validate_transform(transform, engine)
+
+
+def preview_partition_mapping( # pylint: disable=too-many-return-statements
+ datasource: SqlaTable,
+ *,
+ mapped_column: str,
+ value_transform: str | None,
+ sample_values: list[str],
+ operator: FilterOperator = FilterOperator.EQUALS,
+ is_monotonic: bool = False,
+ partition_column: str | None = None,
+) -> dict[str, Any]:
+ """
+ Evaluate a candidate mapping and describe the predicate it would emit.
+
+ Shares the evaluator -- and therefore the probe cache -- with the query
+ path, so preview and runtime cannot drift and a previewed transform warms
+ the chart path for free. The predicate itself comes from
+ `build_mirrored_predicates`, the same builder the query path uses, so
+ operator shapes cannot drift either: what the panel shows is what a chart
+ would emit.
+
+ Validation runs first and the engine second: a half-typed transform is by
+ definition unparseable, so most of what a text input produces costs zero
+ queries.
+
+ Every part of the mapping is taken from the request rather than the stored
+ dataset. The editor previews while the owner is still editing -- a mapping
+ that has to be saved before it can be checked is not a preview.
+ """
+ partition_column = partition_column or datasource.partition_column
+ if not partition_column:
+ return {
+ "valid": False,
+ "reason": "unconfigured",
+ "error": _("No partition column is set."),
+ }
+
+ columns_by_name = {str(column.column_name): column for column in datasource.columns}
+ if mapped_column not in columns_by_name:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _("%(name)s is not a column on this dataset.", name=mapped_column),
+ }
+
+ # The bail-out `resolve_partition_mapping` makes at query time, and that
+ # `partition_filter_mapping_summary` repeats for the Explore indicator.
+ # Without it here, preview reports a valid emitted predicate for a mapping
+ # no chart will ever mirror -- the one answer a preview panel must not give.
+ if has_active_advanced_data_type(columns_by_name[mapped_column]):
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _(
+ "%(name)s has an advanced data type, so its filters are "
+ "translated into their own predicate shape and cannot be "
+ "mirrored onto the partition column.",
+ name=mapped_column,
+ ),
+ }
+
+ engine = datasource.database.backend
+ for issue in validate_partition_mapping(
+ column_names=set(columns_by_name),
+ partition_column=str(partition_column),
+ partition_mapped_column=mapped_column,
+ main_dttm_col=datasource.main_dttm_col,
+ transform=value_transform,
+ engine=engine,
+ ):
+ return {
+ "valid": False,
+ # The parse failure is the one an owner sees constantly, and it is
+ # the only one the mockup gives its own headline to.
+ "reason": (
+ "parse"
+ if issue.field == "partition_value_transform"
+ and not is_parseable(value_transform, engine)
+ else "validation"
+ ),
+ "error": str(issue.message),
+ }
+
+ # The policy every other stored expression goes through. The save path
+ # applies it in `UpdateDatasetCommand._validate_partition_mapping`, but
+ # preview evaluates a candidate transform that has not been saved, so
+ # without this the gate had a door around it. See
+ # `stored_expression_error` for what is being kept out and why.
+ if reason := stored_expression_error(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ cast(str, value_transform),
+ ):
+ return {"valid": False, "reason": "validation", "error": reason}
+
+ mapping = PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=mapped_column,
+ value_transform=cast(str, value_transform),
+ is_monotonic=is_monotonic,
+ equality_is_safe=equality_mirrors_safely(
+ columns_by_name[mapped_column], datasource.database.db_engine_spec
+ ),
+ )
+ sample_input = _render_sample_input(
+ datasource, mapped_column, operator, sample_values
+ )
+
+ if operator not in PREVIEWABLE_OPERATORS:
+ # Checked before `mirrors`, which lets `TEMPORAL_RANGE` through when the
+ # transform is declared monotonic -- and the single sample value would
+ # then reach `handle_comparison_filter`, which has no case for a range
+ # and raises. The request schema rejects it too; this keeps the function
+ # honest for any other caller.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is mirrored as a pair of bounds, which "
+ "a preview of a single value cannot describe.",
+ operator=operator.value,
+ ),
+ }
+
+ if not mapping.mirrors(operator):
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is only mirrored when the transform "
+ "preserves ordering, which this one is not declared to do.",
+ operator=operator.value,
+ ),
+ }
+
+ return _preview_probe(
+ datasource,
+ mapping,
+ columns_by_name[mapped_column],
+ operator,
+ sample_values,
+ sample_input,
+ )
+
+
+def _preview_probe(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ mapped_col: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+ sample_input: str,
+) -> dict[str, Any]:
+ """
+ The half of a preview that needs the warehouse.
+
+ Split out from `preview_partition_mapping` so that the gates which answer
+ from the stored mapping alone stay readable as the single run of guard
+ clauses they are. Everything here has either run a query or decided not to.
+ """
+ value = datasource.mirror_probe_request(
+ operator,
+ _probe_input(datasource, mapped_col, operator, sample_values),
+ mapped_col,
+ )
+ if value is UNMIRRORABLE:
+ # The same step the chart path applies, so the preview cannot promise a
+ # mirror the query declines. Its own reason: the transform is fine and
+ # the engine evaluates it, the filter just carries more of the value
+ # than the engine compares on this column -- which is the column's type
+ # talking, not a broken expression.
+ return {
+ "valid": False,
+ "reason": "resolution",
+ "sample_input": sample_input,
+ "error": _(
+ "This engine compares less of a %(operator)s value on "
+ "%(column)s than the filter carries, so there is no mirror a "
+ "predicate on the partition column could stand in for. Map a "
+ "column the engine compares in full to mirror this operator.",
+ operator=operator.value,
+ column=mapped_col.column_name,
+ ),
+ }
+ errors: list[str] = []
+ type_errors: list[str] = []
+ predicates = build_mirrored_predicates(
+ datasource,
+ mapping,
+ [(operator, value)],
+ errors=errors,
+ type_errors=type_errors,
+ )
+ if type_errors:
+ # Its own reason, because "the database would not evaluate this" and
+ # "it evaluated and answered with the wrong kind of thing" are
+ # different problems with different fixes, and the owner is the only
+ # one who can tell which transform they meant to write.
+ return {
+ "valid": False,
+ "reason": "type",
+ "sample_input": sample_input,
+ "error": type_errors[0],
+ }
+ if not predicates:
+ return {
+ "valid": False,
+ "reason": "engine",
+ "sample_input": sample_input,
+ "error": (
+ _(
+ "The transform could not be evaluated against the "
+ "database: %(reason)s",
+ reason=errors[0],
+ )
+ if errors
+ else _("The transform could not be evaluated against the database.")
+ ),
+ }
+
+ return {
+ "valid": True,
+ "sample_input": sample_input,
+ "emitted_predicate": _render_predicate(datasource, predicates[0]),
+ }
+
+
+def _probe_input(
+ datasource: SqlaTable,
+ column: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+) -> Any:
+ """
+ The sample values as the query path would bind them.
+
+ The request carries samples as strings, and the probe is keyed on exactly
+ what it is handed, so passing them through raw asks the engine a different
+ question from the one a chart asks. A sample of ``2025`` on a numeric
+ column has to arrive as the integer the chart compares: under a transform
+ of ``typeof(:value)`` the raw string previewed ``'text'`` where the chart
+ emitted ``'integer'``. And because `_probe_cache_key` keys on each value's
+ ``repr``, the two also missed each other's cache entirely -- so the "a
+ previewed transform warms the chart path for free" claim in
+ `preview_partition_mapping`'s docstring did not actually hold.
+
+ Coerced by `filter_values_handler`, the same function the query path uses,
+ rather than by a second implementation of the same rules. Everything the
+ query path then does to the coerced value -- rendering an expression as a
+ literal, widening a bound, declining a comparison the engine resolves too
+ coarsely -- is `ExploreMixin.mirror_probe_request`'s, and the caller hands
+ this result straight to it.
+
+ Ranges are not previewable (see `PREVIEWABLE_OPERATORS`), so the bound
+ conversion `_collect_partition_mirror_range` applies -- a ``datetime`` into
+ the column's stored representation -- has no counterpart here.
+
+ :returns: `UNMIRRORABLE` where the samples cannot be coerced at all
+ """
+ is_list = operator == FilterOperator.IN
+ column_spec = datasource.db_engine_spec.get_column_spec(native_type=column.type)
+ handled = datasource.filter_values_handler(
+ # `list[str]` is not a `list[FilterValue]` to mypy, invariantly, even
+ # though every `str` is a `FilterValue`.
+ values=cast(FilterValues, sample_values if is_list else sample_values[0]),
+ operator=operator,
+ target_generic_type=(
+ column_spec.generic_type if column_spec else utils.GenericDataType.STRING
+ ),
+ target_native_type=column.type,
+ is_list_target=is_list,
+ db_engine_spec=datasource.db_engine_spec,
+ db_extra=datasource.db_extra,
+ )
+ # No `ColumnElement` conversion here: an epoch-milliseconds sample comes back
+ # as engine SQL rather than a value, and `mirror_probe_request` renders it --
+ # the same step, on the same values, as for a chart filter.
+ return handled
+
+
+def _render_sample_input(
+ datasource: SqlaTable,
+ mapped_column: str,
+ operator: FilterOperator,
+ values: list[str],
+) -> str:
+ """
+ The filter being previewed, written the way an owner would read it.
+
+ Display-only -- it is never executed -- but it is still read as SQL, so the
+ column is quoted and the values are rendered by the dialect rather than
+ concatenated raw. A column named ``order date`` would otherwise come out as
+ two bare words.
+ """
+ quoted = datasource.quote_identifier(mapped_column)
+ if operator == FilterOperator.IN:
+ rendered = ", ".join(
+ _render_literal(datasource.database, value) for value in values
+ )
+ return f"{quoted} IN ({rendered})"
+ return (
+ f"{quoted} {operator.value} {_render_literal(datasource.database, values[0])}"
+ )
+
+
+def _render_predicate(datasource: SqlaTable, predicate: ColumnElement[Any]) -> str:
+ """
+ Compile a mirrored predicate to the text a reader would see in View query.
+
+ Every value in it is a probed constant by this point, so ``literal_binds``
+ renders the same literals the chart query carries.
+ """
+ return _compile_literal(predicate, _dialect_for(datasource.database)).replace(
+ "\n", " "
+ )
+
+
+def _render_literal(database: Database, value: Any) -> str:
+ """
+ Render a value the way it appears in the generated SQL.
+
+ Compiled by the dialect rather than formatted by hand. `str()` would render
+ a NULL as the Python repr `None` and leave a date unquoted, neither of which
+ is SQL, and hand-rolled quote-doubling would only ever have been right for
+ strings.
+ """
+ return _compile_literal(sa.literal(value), _dialect_for(database))
+
+
+def build_mirrored_predicates(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ requests: list[tuple[FilterOperator, Any]],
+ *,
+ errors: list[str] | None = None,
+ type_errors: list[str] | None = None,
+) -> list[ColumnElement[Any]]:
+ """
+ Turn collected ``(operator, value)`` mirror requests into predicates.
+
+ ``requests`` is expected to be deduplicated by the caller. Every value is
+ resolved in a single probe round trip -- one per chart query at most -- then
+ emitted as a literal constant, so "View query" shows the reader an ordinary
+ ``WHERE`` clause rather than an inline expression.
+
+ A strict bound is emitted non-strictly; see `mirror_operator`. That happens
+ here, at the one point where a ``FilterOperator`` becomes SQL, rather than
+ at the collection sites in `ExploreMixin`: the preview endpoint calls this
+ directly, so this is what keeps the predicate the editor shows an owner and
+ the predicate the chart carries from disagreeing.
+
+ :param errors: optional sink; see `evaluate_transform`.
+ :param type_errors: optional sink for a probe result the partition column
+ cannot hold -- see `probed_value_type_error`. Separate from ``errors``
+ because the two say different things to an owner: that one is "the
+ database would not evaluate this", and this one is "it evaluated, and
+ answered with the wrong kind of thing".
+ """
+ if not requests:
+ return []
+
+ partition_column = next(
+ (
+ column
+ for column in datasource.columns
+ if column.column_name == mapping.partition_column
+ ),
+ None,
+ )
+ if partition_column is None:
+ return []
+
+ # Flatten every value that needs probing into one list, remembering how many
+ # each request consumed so the results can be handed back out.
+ flat: list[Any] = []
+ spans: list[tuple[FilterOperator, int, int]] = []
+ for operator, value in requests:
+ values = list(value) if operator == FilterOperator.IN else [value]
+ spans.append((operator, len(flat), len(values)))
+ flat.extend(values)
+
+ evaluated = evaluate_transform(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ mapping.value_transform,
+ flat,
+ errors=errors,
+ )
+ if evaluated is None:
+ return []
+
+ if not _bounds_are_ordered(evaluated, spans):
+ return []
+
+ # Declining here is the last chance to decline at all: once these
+ # predicates are in the statement, a value the partition column cannot
+ # hold fails the whole chart rather than its pruning.
+ if reason := probed_value_type_error(partition_column, evaluated):
+ logger.warning(
+ "Partition transform returned a value the partition column cannot "
+ "hold; queries will not prune: %s",
+ reason,
+ )
+ if type_errors is not None:
+ type_errors.append(reason)
+ record_mirror_verdict(
Review Comment:
This records a dataset-specific outcome (this partition column can't hold the probed type) under `_mirror_verdict_cache_key`, which is keyed only by database/catalog/schema/transform. With a configured cache: dataset A mirrors `CAST(:value AS text)` onto a text partition column and is cached as evaluable; an owner previews the same transform against a numeric partition column in dataset B, this branch writes `mirrors=False`, and reloading A now reports `evaluable = false` and hides its pruning indicator until the entry expires (a cache hit on A's probe never rewrites the verdict).
Could the type-mismatch decline stay out of the shared verdict, or could the verdict key include the partition column's type?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "hughhhh (via GitHub)" <gi...@apache.org>.
hughhhh merged PR #43870:
URL: https://github.com/apache/superset/pull/43870
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4190076981
##########
superset/config.py:
##########
@@ -2462,15 +2480,23 @@ def engine_context_manager( # pylint: disable=unused-argument
"lo_truncate",
"lo_truncate64",
"lo_unlink",
- # XML functions that can execute SQL
+ # XML functions that can execute SQL. These read tables with no FROM
+ # clause and no sub-query of their own, so a gate that reasons about
+ # table references alone cannot see them -- the whole family has to be
+ # named here. All four shapes, for each of database / schema / table /
+ # query.
"database_to_xml",
"database_to_xmlschema",
+ "database_to_xml_and_xmlschema",
+ "schema_to_xml",
+ "schema_to_xmlschema",
+ "schema_to_xml_and_xmlschema",
"query_to_xml",
"query_to_xmlschema",
- "table_to_xml",
- "table_to_xml_and_xmlschema",
"query_to_xml_and_xmlschema",
+ "table_to_xml",
"table_to_xmlschema",
+ "table_to_xml_and_xmlschema",
Review Comment:
`ts_stat('select …')` and `ts_rewrite(q, 'select …')` also run their text argument as a query with no FROM or sub-query; `stored_expression_error` passes `ts_stat('select 1') || :value` at this head.
```suggestion
"table_to_xml_and_xmlschema",
# Full-text search functions that run their text argument as a query.
"ts_rewrite",
"ts_stat",
```
##########
superset-frontend/src/components/Datasource/components/CollectionTable/index.tsx:
##########
@@ -326,6 +330,26 @@ export default function CRUDCollection({
}));
}, []);
+ // Read through a ref, and keyed on the nonce alone, because callers pass an
+ // inline arrow: an effect depending on the predicate's identity would run on
+ // every render and reopen a row the user had just collapsed, which is the
+ // opposite of the additive behaviour the prop documents.
+ const expandItemWhereRef = useRef(expandItemWhere);
+ expandItemWhereRef.current = expandItemWhere;
+
+ useEffect(() => {
+ const matches = expandItemWhereRef.current;
+ if (!matches || expandItemNonce === undefined) {
+ return;
+ }
+ const target = collectionArray.find(matches);
+ if (!target) {
+ return;
+ }
+ // Merged rather than replaced, so rows the user opened stay open.
+ setExpandedColumns(prev => ({ ...prev, [target.id]: true }));
+ }, [expandItemNonce, collectionArray]);
Review Comment:
With `collectionArray` in the deps this re-runs on every edit or sort, so a revealed row the user collapsed reopens on their next change to any row, despite the comment above saying it is keyed on the nonce alone.
```suggestion
const target = collectionArrayRef.current.find(matches);
if (!target) {
return;
}
// Merged rather than replaced, so rows the user opened stay open.
setExpandedColumns(prev => ({ ...prev, [target.id]: true }));
}, [expandItemNonce]);
```
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2258 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate. Named so it cannot
+#: plausibly collide with a real column; a collision only makes the count
+#: disagree, which fails closed.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+ """
+ if not transform:
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error(
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the probe
+ uninspected -- string elements are escaped by the dialect's own literal
+ processor. `probe_sql_is_evaluable` then re-reads the finished query, which
+ is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ else:
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ rendered = _compile_literal(clause, dialect)
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(sql: str, engine: str, expected: int) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Three things have to hold, and all three are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+
+ A ``FROM`` clause is allowed: ``select_without_from_suffix`` adds one on the
+ engines that cannot select without a table.
+ """
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if statement.has_subquery():
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=values is not None and not any(value is None for value in values),
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ database.db_engine_spec.select_without_from_suffix,
+ )
+ if not probe_sql_is_evaluable(sql, database.backend, len(distinct)):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _mirror_verdict_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str:
+ """
+ `_probe_cache_key` without the values.
+
+ Whether a transform can be evaluated at all is a property of the transform
+ and the connection, not of the filter that happened to be probing it, so
+ one chart's answer settles the question for the next one.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_verdict:{digest}"
+
+
+def record_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ *,
+ mirrors: bool,
+) -> None:
+ """
+ Remember whether this transform produced a mirror, for the UI to read.
+
+ Advisory only. Nothing in the query path consults it: a probe that failed
+ once is retried on the next chart exactly as it is today, because declining
+ to prune for a whole cache timeout over one transient engine blip is the
+ trade `evaluate_transform` deliberately refuses -- see the comment where it
+ declines to cache a failure.
+
+ What this is for is the *claim*. `is_transform_active` parses the transform
+ and no more, so a transform the database rejects -- a misspelled function
+ is the common case -- is "active", and the editor's banner and Explore's
+ pruning glyph promise a speed-up that never happens. A promise is exactly
+ the thing that may be withheld on one bad answer and restored on a good
+ one, which is why this is a separate entry from the probe's own results
+ rather than a relaxation of that rule.
+
+ Written by `_run_probe`, so the preview endpoint -- which shares the
+ evaluator -- settles the question before the owner has even saved.
+ """
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(
+ _mirror_verdict_cache_key(database, catalog, schema, transform),
+ mirrors,
+ timeout=timeout,
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform verdict", exc_info=True)
+
+
+def known_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> bool | None:
+ """
+ The last verdict `record_mirror_verdict` stored, or `None` if there is none.
+
+ `None` is the honest answer on a cold cache and is deliberately not `False`:
+ reporting a working mapping as broken until something probes it would
+ trade one wrong claim for another. The alternative -- probing from the
+ read side -- would put a warehouse round trip on every Explore and
+ dashboard load, and a failing transform is not cached at all, so it would
+ be a round trip every single time.
+ """
+ try:
+ verdict = cache_manager.cache.get(
+ _mirror_verdict_cache_key(database, catalog, schema, transform)
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return verdict if isinstance(verdict, bool) else None
+
+
+def _compile_literal(element: Any, dialect: Dialect | None) -> str:
+ """
+ Compile with inline literals, undoing the paramstyle's percent doubling.
+
+ Both ``TextClause`` and literal compilation run the dialect's
+ ``post_process_text``, which doubles every ``%`` whenever the identifier
+ preparer asks it to -- true for MySQL and Postgres and for every spec
+ inheriting their paramstyle. That doubling exists so a later DBAPI
+ parameter-interpolation pass can undo it, and the probe has no such pass:
+ it executes with no bound parameters at all. So a transform of
+ ``date_format(:value, '%Y%m%d')`` reaches the warehouse asking for the
+ literal string ``%%Y%%m%%d``, the probe returns that instead of a date, and
+ the mirrored predicate drops every row the filter keeps.
+
+ The same normalization ``Database.compile_sqla_query`` applies for the same
+ reason. ``_double_percents`` is private and not guaranteed on a third-party
+ dialect, hence the ``getattr`` default.
+ """
+ compiled = str(
+ element.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
+ )
+ if dialect is not None and getattr(
+ dialect.identifier_preparer, "_double_percents", False
+ ):
+ compiled = compiled.replace("%%", "%")
+ return compiled
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be *asked* to stand in for itself, and the transform
+ cannot carry Jinja or call a non-deterministic function. Tier 2
+ (``blocking=False``) is everything that merely leaves the mapping inactive
+ -- including a self-mapping nobody asked for, where the partition column
+ merely happens to be the default datetime column.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column == partition_column:
+ # Asked for explicitly, so report it as the mistake it is.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+ elif not partition_mapped_column and main_dttm_col == partition_column:
+ # Resolved onto itself only because the default datetime column happens
+ # to be the partition column -- a state metadata sync could produce
+ # without anyone asking for it. The mapping is inert either way, since
+ # `resolve_partition_mapping` bails out on it, so this reports and lets
+ # the write through: blocking here means a dataset already in the state
+ # can never be saved again, not even to change its description, and
+ # there is no field whose edit would clear the error first.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "%(name)s is both the partition column and the default "
+ "datetime column, so the mapping points at itself and "
+ "stays inactive. Set a mapped column override, or change "
+ "the default datetime column.",
+ name=partition_column,
+ ),
+ blocking=False,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_bare_expression(transform, engine):
+ # Blocking, and deliberately placed in `validate_transform` rather than
+ # only at the probe: one issue here closes the PUT, the importer, the
+ # query-time gate through `is_transform_active`, the Explore indicator's
+ # active verdict and the preview endpoint, all of which already consult
+ # this function.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform must be a single SQL expression. It "
+ "cannot carry a FROM, WHERE, GROUP BY or any other clause, "
+ "and it cannot contain a sub-query."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not contains_value_placeholder(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform must contain the :value placeholder, "
+ "which stands for the filter value being mirrored."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not placeholder_is_executable(transform, engine):
+ # Blocking, and for the same reason the shape gate above is: this is
+ # the function the PUT, the importer, `is_transform_active`, the
+ # Explore indicator and the preview all consult, so one issue here
+ # closes every door at once. A placeholder inside a string literal is
+ # a sub-query the engine will run once a filter value closes the quote;
+ # one inside a comment silently eats the probe's own alias.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The :value placeholder must appear where the engine will "
+ "evaluate it. It cannot sit inside a string literal or a "
+ "comment."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if functions := find_non_deterministic_functions(transform, engine):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform calls %(functions)s, whose result "
+ "depends on when and where it runs. The transform is "
+ "evaluated in a separate session and the result is cached, "
+ "so the emitted predicate would freeze a snapshot of that "
+ "moment.",
+ functions=", ".join(sorted(functions)),
+ ),
+ blocking=True,
+ )
+ ]
+
+ return []
+
+
+@lru_cache(maxsize=LRU_CACHE_MAX_SIZE)
+def is_transform_active(transform: str | None, engine: str) -> bool:
+ """
+ Whether Superset will mirror filters through this transform.
+
+ `validate_transform` with the messages discarded, so the Explore indicator
+ cannot advertise a mapping the save path recorded as inactive. Anything
+ cheaper here would be a second, weaker statement of the same rule, free to
+ drift from the one the save path applies.
+
+ Blocking issues count too. Jinja and non-deterministic transforms are
+ rejected on PUT, but `CreateDatasetCommand` and import do not validate the
+ mapping, so one can still reach the database -- and it would never mirror a
+ filter either.
+
+ Memoized because `partition_filter_mapping_summary` is serialized on every
+ Explore and dashboard load and this parses the transform. The key is
+ everything the answer depends on: `validate_transform` reads no session, no
+ locale and no config beyond `SQL_MAX_PARSE_LENGTH`, which bounds the parser
+ rather than changing a verdict within that bound.
+ """
+ return not validate_transform(transform, engine)
+
+
+def preview_partition_mapping( # pylint: disable=too-many-return-statements
+ datasource: SqlaTable,
+ *,
+ mapped_column: str,
+ value_transform: str | None,
+ sample_values: list[str],
+ operator: FilterOperator = FilterOperator.EQUALS,
+ is_monotonic: bool = False,
+ partition_column: str | None = None,
+) -> dict[str, Any]:
+ """
+ Evaluate a candidate mapping and describe the predicate it would emit.
+
+ Shares the evaluator -- and therefore the probe cache -- with the query
+ path, so preview and runtime cannot drift and a previewed transform warms
+ the chart path for free. The predicate itself comes from
+ `build_mirrored_predicates`, the same builder the query path uses, so
+ operator shapes cannot drift either: what the panel shows is what a chart
+ would emit.
+
+ Validation runs first and the engine second: a half-typed transform is by
+ definition unparseable, so most of what a text input produces costs zero
+ queries.
+
+ Every part of the mapping is taken from the request rather than the stored
+ dataset. The editor previews while the owner is still editing -- a mapping
+ that has to be saved before it can be checked is not a preview.
+ """
+ partition_column = partition_column or datasource.partition_column
+ if not partition_column:
+ return {
+ "valid": False,
+ "reason": "unconfigured",
+ "error": _("No partition column is set."),
+ }
+
+ columns_by_name = {str(column.column_name): column for column in datasource.columns}
+ if mapped_column not in columns_by_name:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _("%(name)s is not a column on this dataset.", name=mapped_column),
+ }
+
+ # The bail-out `resolve_partition_mapping` makes at query time, and that
+ # `partition_filter_mapping_summary` repeats for the Explore indicator.
+ # Without it here, preview reports a valid emitted predicate for a mapping
+ # no chart will ever mirror -- the one answer a preview panel must not give.
+ if has_active_advanced_data_type(columns_by_name[mapped_column]):
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _(
+ "%(name)s has an advanced data type, so its filters are "
+ "translated into their own predicate shape and cannot be "
+ "mirrored onto the partition column.",
+ name=mapped_column,
+ ),
+ }
+
+ engine = datasource.database.backend
+ for issue in validate_partition_mapping(
+ column_names=set(columns_by_name),
+ partition_column=str(partition_column),
+ partition_mapped_column=mapped_column,
+ main_dttm_col=datasource.main_dttm_col,
+ transform=value_transform,
+ engine=engine,
+ ):
+ return {
+ "valid": False,
+ # The parse failure is the one an owner sees constantly, and it is
+ # the only one the mockup gives its own headline to.
+ "reason": (
+ "parse"
+ if issue.field == "partition_value_transform"
+ and not is_parseable(value_transform, engine)
+ else "validation"
+ ),
+ "error": str(issue.message),
+ }
+
+ # The policy every other stored expression goes through. The save path
+ # applies it in `UpdateDatasetCommand._validate_partition_mapping`, but
+ # preview evaluates a candidate transform that has not been saved, so
+ # without this the gate had a door around it. See
+ # `stored_expression_error` for what is being kept out and why.
+ if reason := stored_expression_error(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ cast(str, value_transform),
+ ):
+ return {"valid": False, "reason": "validation", "error": reason}
+
+ mapping = PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=mapped_column,
+ value_transform=cast(str, value_transform),
+ is_monotonic=is_monotonic,
+ equality_is_safe=equality_mirrors_safely(
+ columns_by_name[mapped_column], datasource.database.db_engine_spec
+ ),
+ )
+ sample_input = _render_sample_input(
+ datasource, mapped_column, operator, sample_values
+ )
+
+ if operator not in PREVIEWABLE_OPERATORS:
+ # Checked before `mirrors`, which lets `TEMPORAL_RANGE` through when the
+ # transform is declared monotonic -- and the single sample value would
+ # then reach `handle_comparison_filter`, which has no case for a range
+ # and raises. The request schema rejects it too; this keeps the function
+ # honest for any other caller.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is mirrored as a pair of bounds, which "
+ "a preview of a single value cannot describe.",
+ operator=operator.value,
+ ),
+ }
+
+ if not mapping.mirrors(operator):
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is only mirrored when the transform "
+ "preserves ordering, which this one is not declared to do.",
+ operator=operator.value,
+ ),
+ }
+
+ value = _probe_input(
+ datasource, columns_by_name[mapped_column], operator, sample_values
+ )
+ errors: list[str] = []
+ type_errors: list[str] = []
+ predicates = build_mirrored_predicates(
+ datasource,
+ mapping,
+ [(operator, value)],
+ errors=errors,
+ type_errors=type_errors,
+ )
+ if type_errors:
+ # Its own reason, because "the database would not evaluate this" and
+ # "it evaluated and answered with the wrong kind of thing" are
+ # different problems with different fixes, and the owner is the only
+ # one who can tell which transform they meant to write.
+ return {
+ "valid": False,
+ "reason": "type",
+ "sample_input": sample_input,
+ "error": type_errors[0],
+ }
+ if not predicates:
+ return {
+ "valid": False,
+ "reason": "engine",
+ "sample_input": sample_input,
+ "error": (
+ _(
+ "The transform could not be evaluated against the "
+ "database: %(reason)s",
+ reason=errors[0],
+ )
+ if errors
+ else _("The transform could not be evaluated against the database.")
+ ),
+ }
+
+ return {
+ "valid": True,
+ "sample_input": sample_input,
+ "emitted_predicate": _render_predicate(datasource, predicates[0]),
+ }
+
+
+def _probe_input(
+ datasource: SqlaTable,
+ column: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+) -> Any:
+ """
+ The sample values as the query path would bind them.
+
+ The request carries samples as strings, and the probe is keyed on exactly
+ what it is handed, so passing them through raw asks the engine a different
+ question from the one a chart asks. A sample of ``2025`` on a numeric
+ column has to arrive as the integer the chart compares: under a transform
+ of ``typeof(:value)`` the raw string previewed ``'text'`` where the chart
+ emitted ``'integer'``. And because `_probe_cache_key` keys on each value's
+ ``repr``, the two also missed each other's cache entirely -- so the "a
+ previewed transform warms the chart path for free" claim in
+ `preview_partition_mapping`'s docstring did not actually hold.
+
+ Coerced by `filter_values_handler`, the same function the query path uses,
+ rather than by a second implementation of the same rules.
+
+ Ranges are not previewable (see `PREVIEWABLE_OPERATORS`), so the bound
+ conversion `_collect_partition_mirror_range` applies -- a ``datetime`` into
+ the column's stored representation -- has no counterpart here.
+ """
+ is_list = operator == FilterOperator.IN
+ column_spec = datasource.db_engine_spec.get_column_spec(native_type=column.type)
+ handled = datasource.filter_values_handler(
+ # `list[str]` is not a `list[FilterValue]` to mypy, invariantly, even
+ # though every `str` is a `FilterValue`.
+ values=cast(FilterValues, sample_values if is_list else sample_values[0]),
+ operator=operator,
+ target_generic_type=(
+ column_spec.generic_type if column_spec else utils.GenericDataType.STRING
+ ),
+ target_native_type=column.type,
+ is_list_target=is_list,
+ db_engine_spec=datasource.db_engine_spec,
+ db_extra=datasource.db_extra,
+ )
+
+ def bindable(value: Any) -> Any:
+ # An epoch-milliseconds sample on a temporal column comes back as
+ # engine SQL rather than a value, and SQL cannot be the value of a bind
+ # parameter -- carried as text so the probe substitutes it, the same way
+ # an array literal is.
+ if isinstance(value, ColumnElement):
+ return raw_probe_value(datasource.database, value)
+ return value
+
+ if is_list and isinstance(handled, (list, tuple)):
+ return [bindable(entry) for entry in handled]
+ return bindable(handled)
+
+
+def _render_sample_input(
+ datasource: SqlaTable,
+ mapped_column: str,
+ operator: FilterOperator,
+ values: list[str],
+) -> str:
+ """
+ The filter being previewed, written the way an owner would read it.
+
+ Display-only -- it is never executed -- but it is still read as SQL, so the
+ column is quoted and the values are rendered by the dialect rather than
+ concatenated raw. A column named ``order date`` would otherwise come out as
+ two bare words.
+ """
+ quoted = datasource.quote_identifier(mapped_column)
+ if operator == FilterOperator.IN:
+ rendered = ", ".join(
+ _render_literal(datasource.database, value) for value in values
+ )
+ return f"{quoted} IN ({rendered})"
+ return (
+ f"{quoted} {operator.value} {_render_literal(datasource.database, values[0])}"
+ )
+
+
+def _render_predicate(datasource: SqlaTable, predicate: ColumnElement[Any]) -> str:
+ """
+ Compile a mirrored predicate to the text a reader would see in View query.
+
+ Every value in it is a probed constant by this point, so ``literal_binds``
+ renders the same literals the chart query carries.
+ """
+ return _compile_literal(predicate, _dialect_for(datasource.database)).replace(
+ "\n", " "
+ )
+
+
+def _render_literal(database: Database, value: Any) -> str:
+ """
+ Render a value the way it appears in the generated SQL.
+
+ Compiled by the dialect rather than formatted by hand. `str()` would render
+ a NULL as the Python repr `None` and leave a date unquoted, neither of which
+ is SQL, and hand-rolled quote-doubling would only ever have been right for
+ strings.
+ """
+ return _compile_literal(sa.literal(value), _dialect_for(database))
+
+
+def build_mirrored_predicates(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ requests: list[tuple[FilterOperator, Any]],
+ *,
+ errors: list[str] | None = None,
+ type_errors: list[str] | None = None,
+) -> list[ColumnElement[Any]]:
+ """
+ Turn collected ``(operator, value)`` mirror requests into predicates.
+
+ ``requests`` is expected to be deduplicated by the caller. Every value is
+ resolved in a single probe round trip -- one per chart query at most -- then
+ emitted as a literal constant, so "View query" shows the reader an ordinary
+ ``WHERE`` clause rather than an inline expression.
+
+ A strict bound is emitted non-strictly; see `mirror_operator`. That happens
+ here, at the one point where a ``FilterOperator`` becomes SQL, rather than
+ at the collection sites in `ExploreMixin`: the preview endpoint calls this
+ directly, so this is what keeps the predicate the editor shows an owner and
+ the predicate the chart carries from disagreeing.
+
+ :param errors: optional sink; see `evaluate_transform`.
+ :param type_errors: optional sink for a probe result the partition column
+ cannot hold -- see `probed_value_type_error`. Separate from ``errors``
+ because the two say different things to an owner: that one is "the
+ database would not evaluate this", and this one is "it evaluated, and
+ answered with the wrong kind of thing".
+ """
+ if not requests:
+ return []
+
+ partition_column = next(
+ (
+ column
+ for column in datasource.columns
+ if column.column_name == mapping.partition_column
+ ),
+ None,
+ )
+ if partition_column is None:
+ return []
+
+ # Flatten every value that needs probing into one list, remembering how many
+ # each request consumed so the results can be handed back out.
+ flat: list[Any] = []
+ spans: list[tuple[FilterOperator, int, int]] = []
+ for operator, value in requests:
+ values = list(value) if operator == FilterOperator.IN else [value]
+ spans.append((operator, len(flat), len(values)))
+ flat.extend(values)
+
+ evaluated = evaluate_transform(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ mapping.value_transform,
+ flat,
+ errors=errors,
+ )
+ if evaluated is None:
+ return []
+
+ if not _bounds_are_ordered(evaluated, spans):
+ return []
+
+ # Declining here is the last chance to decline at all: once these
+ # predicates are in the statement, a value the partition column cannot
+ # hold fails the whole chart rather than its pruning.
+ if reason := probed_value_type_error(partition_column, evaluated):
+ logger.warning(
+ "Partition transform returned a value the partition column cannot "
+ "hold; queries will not prune: %s",
+ reason,
+ )
+ if type_errors is not None:
+ type_errors.append(reason)
+ record_mirror_verdict(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ mapping.value_transform,
+ mirrors=False,
+ )
+ return []
+
+ sqla_col = datasource.convert_tbl_column_to_sqla_col(partition_column)
+ predicates = _predicates_from_probe(
+ sqla_col, datasource.db_engine_spec, evaluated, spans
+ )
+ if not predicates:
+ return []
+
+ # A comparison against a NULL partition value is NULL, so a row parked in a
+ # NULL partition is dropped by the mirror even when the real filter matches
+ # it -- Hive and Impala's default partition, or a transform that returns
+ # NULL for an input it cannot convert. The mirror only has to be no
+ # narrower than the filter it stands in for, so admitting NULL partitions
+ # keeps those rows. Engines still prune; they read one extra partition.
+ return [sa.or_(sa.and_(*predicates), sqla_col.is_(None))]
+
+
+def _predicates_from_probe(
+ sqla_col: ColumnElement[Any],
+ db_engine_spec: type[BaseEngineSpec],
+ evaluated: list[Any],
+ spans: list[tuple[FilterOperator, int, int]],
+) -> list[ColumnElement[Any]]:
+ """
+ One predicate on the partition column per surviving mirror request.
+
+ A request whose probe answered `None` for any of its values is skipped
+ rather than emitted: `col = NULL` is `NULL`, so it would drop every row the
+ filter keeps. A strict bound is emitted non-strictly; see `mirror_operator`.
+ """
+ predicates: list[ColumnElement[Any]] = []
+ for operator, start, length in spans:
+ chunk = evaluated[start : start + length]
+ if any(value is None for value in chunk):
+ continue
+ if operator == FilterOperator.IN:
+ # The probe answers per value, so a transform over a mixed-number
+ # filter can answer with a mixed-number partition key -- and
+ # `in_` infers the bind type from the first element it is handed.
+ # Without this, probe results of `[33, 29.02]` emit
+ # `IN (33, 29)` and prune away the partition holding `29.02`.
+ predicates.append(sqla_col.in_(normalize_mixed_numbers(chunk)))
+ else:
+ predicates.append(
+ db_engine_spec.handle_comparison_filter(
+ sqla_col, mirror_operator(operator), chunk[0]
+ )
+ )
+ return predicates
+
+
+#: Operators whose value is the lower end of a range, and whose upper-end twins.
+#:
+#: Shared with `ExploreMixin._mirror_probe_input`, which rounds a bound *outward*
+#: where the engine resolves it more coarsely than the filter carries -- backward
+#: for a lower bound, forward for an upper one. Which end an operator names is
+#: the only thing separating the two directions in either caller, so the two have
+#: to agree on it rather than each classify for itself.
+LOWER_BOUND_OPERATORS = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+}
+UPPER_BOUND_OPERATORS = {
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+#: What Python type a probe result may have, per generic type of the partition
+#: column it is about to be compared against.
+#:
+#: Only the types a mismatch can actually break a query with are listed. A
+#: ``STRING`` partition column is deliberately absent: every engine accepts a
+#: number in a text comparison, and refusing one would break a working mapping
+#: for the sake of tidiness. An unresolvable column type is absent for the
+#: stronger reason that there is nothing to check against.
+_PROBE_RESULT_TYPES: dict[utils.GenericDataType, tuple[type, ...]] = {
+ utils.GenericDataType.NUMERIC: (int, float),
Review Comment:
A `Decimal` probe result is refused here even against a NUMERIC partition column, so `extract(epoch from :value)` on Postgres 14+ (and decimal arithmetic on MySQL, Snowflake, Oracle) stops mirroring and preview reports `type`. Add `Decimal`; no suggestion because the import sits ~2,000 lines up.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4191232092
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2264 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate. Named so it cannot
+#: plausibly collide with a real column; a collision only makes the count
+#: disagree, which fails closed.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+ """
+ if not transform:
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
Review Comment:
The count check can be satisfied by the owner writing `superset_pfm_value_standin` themselves. In `concat(superset_pfm_value_standin, ':value')` that identifier is the one expected column reference, while the real `:value` sits inside a string literal, so `placeholder_is_executable` returns True. At probe time the bound value is rendered inside that literal, so a sample value like `) AS v0 FROM private.secrets AS p(superset_pfm_value_standin) -- ` compiles to one statement with no sub-query and the alias `v0`, which `probe_sql_is_evaluable` accepts. On Postgres `p(superset_pfm_value_standin)` is a column alias, so a column from any table the warehouse connection can read comes back through the preview's emitted predicate, for a user who has dataset write but no SQL Lab. Could the transform be rejected when the stand-in already appears in its text (and the compiled probe be limited to the engine's own `FROM` suffix)?
##########
superset/models/helpers.py:
##########
@@ -5041,6 +5688,26 @@ def get_sqla_query( # pylint: disable=too-many-arguments,too-many-locals,too-ma
)
if _main_dttm_filter is not None:
time_filters.append(_main_dttm_filter)
+ # This block filters `main_dttm_col`, a *different* column
+ # from `dttm_col`. Checking only `dttm_col` below would miss
+ # it when the mapping tracks the main datetime column.
+ self._collect_partition_mirror_range(
+ partition_mapping,
+ partition_mirror,
+ self.main_dttm_col,
+ from_dttm,
+ to_dttm,
+ )
+ if not db_engine_spec.time_groupby_inline:
+ # Only where the subquery actually gets a time filter
+ # -- see the longer note on the `dttm_col` mirror below.
+ self._collect_partition_mirror_range(
+ partition_mapping,
+ partition_mirror_inner,
Review Comment:
This adds an inner-window partition mirror for `main_dttm_col`, but the series-limit subquery only gets a time filter on `dttm_col` (`inner_time_filter`), never on `main_dttm_col`. With `always_filter_main_dttm` on and a chart time column that differs from the main one, the ranking subquery is narrowed by a partition predicate that has no matching time predicate. Example: series A has 100 rows with a January chart-column date but a December main-column date plus 1 row in January on both, series B has 10 rows in January on both; unmapped, the top series is A (101 vs 10) and the outer query returns A's one row, but with the mapping A's December rows are excluded from the ranking and B is returned instead. Should this inner mirror be dropped, since the subquery never filters `main_dttm_col`?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2264 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate. Named so it cannot
+#: plausibly collide with a real column; a collision only makes the count
+#: disagree, which fails closed.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+ """
+ if not transform:
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error(
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the probe
+ uninspected -- string elements are escaped by the dialect's own literal
+ processor. `probe_sql_is_evaluable` then re-reads the finished query, which
+ is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ else:
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ rendered = _compile_literal(clause, dialect)
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(sql: str, engine: str, expected: int) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Three things have to hold, and all three are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+
+ A ``FROM`` clause is allowed: ``select_without_from_suffix`` adds one on the
+ engines that cannot select without a table.
+ """
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if statement.has_subquery():
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=values is not None and not any(value is None for value in values),
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ database.db_engine_spec.select_without_from_suffix,
+ )
+ if not probe_sql_is_evaluable(sql, database.backend, len(distinct)):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _mirror_verdict_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str:
+ """
+ `_probe_cache_key` without the values.
+
+ Whether a transform can be evaluated at all is a property of the transform
+ and the connection, not of the filter that happened to be probing it, so
+ one chart's answer settles the question for the next one.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_verdict:{digest}"
+
+
+def record_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ *,
+ mirrors: bool,
+) -> None:
+ """
+ Remember whether this transform produced a mirror, for the UI to read.
+
+ Advisory only. Nothing in the query path consults it: a probe that failed
+ once is retried on the next chart exactly as it is today, because declining
+ to prune for a whole cache timeout over one transient engine blip is the
+ trade `evaluate_transform` deliberately refuses -- see the comment where it
+ declines to cache a failure.
+
+ What this is for is the *claim*. `is_transform_active` parses the transform
+ and no more, so a transform the database rejects -- a misspelled function
+ is the common case -- is "active", and the editor's banner and Explore's
+ pruning glyph promise a speed-up that never happens. A promise is exactly
+ the thing that may be withheld on one bad answer and restored on a good
+ one, which is why this is a separate entry from the probe's own results
+ rather than a relaxation of that rule.
+
+ Written by `_run_probe`, so the preview endpoint -- which shares the
+ evaluator -- settles the question before the owner has even saved.
+ """
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(
+ _mirror_verdict_cache_key(database, catalog, schema, transform),
+ mirrors,
+ timeout=timeout,
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform verdict", exc_info=True)
+
+
+def known_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> bool | None:
+ """
+ The last verdict `record_mirror_verdict` stored, or `None` if there is none.
+
+ `None` is the honest answer on a cold cache and is deliberately not `False`:
+ reporting a working mapping as broken until something probes it would
+ trade one wrong claim for another. The alternative -- probing from the
+ read side -- would put a warehouse round trip on every Explore and
+ dashboard load, and a failing transform is not cached at all, so it would
+ be a round trip every single time.
+ """
+ try:
+ verdict = cache_manager.cache.get(
+ _mirror_verdict_cache_key(database, catalog, schema, transform)
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return verdict if isinstance(verdict, bool) else None
+
+
+def _compile_literal(element: Any, dialect: Dialect | None) -> str:
+ """
+ Compile with inline literals, undoing the paramstyle's percent doubling.
+
+ Both ``TextClause`` and literal compilation run the dialect's
+ ``post_process_text``, which doubles every ``%`` whenever the identifier
+ preparer asks it to -- true for MySQL and Postgres and for every spec
+ inheriting their paramstyle. That doubling exists so a later DBAPI
+ parameter-interpolation pass can undo it, and the probe has no such pass:
+ it executes with no bound parameters at all. So a transform of
+ ``date_format(:value, '%Y%m%d')`` reaches the warehouse asking for the
+ literal string ``%%Y%%m%%d``, the probe returns that instead of a date, and
+ the mirrored predicate drops every row the filter keeps.
+
+ The same normalization ``Database.compile_sqla_query`` applies for the same
+ reason. ``_double_percents`` is private and not guaranteed on a third-party
+ dialect, hence the ``getattr`` default.
+ """
+ compiled = str(
+ element.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
+ )
+ if dialect is not None and getattr(
+ dialect.identifier_preparer, "_double_percents", False
+ ):
+ compiled = compiled.replace("%%", "%")
+ return compiled
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be *asked* to stand in for itself, and the transform
+ cannot carry Jinja or call a non-deterministic function. Tier 2
+ (``blocking=False``) is everything that merely leaves the mapping inactive
+ -- including a self-mapping nobody asked for, where the partition column
+ merely happens to be the default datetime column.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column == partition_column:
+ # Asked for explicitly, so report it as the mistake it is.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+ elif not partition_mapped_column and main_dttm_col == partition_column:
+ # Resolved onto itself only because the default datetime column happens
+ # to be the partition column -- a state metadata sync could produce
+ # without anyone asking for it. The mapping is inert either way, since
+ # `resolve_partition_mapping` bails out on it, so this reports and lets
+ # the write through: blocking here means a dataset already in the state
+ # can never be saved again, not even to change its description, and
+ # there is no field whose edit would clear the error first.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "%(name)s is both the partition column and the default "
+ "datetime column, so the mapping points at itself and "
+ "stays inactive. Set a mapped column override, or change "
+ "the default datetime column.",
+ name=partition_column,
+ ),
+ blocking=False,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_bare_expression(transform, engine):
+ # Blocking, and deliberately placed in `validate_transform` rather than
+ # only at the probe: one issue here closes the PUT, the importer, the
+ # query-time gate through `is_transform_active`, the Explore indicator's
+ # active verdict and the preview endpoint, all of which already consult
+ # this function.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform must be a single SQL expression. It "
+ "cannot carry a FROM, WHERE, GROUP BY or any other clause, "
+ "and it cannot contain a sub-query."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not contains_value_placeholder(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform must contain the :value placeholder, "
+ "which stands for the filter value being mirrored."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not placeholder_is_executable(transform, engine):
+ # Blocking, and for the same reason the shape gate above is: this is
+ # the function the PUT, the importer, `is_transform_active`, the
+ # Explore indicator and the preview all consult, so one issue here
+ # closes every door at once. A placeholder inside a string literal is
+ # a sub-query the engine will run once a filter value closes the quote;
+ # one inside a comment silently eats the probe's own alias.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The :value placeholder must appear where the engine will "
+ "evaluate it. It cannot sit inside a string literal or a "
+ "comment."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if functions := find_non_deterministic_functions(transform, engine):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform calls %(functions)s, whose result "
+ "depends on when and where it runs. The transform is "
+ "evaluated in a separate session and the result is cached, "
+ "so the emitted predicate would freeze a snapshot of that "
+ "moment.",
+ functions=", ".join(sorted(functions)),
+ ),
+ blocking=True,
+ )
+ ]
+
+ return []
+
+
+@lru_cache(maxsize=LRU_CACHE_MAX_SIZE)
+def is_transform_active(transform: str | None, engine: str) -> bool:
+ """
+ Whether Superset will mirror filters through this transform.
+
+ `validate_transform` with the messages discarded, so the Explore indicator
+ cannot advertise a mapping the save path recorded as inactive. Anything
+ cheaper here would be a second, weaker statement of the same rule, free to
+ drift from the one the save path applies.
+
+ Blocking issues count too. Jinja and non-deterministic transforms are
+ rejected on PUT, but `CreateDatasetCommand` and import do not validate the
+ mapping, so one can still reach the database -- and it would never mirror a
+ filter either.
+
+ Memoized because `partition_filter_mapping_summary` is serialized on every
+ Explore and dashboard load and this parses the transform. The key is
+ everything the answer depends on: `validate_transform` reads no session, no
+ locale and no config beyond `SQL_MAX_PARSE_LENGTH`, which bounds the parser
+ rather than changing a verdict within that bound.
+ """
+ return not validate_transform(transform, engine)
+
+
+def preview_partition_mapping( # pylint: disable=too-many-return-statements
+ datasource: SqlaTable,
+ *,
+ mapped_column: str,
+ value_transform: str | None,
+ sample_values: list[str],
+ operator: FilterOperator = FilterOperator.EQUALS,
+ is_monotonic: bool = False,
+ partition_column: str | None = None,
+) -> dict[str, Any]:
+ """
+ Evaluate a candidate mapping and describe the predicate it would emit.
+
+ Shares the evaluator -- and therefore the probe cache -- with the query
+ path, so preview and runtime cannot drift and a previewed transform warms
+ the chart path for free. The predicate itself comes from
+ `build_mirrored_predicates`, the same builder the query path uses, so
+ operator shapes cannot drift either: what the panel shows is what a chart
+ would emit.
+
+ Validation runs first and the engine second: a half-typed transform is by
+ definition unparseable, so most of what a text input produces costs zero
+ queries.
+
+ Every part of the mapping is taken from the request rather than the stored
+ dataset. The editor previews while the owner is still editing -- a mapping
+ that has to be saved before it can be checked is not a preview.
+ """
+ partition_column = partition_column or datasource.partition_column
+ if not partition_column:
+ return {
+ "valid": False,
+ "reason": "unconfigured",
+ "error": _("No partition column is set."),
+ }
+
+ columns_by_name = {str(column.column_name): column for column in datasource.columns}
+ if mapped_column not in columns_by_name:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _("%(name)s is not a column on this dataset.", name=mapped_column),
+ }
+
+ # The bail-out `resolve_partition_mapping` makes at query time, and that
+ # `partition_filter_mapping_summary` repeats for the Explore indicator.
+ # Without it here, preview reports a valid emitted predicate for a mapping
+ # no chart will ever mirror -- the one answer a preview panel must not give.
+ if has_active_advanced_data_type(columns_by_name[mapped_column]):
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _(
+ "%(name)s has an advanced data type, so its filters are "
+ "translated into their own predicate shape and cannot be "
+ "mirrored onto the partition column.",
+ name=mapped_column,
+ ),
+ }
+
+ engine = datasource.database.backend
+ for issue in validate_partition_mapping(
+ column_names=set(columns_by_name),
+ partition_column=str(partition_column),
+ partition_mapped_column=mapped_column,
+ main_dttm_col=datasource.main_dttm_col,
+ transform=value_transform,
+ engine=engine,
+ ):
+ return {
+ "valid": False,
+ # The parse failure is the one an owner sees constantly, and it is
+ # the only one the mockup gives its own headline to.
+ "reason": (
+ "parse"
+ if issue.field == "partition_value_transform"
+ and not is_parseable(value_transform, engine)
+ else "validation"
+ ),
+ "error": str(issue.message),
+ }
+
+ # The policy every other stored expression goes through. The save path
+ # applies it in `UpdateDatasetCommand._validate_partition_mapping`, but
+ # preview evaluates a candidate transform that has not been saved, so
+ # without this the gate had a door around it. See
+ # `stored_expression_error` for what is being kept out and why.
+ if reason := stored_expression_error(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ cast(str, value_transform),
+ ):
+ return {"valid": False, "reason": "validation", "error": reason}
+
+ mapping = PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=mapped_column,
+ value_transform=cast(str, value_transform),
+ is_monotonic=is_monotonic,
+ equality_is_safe=equality_mirrors_safely(
+ columns_by_name[mapped_column], datasource.database.db_engine_spec
+ ),
+ )
+ sample_input = _render_sample_input(
+ datasource, mapped_column, operator, sample_values
+ )
+
+ if operator not in PREVIEWABLE_OPERATORS:
+ # Checked before `mirrors`, which lets `TEMPORAL_RANGE` through when the
+ # transform is declared monotonic -- and the single sample value would
+ # then reach `handle_comparison_filter`, which has no case for a range
+ # and raises. The request schema rejects it too; this keeps the function
+ # honest for any other caller.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is mirrored as a pair of bounds, which "
+ "a preview of a single value cannot describe.",
+ operator=operator.value,
+ ),
+ }
+
+ if not mapping.mirrors(operator):
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is only mirrored when the transform "
+ "preserves ordering, which this one is not declared to do.",
+ operator=operator.value,
+ ),
+ }
+
+ value = _probe_input(
Review Comment:
Preview passes `_probe_input` straight into `build_mirrored_predicates`, but chart filters go through `ExploreMixin._mirror_probe_input` first, which widens a bound or declines an equality when the engine compares less of a datetime than the filter carries. On a `DATE` mapped column with `to_char(cast(:value as timestamp), 'YYYYMMDDHH24MISS')`, previewing `==` with `2026-07-06 10:08:11` returns a valid predicate on `'20260706100811'`, while the same chart filter emits no mirror at all; for a bound, the preview shows an un-widened (narrower) value than the query uses. Could the preview run its samples through the same normalize-or-decline step as the chart path?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,2264 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate. Named so it cannot
+#: plausibly collide with a real column; a collision only makes the count
+#: disagree, which fails closed.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+ """
+ if not transform:
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error(
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the probe
+ uninspected -- string elements are escaped by the dialect's own literal
+ processor. `probe_sql_is_evaluable` then re-reads the finished query, which
+ is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ else:
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ rendered = _compile_literal(clause, dialect)
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(sql: str, engine: str, expected: int) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Three things have to hold, and all three are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+
+ A ``FROM`` clause is allowed: ``select_without_from_suffix`` adds one on the
+ engines that cannot select without a table.
+ """
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if statement.has_subquery():
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=values is not None and not any(value is None for value in values),
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ database.db_engine_spec.select_without_from_suffix,
+ )
+ if not probe_sql_is_evaluable(sql, database.backend, len(distinct)):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _mirror_verdict_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str:
+ """
+ `_probe_cache_key` without the values.
+
+ Whether a transform can be evaluated at all is a property of the transform
+ and the connection, not of the filter that happened to be probing it, so
+ one chart's answer settles the question for the next one.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_verdict:{digest}"
+
+
+def record_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ *,
+ mirrors: bool,
+) -> None:
+ """
+ Remember whether this transform produced a mirror, for the UI to read.
+
+ Advisory only. Nothing in the query path consults it: a probe that failed
+ once is retried on the next chart exactly as it is today, because declining
+ to prune for a whole cache timeout over one transient engine blip is the
+ trade `evaluate_transform` deliberately refuses -- see the comment where it
+ declines to cache a failure.
+
+ What this is for is the *claim*. `is_transform_active` parses the transform
+ and no more, so a transform the database rejects -- a misspelled function
+ is the common case -- is "active", and the editor's banner and Explore's
+ pruning glyph promise a speed-up that never happens. A promise is exactly
+ the thing that may be withheld on one bad answer and restored on a good
+ one, which is why this is a separate entry from the probe's own results
+ rather than a relaxation of that rule.
+
+ Written by `_run_probe`, so the preview endpoint -- which shares the
+ evaluator -- settles the question before the owner has even saved.
+ """
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(
+ _mirror_verdict_cache_key(database, catalog, schema, transform),
+ mirrors,
+ timeout=timeout,
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform verdict", exc_info=True)
+
+
+def known_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> bool | None:
+ """
+ The last verdict `record_mirror_verdict` stored, or `None` if there is none.
+
+ `None` is the honest answer on a cold cache and is deliberately not `False`:
+ reporting a working mapping as broken until something probes it would
+ trade one wrong claim for another. The alternative -- probing from the
+ read side -- would put a warehouse round trip on every Explore and
+ dashboard load, and a failing transform is not cached at all, so it would
+ be a round trip every single time.
+ """
+ try:
+ verdict = cache_manager.cache.get(
+ _mirror_verdict_cache_key(database, catalog, schema, transform)
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return verdict if isinstance(verdict, bool) else None
+
+
+def _compile_literal(element: Any, dialect: Dialect | None) -> str:
+ """
+ Compile with inline literals, undoing the paramstyle's percent doubling.
+
+ Both ``TextClause`` and literal compilation run the dialect's
+ ``post_process_text``, which doubles every ``%`` whenever the identifier
+ preparer asks it to -- true for MySQL and Postgres and for every spec
+ inheriting their paramstyle. That doubling exists so a later DBAPI
+ parameter-interpolation pass can undo it, and the probe has no such pass:
+ it executes with no bound parameters at all. So a transform of
+ ``date_format(:value, '%Y%m%d')`` reaches the warehouse asking for the
+ literal string ``%%Y%%m%%d``, the probe returns that instead of a date, and
+ the mirrored predicate drops every row the filter keeps.
+
+ The same normalization ``Database.compile_sqla_query`` applies for the same
+ reason. ``_double_percents`` is private and not guaranteed on a third-party
+ dialect, hence the ``getattr`` default.
+ """
+ compiled = str(
+ element.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
+ )
+ if dialect is not None and getattr(
+ dialect.identifier_preparer, "_double_percents", False
+ ):
+ compiled = compiled.replace("%%", "%")
+ return compiled
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be *asked* to stand in for itself, and the transform
+ cannot carry Jinja or call a non-deterministic function. Tier 2
+ (``blocking=False``) is everything that merely leaves the mapping inactive
+ -- including a self-mapping nobody asked for, where the partition column
+ merely happens to be the default datetime column.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column == partition_column:
+ # Asked for explicitly, so report it as the mistake it is.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+ elif not partition_mapped_column and main_dttm_col == partition_column:
+ # Resolved onto itself only because the default datetime column happens
+ # to be the partition column -- a state metadata sync could produce
+ # without anyone asking for it. The mapping is inert either way, since
+ # `resolve_partition_mapping` bails out on it, so this reports and lets
+ # the write through: blocking here means a dataset already in the state
+ # can never be saved again, not even to change its description, and
+ # there is no field whose edit would clear the error first.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "%(name)s is both the partition column and the default "
+ "datetime column, so the mapping points at itself and "
+ "stays inactive. Set a mapped column override, or change "
+ "the default datetime column.",
+ name=partition_column,
+ ),
+ blocking=False,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def validate_transform(
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """Validate the value transform on its own. See `validate_partition_mapping`."""
+ field = "partition_value_transform"
+
+ if contains_jinja(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "Jinja templating is not supported in a partition value "
+ "transform. The transform is evaluated in a different "
+ "context and at a different time from the chart query, so "
+ "a template would not render the same way."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not transform or not transform.strip():
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "No value transform is set, so no filter will be mirrored "
+ "onto the partition column."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_parseable(transform, engine):
+ detail = parse_error_detail(cast(str, transform), engine)
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=(
+ _(
+ "The value transform could not be parsed: %(detail)s "
+ "The mapping is saved but stays inactive until it does.",
+ detail=detail,
+ )
+ if detail
+ else _(
+ "The value transform could not be parsed. The mapping "
+ "is saved but stays inactive until it does."
+ )
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not is_bare_expression(transform, engine):
+ # Blocking, and deliberately placed in `validate_transform` rather than
+ # only at the probe: one issue here closes the PUT, the importer, the
+ # query-time gate through `is_transform_active`, the Explore indicator's
+ # active verdict and the preview endpoint, all of which already consult
+ # this function.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "A value transform must be a single SQL expression. It "
+ "cannot carry a FROM, WHERE, GROUP BY or any other clause, "
+ "and it cannot contain a sub-query."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if not contains_value_placeholder(transform):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform must contain the :value placeholder, "
+ "which stands for the filter value being mirrored."
+ ),
+ blocking=False,
+ )
+ ]
+
+ if not placeholder_is_executable(transform, engine):
+ # Blocking, and for the same reason the shape gate above is: this is
+ # the function the PUT, the importer, `is_transform_active`, the
+ # Explore indicator and the preview all consult, so one issue here
+ # closes every door at once. A placeholder inside a string literal is
+ # a sub-query the engine will run once a filter value closes the quote;
+ # one inside a comment silently eats the probe's own alias.
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The :value placeholder must appear where the engine will "
+ "evaluate it. It cannot sit inside a string literal or a "
+ "comment."
+ ),
+ blocking=True,
+ )
+ ]
+
+ if functions := find_non_deterministic_functions(transform, engine):
+ return [
+ MappingValidationIssue(
+ field=field,
+ message=_(
+ "The value transform calls %(functions)s, whose result "
+ "depends on when and where it runs. The transform is "
+ "evaluated in a separate session and the result is cached, "
+ "so the emitted predicate would freeze a snapshot of that "
+ "moment.",
+ functions=", ".join(sorted(functions)),
+ ),
+ blocking=True,
+ )
+ ]
+
+ return []
+
+
+@lru_cache(maxsize=LRU_CACHE_MAX_SIZE)
+def is_transform_active(transform: str | None, engine: str) -> bool:
+ """
+ Whether Superset will mirror filters through this transform.
+
+ `validate_transform` with the messages discarded, so the Explore indicator
+ cannot advertise a mapping the save path recorded as inactive. Anything
+ cheaper here would be a second, weaker statement of the same rule, free to
+ drift from the one the save path applies.
+
+ Blocking issues count too. Jinja and non-deterministic transforms are
+ rejected on PUT, but `CreateDatasetCommand` and import do not validate the
+ mapping, so one can still reach the database -- and it would never mirror a
+ filter either.
+
+ Memoized because `partition_filter_mapping_summary` is serialized on every
+ Explore and dashboard load and this parses the transform. The key is
+ everything the answer depends on: `validate_transform` reads no session, no
+ locale and no config beyond `SQL_MAX_PARSE_LENGTH`, which bounds the parser
+ rather than changing a verdict within that bound.
+ """
+ return not validate_transform(transform, engine)
+
+
+def preview_partition_mapping( # pylint: disable=too-many-return-statements
+ datasource: SqlaTable,
+ *,
+ mapped_column: str,
+ value_transform: str | None,
+ sample_values: list[str],
+ operator: FilterOperator = FilterOperator.EQUALS,
+ is_monotonic: bool = False,
+ partition_column: str | None = None,
+) -> dict[str, Any]:
+ """
+ Evaluate a candidate mapping and describe the predicate it would emit.
+
+ Shares the evaluator -- and therefore the probe cache -- with the query
+ path, so preview and runtime cannot drift and a previewed transform warms
+ the chart path for free. The predicate itself comes from
+ `build_mirrored_predicates`, the same builder the query path uses, so
+ operator shapes cannot drift either: what the panel shows is what a chart
+ would emit.
+
+ Validation runs first and the engine second: a half-typed transform is by
+ definition unparseable, so most of what a text input produces costs zero
+ queries.
+
+ Every part of the mapping is taken from the request rather than the stored
+ dataset. The editor previews while the owner is still editing -- a mapping
+ that has to be saved before it can be checked is not a preview.
+ """
+ partition_column = partition_column or datasource.partition_column
+ if not partition_column:
+ return {
+ "valid": False,
+ "reason": "unconfigured",
+ "error": _("No partition column is set."),
+ }
+
+ columns_by_name = {str(column.column_name): column for column in datasource.columns}
+ if mapped_column not in columns_by_name:
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _("%(name)s is not a column on this dataset.", name=mapped_column),
+ }
+
+ # The bail-out `resolve_partition_mapping` makes at query time, and that
+ # `partition_filter_mapping_summary` repeats for the Explore indicator.
+ # Without it here, preview reports a valid emitted predicate for a mapping
+ # no chart will ever mirror -- the one answer a preview panel must not give.
+ if has_active_advanced_data_type(columns_by_name[mapped_column]):
+ return {
+ "valid": False,
+ "reason": "validation",
+ "error": _(
+ "%(name)s has an advanced data type, so its filters are "
+ "translated into their own predicate shape and cannot be "
+ "mirrored onto the partition column.",
+ name=mapped_column,
+ ),
+ }
+
+ engine = datasource.database.backend
+ for issue in validate_partition_mapping(
+ column_names=set(columns_by_name),
+ partition_column=str(partition_column),
+ partition_mapped_column=mapped_column,
+ main_dttm_col=datasource.main_dttm_col,
+ transform=value_transform,
+ engine=engine,
+ ):
+ return {
+ "valid": False,
+ # The parse failure is the one an owner sees constantly, and it is
+ # the only one the mockup gives its own headline to.
+ "reason": (
+ "parse"
+ if issue.field == "partition_value_transform"
+ and not is_parseable(value_transform, engine)
+ else "validation"
+ ),
+ "error": str(issue.message),
+ }
+
+ # The policy every other stored expression goes through. The save path
+ # applies it in `UpdateDatasetCommand._validate_partition_mapping`, but
+ # preview evaluates a candidate transform that has not been saved, so
+ # without this the gate had a door around it. See
+ # `stored_expression_error` for what is being kept out and why.
+ if reason := stored_expression_error(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ cast(str, value_transform),
+ ):
+ return {"valid": False, "reason": "validation", "error": reason}
+
+ mapping = PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=mapped_column,
+ value_transform=cast(str, value_transform),
+ is_monotonic=is_monotonic,
+ equality_is_safe=equality_mirrors_safely(
+ columns_by_name[mapped_column], datasource.database.db_engine_spec
+ ),
+ )
+ sample_input = _render_sample_input(
+ datasource, mapped_column, operator, sample_values
+ )
+
+ if operator not in PREVIEWABLE_OPERATORS:
+ # Checked before `mirrors`, which lets `TEMPORAL_RANGE` through when the
+ # transform is declared monotonic -- and the single sample value would
+ # then reach `handle_comparison_filter`, which has no case for a range
+ # and raises. The request schema rejects it too; this keeps the function
+ # honest for any other caller.
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is mirrored as a pair of bounds, which "
+ "a preview of a single value cannot describe.",
+ operator=operator.value,
+ ),
+ }
+
+ if not mapping.mirrors(operator):
+ return {
+ "valid": False,
+ "reason": "operator",
+ "sample_input": sample_input,
+ "error": _(
+ "A %(operator)s filter is only mirrored when the transform "
+ "preserves ordering, which this one is not declared to do.",
+ operator=operator.value,
+ ),
+ }
+
+ value = _probe_input(
+ datasource, columns_by_name[mapped_column], operator, sample_values
+ )
+ errors: list[str] = []
+ type_errors: list[str] = []
+ predicates = build_mirrored_predicates(
+ datasource,
+ mapping,
+ [(operator, value)],
+ errors=errors,
+ type_errors=type_errors,
+ )
+ if type_errors:
+ # Its own reason, because "the database would not evaluate this" and
+ # "it evaluated and answered with the wrong kind of thing" are
+ # different problems with different fixes, and the owner is the only
+ # one who can tell which transform they meant to write.
+ return {
+ "valid": False,
+ "reason": "type",
+ "sample_input": sample_input,
+ "error": type_errors[0],
+ }
+ if not predicates:
+ return {
+ "valid": False,
+ "reason": "engine",
+ "sample_input": sample_input,
+ "error": (
+ _(
+ "The transform could not be evaluated against the "
+ "database: %(reason)s",
+ reason=errors[0],
+ )
+ if errors
+ else _("The transform could not be evaluated against the database.")
+ ),
+ }
+
+ return {
+ "valid": True,
+ "sample_input": sample_input,
+ "emitted_predicate": _render_predicate(datasource, predicates[0]),
+ }
+
+
+def _probe_input(
+ datasource: SqlaTable,
+ column: "TableColumn",
+ operator: FilterOperator,
+ sample_values: list[str],
+) -> Any:
+ """
+ The sample values as the query path would bind them.
+
+ The request carries samples as strings, and the probe is keyed on exactly
+ what it is handed, so passing them through raw asks the engine a different
+ question from the one a chart asks. A sample of ``2025`` on a numeric
+ column has to arrive as the integer the chart compares: under a transform
+ of ``typeof(:value)`` the raw string previewed ``'text'`` where the chart
+ emitted ``'integer'``. And because `_probe_cache_key` keys on each value's
+ ``repr``, the two also missed each other's cache entirely -- so the "a
+ previewed transform warms the chart path for free" claim in
+ `preview_partition_mapping`'s docstring did not actually hold.
+
+ Coerced by `filter_values_handler`, the same function the query path uses,
+ rather than by a second implementation of the same rules.
+
+ Ranges are not previewable (see `PREVIEWABLE_OPERATORS`), so the bound
+ conversion `_collect_partition_mirror_range` applies -- a ``datetime`` into
+ the column's stored representation -- has no counterpart here.
+ """
+ is_list = operator == FilterOperator.IN
+ column_spec = datasource.db_engine_spec.get_column_spec(native_type=column.type)
+ handled = datasource.filter_values_handler(
+ # `list[str]` is not a `list[FilterValue]` to mypy, invariantly, even
+ # though every `str` is a `FilterValue`.
+ values=cast(FilterValues, sample_values if is_list else sample_values[0]),
+ operator=operator,
+ target_generic_type=(
+ column_spec.generic_type if column_spec else utils.GenericDataType.STRING
+ ),
+ target_native_type=column.type,
+ is_list_target=is_list,
+ db_engine_spec=datasource.db_engine_spec,
+ db_extra=datasource.db_extra,
+ )
+
+ def bindable(value: Any) -> Any:
+ # An epoch-milliseconds sample on a temporal column comes back as
+ # engine SQL rather than a value, and SQL cannot be the value of a bind
+ # parameter -- carried as text so the probe substitutes it, the same way
+ # an array literal is.
+ if isinstance(value, ColumnElement):
+ return raw_probe_value(datasource.database, value)
+ return value
+
+ if is_list and isinstance(handled, (list, tuple)):
+ return [bindable(entry) for entry in handled]
+ return bindable(handled)
+
+
+def _render_sample_input(
+ datasource: SqlaTable,
+ mapped_column: str,
+ operator: FilterOperator,
+ values: list[str],
+) -> str:
+ """
+ The filter being previewed, written the way an owner would read it.
+
+ Display-only -- it is never executed -- but it is still read as SQL, so the
+ column is quoted and the values are rendered by the dialect rather than
+ concatenated raw. A column named ``order date`` would otherwise come out as
+ two bare words.
+ """
+ quoted = datasource.quote_identifier(mapped_column)
+ if operator == FilterOperator.IN:
+ rendered = ", ".join(
+ _render_literal(datasource.database, value) for value in values
+ )
+ return f"{quoted} IN ({rendered})"
+ return (
+ f"{quoted} {operator.value} {_render_literal(datasource.database, values[0])}"
+ )
+
+
+def _render_predicate(datasource: SqlaTable, predicate: ColumnElement[Any]) -> str:
+ """
+ Compile a mirrored predicate to the text a reader would see in View query.
+
+ Every value in it is a probed constant by this point, so ``literal_binds``
+ renders the same literals the chart query carries.
+ """
+ return _compile_literal(predicate, _dialect_for(datasource.database)).replace(
+ "\n", " "
+ )
+
+
+def _render_literal(database: Database, value: Any) -> str:
+ """
+ Render a value the way it appears in the generated SQL.
+
+ Compiled by the dialect rather than formatted by hand. `str()` would render
+ a NULL as the Python repr `None` and leave a date unquoted, neither of which
+ is SQL, and hand-rolled quote-doubling would only ever have been right for
+ strings.
+ """
+ return _compile_literal(sa.literal(value), _dialect_for(database))
+
+
+def build_mirrored_predicates(
+ datasource: SqlaTable,
+ mapping: PartitionMapping,
+ requests: list[tuple[FilterOperator, Any]],
+ *,
+ errors: list[str] | None = None,
+ type_errors: list[str] | None = None,
+) -> list[ColumnElement[Any]]:
+ """
+ Turn collected ``(operator, value)`` mirror requests into predicates.
+
+ ``requests`` is expected to be deduplicated by the caller. Every value is
+ resolved in a single probe round trip -- one per chart query at most -- then
+ emitted as a literal constant, so "View query" shows the reader an ordinary
+ ``WHERE`` clause rather than an inline expression.
+
+ A strict bound is emitted non-strictly; see `mirror_operator`. That happens
+ here, at the one point where a ``FilterOperator`` becomes SQL, rather than
+ at the collection sites in `ExploreMixin`: the preview endpoint calls this
+ directly, so this is what keeps the predicate the editor shows an owner and
+ the predicate the chart carries from disagreeing.
+
+ :param errors: optional sink; see `evaluate_transform`.
+ :param type_errors: optional sink for a probe result the partition column
+ cannot hold -- see `probed_value_type_error`. Separate from ``errors``
+ because the two say different things to an owner: that one is "the
+ database would not evaluate this", and this one is "it evaluated, and
+ answered with the wrong kind of thing".
+ """
+ if not requests:
+ return []
+
+ partition_column = next(
+ (
+ column
+ for column in datasource.columns
+ if column.column_name == mapping.partition_column
+ ),
+ None,
+ )
+ if partition_column is None:
+ return []
+
+ # Flatten every value that needs probing into one list, remembering how many
+ # each request consumed so the results can be handed back out.
+ flat: list[Any] = []
+ spans: list[tuple[FilterOperator, int, int]] = []
+ for operator, value in requests:
+ values = list(value) if operator == FilterOperator.IN else [value]
+ spans.append((operator, len(flat), len(values)))
+ flat.extend(values)
+
+ evaluated = evaluate_transform(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ mapping.value_transform,
+ flat,
+ errors=errors,
+ )
+ if evaluated is None:
+ return []
+
+ if not _bounds_are_ordered(evaluated, spans):
+ return []
+
+ # Declining here is the last chance to decline at all: once these
+ # predicates are in the statement, a value the partition column cannot
+ # hold fails the whole chart rather than its pruning.
+ if reason := probed_value_type_error(partition_column, evaluated):
+ logger.warning(
+ "Partition transform returned a value the partition column cannot "
+ "hold; queries will not prune: %s",
+ reason,
+ )
+ if type_errors is not None:
+ type_errors.append(reason)
+ record_mirror_verdict(
+ datasource.database,
+ datasource.catalog,
+ datasource.schema,
+ mapping.value_transform,
+ mirrors=False,
+ )
+ return []
+
+ sqla_col = datasource.convert_tbl_column_to_sqla_col(partition_column)
+ predicates = _predicates_from_probe(
+ sqla_col, datasource.db_engine_spec, evaluated, spans
+ )
+ if not predicates:
+ return []
+
+ # A comparison against a NULL partition value is NULL, so a row parked in a
+ # NULL partition is dropped by the mirror even when the real filter matches
+ # it -- Hive and Impala's default partition, or a transform that returns
+ # NULL for an input it cannot convert. The mirror only has to be no
+ # narrower than the filter it stands in for, so admitting NULL partitions
+ # keeps those rows. Engines still prune; they read one extra partition.
+ return [sa.or_(sa.and_(*predicates), sqla_col.is_(None))]
+
+
+def _predicates_from_probe(
+ sqla_col: ColumnElement[Any],
+ db_engine_spec: type[BaseEngineSpec],
+ evaluated: list[Any],
+ spans: list[tuple[FilterOperator, int, int]],
+) -> list[ColumnElement[Any]]:
+ """
+ One predicate on the partition column per surviving mirror request.
+
+ A request whose probe answered `None` for any of its values is skipped
+ rather than emitted: `col = NULL` is `NULL`, so it would drop every row the
+ filter keeps. A strict bound is emitted non-strictly; see `mirror_operator`.
+ """
+ predicates: list[ColumnElement[Any]] = []
+ for operator, start, length in spans:
+ chunk = evaluated[start : start + length]
+ if any(value is None for value in chunk):
+ continue
+ if operator == FilterOperator.IN:
+ # The probe answers per value, so a transform over a mixed-number
+ # filter can answer with a mixed-number partition key -- and
+ # `in_` infers the bind type from the first element it is handed.
+ # Without this, probe results of `[33, 29.02]` emit
+ # `IN (33, 29)` and prune away the partition holding `29.02`.
+ predicates.append(sqla_col.in_(normalize_mixed_numbers(chunk)))
+ else:
+ predicates.append(
+ db_engine_spec.handle_comparison_filter(
+ sqla_col, mirror_operator(operator), chunk[0]
+ )
+ )
+ return predicates
+
+
+#: Operators whose value is the lower end of a range, and whose upper-end twins.
+#:
+#: Shared with `ExploreMixin._mirror_probe_input`, which rounds a bound *outward*
+#: where the engine resolves it more coarsely than the filter carries -- backward
+#: for a lower bound, forward for an upper one. Which end an operator names is
+#: the only thing separating the two directions in either caller, so the two have
+#: to agree on it rather than each classify for itself.
+LOWER_BOUND_OPERATORS = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+}
+UPPER_BOUND_OPERATORS = {
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+#: What Python type a probe result may have, per generic type of the partition
+#: column it is about to be compared against.
+#:
+#: Only the types a mismatch can actually break a query with are listed. A
+#: ``STRING`` partition column is deliberately absent: every engine accepts a
+#: number in a text comparison, and refusing one would break a working mapping
+#: for the sake of tidiness. An unresolvable column type is absent for the
+#: stronger reason that there is nothing to check against.
+#: ``numbers.Number`` rather than ``(int, float)``: Postgres answers
+#: ``extract(epoch from ...)`` with a `Decimal`, which is the single commonest
+#: transform this feature has, and an engine is free to answer with any number
+#: type its driver prefers. What the check is for is a *string* where a number
+#: belongs, and every numeric type is equally not that.
+_PROBE_RESULT_TYPES: dict[utils.GenericDataType, tuple[type, ...]] = {
Review Comment:
The exemption for `STRING` partition columns assumes every engine accepts a number in a text comparison, but Postgres rejects `character varying = integer` and strictly typed engines such as Trino reject `varchar = bigint`. With a transform like `CAST(:value AS BIGINT)` against a VARCHAR partition key, this check passes, the preview reports a valid predicate, and the chart query then fails at execution instead of falling back to an unpruned query. Should a numeric probe result against a string partition column be declined (or rendered as text) rather than exempted?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "github-actions[bot] (via GitHub)" <gi...@apache.org>.
github-actions[bot] commented on PR #43870:
URL: https://github.com/apache/superset/pull/43870#issuecomment-6022199399
### ⚠️ Possible DB migration conflict
@hughhhh the base branch `master` picked up a new database migration under `superset/migrations/` after this PR was opened, and this PR adds or modifies migration files too. Alembic migrations form a single linear chain, so if both branch off the same parent revision, merging this PR as-is could leave the migration history with two heads instead of one, which makes `superset db upgrade` fail with `Multiple head revisions are present`.
To check and, if needed, fix this:
1. Rebase this branch onto the latest `master`.
2. Run `superset db heads`. If it lists more than one revision, you have a conflict.
3. In your new migration's script, update `down_revision` (and the `Revises` comment) to point at the other head instead, so the chain has a single head again.
See [Merging DB Migrations](https://superset.apache.org/docs/contributing/development#merging-db-migrations) in the contributing guide for a worked example.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(explore): indicate when a filter is mirrored onto a partition column [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4137602299
##########
superset-frontend/src/explore/components/PartitionPruningIndicator/index.tsx:
##########
@@ -0,0 +1,169 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { t } from '@apache-superset/core/translation';
+import { css, useTheme } from '@apache-superset/core/theme';
+import { NO_TIME_RANGE } from '@superset-ui/core';
+import { Icons, Tooltip } from '@superset-ui/core/components';
+import type { PartitionFilterMapping } from '@superset-ui/chart-controls';
+import { ExpressionTypes } from 'src/explore/components/controls/FilterControl/types';
+
+interface PartitionPruningIndicatorProps {
+ /** The dataset's mapping summary, straight off the datasource payload. */
+ mapping?: PartitionFilterMapping | null;
+}
+
+/**
+ * The parts of an ad-hoc filter that decide whether it is mirrored. Structural
+ * rather than the `AdhocFilter` class so native filters and cross-filters --
+ * which reach the query path in the same shape but are not that class -- can be
+ * checked with the same function.
+ */
+export interface MirrorCandidateFilter {
+ expressionType?: string;
+ subject?: string | { column_name?: string } | null;
+ operator?: string | null;
+ comparator?: unknown;
+}
+
+/**
+ * The glyph on a filter whose column is mirrored onto a partition column
+ * (wireframe 1d).
+ *
+ * Chart authors do not configure any of this and ideally never learn the word
+ * "partition"; the indicator exists only to explain why their query got faster,
+ * and to point at the generated SQL where the extra predicate is visible.
+ */
+export default function PartitionPruningIndicator({
+ mapping,
+}: PartitionPruningIndicatorProps) {
+ const theme = useTheme();
+
+ if (!mapping?.active) {
+ return null;
+ }
+
+ return (
+ <Tooltip
+ placement="top"
+ title={t(
+ 'This filter is also applied to a partition column for faster queries. See "View query" for the generated SQL.',
+ )}
+ >
+ <span data-test="partition-pruning-indicator">
+ <Icons.FilterOutlined
+ iconSize="s"
+ iconColor={theme.colorSuccess}
+ css={css`
+ margin-left: ${theme.sizeUnit}px;
+ vertical-align: middle;
+ `}
+ />
+ </span>
+ </Tooltip>
+ );
+}
+
+/**
+ * The filter's column name. `subject` is a bare string for simple filters and a
+ * column object when the filter was built from a dropped column.
+ */
+function subjectName(
+ subject: MirrorCandidateFilter['subject'],
+): string | undefined {
+ return typeof subject === 'string'
+ ? subject
+ : (subject?.column_name ?? undefined);
+}
+
+/**
+ * Whether `columnName` is the one column the mapping mirrors.
+ *
+ * Necessary but not sufficient for the glyph -- see `isMirroredFilter`.
+ */
+export function isMirroredColumn(
+ mapping: PartitionFilterMapping | null | undefined,
+ columnName: string | null | undefined,
+): boolean {
+ return Boolean(
+ mapping?.active && columnName && mapping.mapped_column === columnName,
+ );
+}
+
+/**
+ * Whether the comparator is one the mirrored predicate can be built from.
+ *
+ * A `NULL` inside an `IN` list widens the real predicate to
+ * `col IS NULL OR col IN (...)`, which the mirror cannot express, so the
+ * backend skips those lists outright.
+ */
+function hasMirrorableValue(operator: string, comparator: unknown): boolean {
+ if (operator === 'TEMPORAL_RANGE') {
+ // `No filter` resolves to neither bound, so no range is mirrored.
+ return typeof comparator === 'string' && comparator !== NO_TIME_RANGE;
+ }
+ if (operator === 'IN') {
+ return (
+ Array.isArray(comparator) &&
+ comparator.length > 0 &&
+ !comparator.some(value => value == null)
+ );
+ }
+ return comparator !== null && comparator !== undefined && comparator !== '';
+}
+
+/**
+ * Whether this filter actually produces a predicate on the partition column.
+ *
+ * Naming the mapped column is only the first of the query path's gates
+ * (`_collect_partition_mirror_filter` in `superset/models/helpers.py`): the
+ * operator has to be one the mapping can mirror, and the value has to be one
+ * the mirrored predicate can carry. A `country != 'US'` chip names the mapped
+ * column and mirrors nothing -- negations are never safe, because the transform
+ * need not be injective -- so labelling it would promise a speed-up the query
+ * does not deliver.
+ *
+ * The operator list is not restated here; it is computed server-side from the
+ * transform's declared monotonicity and shipped on the mapping.
+ */
+export function isMirroredFilter(
Review Comment:
A virtual dataset's SQL can consume a filter via a Jinja `get_filters('col', remove_filter=True)` (or `get_time_filter(..., remove_filter=True)`) template call; the query builder then skips both the filter's own predicate and any partition mirror for that column entirely (`should_skip_filter` in `superset/models/helpers.py`). This function only looks at the filter's own shape, so it still shows the glyph for a filter on the mapped column that produces no SQL predicate at all in that case. Could this account for `removed_filters`, or is that out of scope for the indicator?
##########
superset-frontend/src/explore/components/PartitionPruningIndicator/index.tsx:
##########
@@ -0,0 +1,169 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { t } from '@apache-superset/core/translation';
+import { css, useTheme } from '@apache-superset/core/theme';
+import { NO_TIME_RANGE } from '@superset-ui/core';
+import { Icons, Tooltip } from '@superset-ui/core/components';
+import type { PartitionFilterMapping } from '@superset-ui/chart-controls';
+import { ExpressionTypes } from 'src/explore/components/controls/FilterControl/types';
+
+interface PartitionPruningIndicatorProps {
+ /** The dataset's mapping summary, straight off the datasource payload. */
+ mapping?: PartitionFilterMapping | null;
+}
+
+/**
+ * The parts of an ad-hoc filter that decide whether it is mirrored. Structural
+ * rather than the `AdhocFilter` class so native filters and cross-filters --
+ * which reach the query path in the same shape but are not that class -- can be
+ * checked with the same function.
+ */
+export interface MirrorCandidateFilter {
+ expressionType?: string;
+ subject?: string | { column_name?: string } | null;
+ operator?: string | null;
+ comparator?: unknown;
+}
+
+/**
+ * The glyph on a filter whose column is mirrored onto a partition column
+ * (wireframe 1d).
+ *
+ * Chart authors do not configure any of this and ideally never learn the word
+ * "partition"; the indicator exists only to explain why their query got faster,
+ * and to point at the generated SQL where the extra predicate is visible.
+ */
+export default function PartitionPruningIndicator({
+ mapping,
+}: PartitionPruningIndicatorProps) {
+ const theme = useTheme();
+
+ if (!mapping?.active) {
+ return null;
+ }
+
+ return (
+ <Tooltip
+ placement="top"
+ title={t(
+ 'This filter is also applied to a partition column for faster queries. See "View query" for the generated SQL.',
+ )}
+ >
+ <span data-test="partition-pruning-indicator">
Review Comment:
The tooltip's explanation is reachable only by mouse hover: the icon sits in a non-focusable `<span>` with no accessible name, so a keyboard or screen-reader user has no way to discover why the glyph is there. Could this add a focusable target with an accessible label (e.g. an `aria-label` matching the tooltip text)?
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/useDebouncedCommit.ts:
##########
@@ -0,0 +1,85 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { debounce } from 'lodash-es';
+import { Constants } from '@superset-ui/core/components';
+
+/**
+ * Local text state that commits upward on a debounce.
+ *
+ * The dataset editor's commit path is asynchronous and snapshot-based: a value
+ * handed to `onChange` travels Field -> Fieldset -> CollectionTable ->
+ * DatasourceEditor -> DatasourceModal and arrives back on the `value` prop
+ * several renders later, and the callback that commits it was built during an
+ * earlier render. An input driven straight off that prop therefore loses any
+ * keystroke that lands while a commit is in flight -- which is why every other
+ * control in the editor types into local state and commits on a debounce, and
+ * why Fieldset's own comment says the editor assumes exactly that. This is
+ * TextControl's contract (src/explore/components/controls/TextControl), minus
+ * the ControlHeader and the number parsing this field does not want.
+ */
+export function useDebouncedCommit(
+ value: string | null | undefined,
+ commit: (next: string) => void,
+ delay: number = Constants.FAST_DEBOUNCE,
+) {
+ const [localValue, setLocalValue] = useState(value ?? '');
+ const [prevValue, setPrevValue] = useState(value);
+
+ // The commit fires from a timer, so the callback is handed in at call time
Review Comment:
This comment says the commit callback reads the column's monotonic flag to decide what to write, but `commit` here is just the plain `(next: string) => void` passed in by the caller -- this hook doesn't reference monotonicity anywhere. Looks like a leftover from an earlier, more specific version of this code; could this be corrected or removed?
##########
superset/daos/dataset.py:
##########
@@ -476,6 +484,48 @@ def _validate_column_date_formats(
"python_date_format is an invalid date/timestamp format."
)
+ @staticmethod
+ def clear_unmapped_partition_transforms(model: SqlaTable) -> None:
+ """
+ Drop the value transform from every column the mapping does not mirror.
+
+ A mapping has exactly one mirrored column, so at most one column may
+ carry a transform. A transform parked on any other column is invisible
+ -- no row but the mapped one renders one -- yet it is still stored, and
+ it goes live the moment the mapped column resolves back to it. Clearing
+ an override is enough to do that: a null `partition_mapped_column` means
+ "follow `main_dttm_col`", so dropping a mapping would otherwise activate
+ whatever the default datetime column happened to be holding, turning a
+ request to remove a mapping into a request to add a different one.
+
+ Enforced here rather than in the editor alone because the editor is only
+ one writer: a PUT, an `override_columns=true` metadata sync and an
+ import all reach the columns directly. The same argument
+ `clear_dangling_partition_mapping` makes about dangling columns.
+
+ Gated on the feature flag, unlike its sibling, because this discards
+ stored configuration rather than repairing a broken reference. With the
+ flag off nothing mirrors, so there is no armed mapping to disarm and
+ clearing would be pure loss.
+ """
+ if not feature_flag_manager.is_feature_enabled(PARTITION_FILTER_MAPPING_FLAG):
+ return
+
+ mapped_column = (
+ (model.partition_mapped_column or model.main_dttm_col)
+ if model.partition_column
+ else None
+ )
+ for column in model.columns:
Review Comment:
Concretely: `_upsert_columns` and `_override_columns` attach a brand-new column via `db.session.add(TableColumn(..., table_id=model.id))` rather than through the `columns` relationship, and both already read `model.columns` earlier in the same call to build their by-id/by-name maps. When that collection was loaded before the insert, the new row isn't reflected in it when this loop runs right after -- so a single request that both adds a column with a `partition_value_transform` and points the mapping elsewhere leaves that transform stored and uncleared, and it goes live the moment the mapping later resolves back to that column. `tests/unit_tests/dao/dataset_test.py` already notes this relationship-cache gap for a different reason (see its comment near line 394). Could this loop read from the same collection the insert path writes to, or expire `model.columns` first?
##########
superset-frontend/src/explore/components/PartitionPruningIndicator/index.tsx:
##########
@@ -0,0 +1,169 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { t } from '@apache-superset/core/translation';
+import { css, useTheme } from '@apache-superset/core/theme';
+import { NO_TIME_RANGE } from '@superset-ui/core';
+import { Icons, Tooltip } from '@superset-ui/core/components';
+import type { PartitionFilterMapping } from '@superset-ui/chart-controls';
+import { ExpressionTypes } from 'src/explore/components/controls/FilterControl/types';
+
+interface PartitionPruningIndicatorProps {
+ /** The dataset's mapping summary, straight off the datasource payload. */
+ mapping?: PartitionFilterMapping | null;
+}
+
+/**
+ * The parts of an ad-hoc filter that decide whether it is mirrored. Structural
+ * rather than the `AdhocFilter` class so native filters and cross-filters --
+ * which reach the query path in the same shape but are not that class -- can be
+ * checked with the same function.
+ */
+export interface MirrorCandidateFilter {
+ expressionType?: string;
+ subject?: string | { column_name?: string } | null;
+ operator?: string | null;
+ comparator?: unknown;
+}
+
+/**
+ * The glyph on a filter whose column is mirrored onto a partition column
+ * (wireframe 1d).
+ *
+ * Chart authors do not configure any of this and ideally never learn the word
+ * "partition"; the indicator exists only to explain why their query got faster,
+ * and to point at the generated SQL where the extra predicate is visible.
+ */
+export default function PartitionPruningIndicator({
+ mapping,
+}: PartitionPruningIndicatorProps) {
+ const theme = useTheme();
+
+ if (!mapping?.active) {
+ return null;
+ }
+
+ return (
+ <Tooltip
+ placement="top"
+ title={t(
+ 'This filter is also applied to a partition column for faster queries. See "View query" for the generated SQL.',
+ )}
+ >
+ <span data-test="partition-pruning-indicator">
+ <Icons.FilterOutlined
+ iconSize="s"
+ iconColor={theme.colorSuccess}
+ css={css`
+ margin-left: ${theme.sizeUnit}px;
+ vertical-align: middle;
+ `}
+ />
+ </span>
+ </Tooltip>
+ );
+}
+
+/**
+ * The filter's column name. `subject` is a bare string for simple filters and a
+ * column object when the filter was built from a dropped column.
+ */
+function subjectName(
+ subject: MirrorCandidateFilter['subject'],
+): string | undefined {
+ return typeof subject === 'string'
+ ? subject
+ : (subject?.column_name ?? undefined);
+}
+
+/**
+ * Whether `columnName` is the one column the mapping mirrors.
+ *
+ * Necessary but not sufficient for the glyph -- see `isMirroredFilter`.
+ */
+export function isMirroredColumn(
+ mapping: PartitionFilterMapping | null | undefined,
+ columnName: string | null | undefined,
+): boolean {
+ return Boolean(
+ mapping?.active && columnName && mapping.mapped_column === columnName,
+ );
+}
+
+/**
+ * Whether the comparator is one the mirrored predicate can be built from.
+ *
+ * A `NULL` inside an `IN` list widens the real predicate to
+ * `col IS NULL OR col IN (...)`, which the mirror cannot express, so the
+ * backend skips those lists outright.
+ */
+function hasMirrorableValue(operator: string, comparator: unknown): boolean {
+ if (operator === 'TEMPORAL_RANGE') {
+ // `No filter` resolves to neither bound, so no range is mirrored.
+ return typeof comparator === 'string' && comparator !== NO_TIME_RANGE;
+ }
+ if (operator === 'IN') {
+ return (
+ Array.isArray(comparator) &&
+ comparator.length > 0 &&
+ !comparator.some(value => value == null)
+ );
+ }
+ return comparator !== null && comparator !== undefined && comparator !== '';
Review Comment:
`hasMirrorableValue` treats an empty string as not mirrorable (`comparator !== ''`), but the backend's mirror collector (`_collect_partition_mirror_filter` in `superset/models/helpers.py`) only excludes `None`, not `''`. A valid `column == ''` filter is mirrored server-side while Explore hides the indicator for it. Could this align with the backend's null-only exclusion?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -416,7 +416,7 @@ def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
if not _transform_is_usable(transform, datasource.database.backend):
Review Comment:
This trusts `_transform_is_usable` as the gate for real query-time mirroring, but that function (below) doesn't call `find_non_deterministic_functions`, while `validate_transform` (used both for PUT-time validation and for `is_transform_active`, which drives the Explore indicator) treats a non-deterministic function as blocking. Since import and `CreateDatasetCommand` don't run `validate_partition_mapping`, a transform calling e.g. `NOW()` can reach the database, be treated as usable here, and mirror filters with a value frozen at whatever moment the probe/query happened to run -- while Explore's own indicator correctly identifies it as inactive and shows no glyph, so there's no visible signal that mirroring is happening with a non-deterministic value. Could `_transform_is_usable` share the same check?
##########
superset-frontend/packages/superset-ui-chart-controls/src/shared-controls/sharedControls.tsx:
##########
@@ -208,9 +208,68 @@ const time_grain_sqla: SharedControlConfig<'SelectControl'> = {
sortComparator: () => 0, // Disable frontend sorting to preserve backend order
};
+/**
+ * The mapping to hand the time control's partition-pruning indicator, or `null`
+ * when this time range is not mirrored.
+ *
+ * The control renders whatever mapping it is given, so the applicability check
+ * belongs here, where the selected temporal column and the range are both in
+ * scope. Unlike an ad-hoc filter chip the control names no column of its own:
+ * the query path mirrors the time range only when the *chart's* temporal column
+ * is the mapped one (`superset/models/helpers.py`, the `granularity` and
+ * `always_filter_main_dttm` branches), and only when the range resolves to at
+ * least one bound -- `No filter` resolves to neither.
+ */
+function timeRangePartitionMapping({
+ datasource,
+ form_data: formData,
+}: ControlPanelState) {
+ const dataset = datasource as Dataset | null;
+ const mapping = dataset?.partition_filter_mapping;
+ if (
+ !mapping?.active ||
+ !mapping.mirrorable_operators?.includes('TEMPORAL_RANGE')
+ ) {
+ return null;
+ }
+ if (formData?.time_range === NO_TIME_RANGE) {
Review Comment:
This checks `formData?.time_range === NO_TIME_RANGE`, but when `time_range` is simply absent from `form_data` (e.g. a legacy saved chart predating this control, or before defaults populate the state), the value is `undefined` rather than the sentinel, so this falls through to the mirrors-check below instead of returning null. Could a missing `time_range` be treated the same as `NO_TIME_RANGE` here?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4224320545
##########
superset/views/datasource/views.py:
##########
@@ -87,6 +95,109 @@ def _load_dataset_for_samples(
return dataset, None
+def _partition_transform_error(
+ orm_datasource: Any,
+ datasource_dict: dict[str, Any],
+) -> str | None:
+ """
+ The first column whose incoming value transform may not be stored, if any.
+
+ Only datasets carry a partition mapping, and only a transform the request
+ actually changes is worth refusing over -- re-sending a value already in
+ storage is what a GET-then-PUT client does, and a transform stored before
+ this check existed is disarmed at probe time instead.
+ """
+ incoming = [
+ column
+ for column in datasource_dict.get("columns") or []
+ if column.get("partition_value_transform")
+ ]
+ database = getattr(orm_datasource, "database", None)
+ if not incoming or database is None:
+ return None
+
+ stored = {
+ column.column_name: column.partition_value_transform
+ for column in orm_datasource.columns
+ }
+ for column in incoming:
+ transform = column["partition_value_transform"]
+ if transform == stored.get(column.get("column_name")):
+ continue
+ if reason := stored_expression_error(
Review Comment:
The legacy save only runs `stored_expression_error` on a changed transform, while the REST path and the import path also reach `validate_transform`, where the nondeterministic-function check is blocking. A transform such as `random() + :value` is saved here with a 200, and then even a description-only `PUT /api/v1/dataset/<pk>` fails validation on the persisted transform, so the dataset can't be saved again until the transform is edited. Should this also reject a changed transform that `validate_transform` flags as blocking?
##########
superset/models/helpers.py:
##########
@@ -4292,36 +4389,644 @@ def dttm_sql_literal(self, dttm: datetime, col: "TableColumn") -> str:
return f"""'{dttm.strftime("%Y-%m-%d %H:%M:%S.%f")}'"""
- def get_time_filter( # pylint: disable=too-many-arguments # noqa: C901
+ def _mirror_probe_value(self, dttm: datetime, col: Optional["TableColumn"]) -> Any:
+ """
+ ``dttm`` in the mapped column's own stored representation.
+
+ The predicate this mirror stands in for compares the column against
+ `dttm_sql_literal(dttm, col)`, so the transform has to be probed with
+ the same value. On a column stored as an epoch integer, ``T`` is a
+ function of an integer: probing it with a `datetime` either returns
+ something unrelated to the partition keys or raises, and a raise costs
+ the dataset its pruning silently.
+
+ Only the ``python_date_format`` branches of `dttm_sql_literal` are
+ reproduced, because only those produce a *value*. `convert_dttm` yields
+ engine-specific SQL text, which cannot be bound as a parameter; its own
+ divergence from the probe is handled by widening the bounds instead
+ (`_engine_literal_resolution`).
+
+ In `dttm_sql_literal`'s own order, though: it asks ``convert_dttm``
+ first and reaches the format only when the engine answers nothing. A
+ column can carry both -- a TIMESTAMP with a ``%Y%m%d``
+ ``python_date_format``, or an entry in
+ ``python_date_format_by_column_name`` -- and applying the format
+ unconditionally probed a value the real predicate never compares.
+ ``event_time >= '2026-01-01 00:00:00'`` mirrored as
+ ``partition_col >= '20260101'``, and a January 15 row keyed
+ ``2026-01-15`` sorts below that string, so the chart lost a row the
+ filter keeps.
+
+ Where the engine does answer, the `datetime` is returned unchanged and
+ the widening path takes over -- which is exactly what already happens
+ for every temporal column that carries no format at all.
+ """
+ if col is None:
+ return dttm
+
+ if col.type and self.db_engine_spec.convert_dttm(
+ col.type, dttm, db_extra=self.db_extra
+ ):
+ # The format is unreachable in `dttm_sql_literal` for this column,
+ # so reproducing it here would describe a different bound.
+ return dttm
+
+ tf = col.python_date_format
+ if not tf and self.db_extra:
+ tf = self.db_extra.get("python_date_format_by_column_name", {}).get(
+ col.column_name
+ )
+ if not tf:
+ return dttm
+
+ if tf in EPOCH_FORMATS:
+ dttm_tz_aware = dttm
+ if dttm_tz_aware.tzinfo is None:
+ dttm_tz_aware = dttm_tz_aware.replace(tzinfo=timezone.utc)
+ return int(dttm_tz_aware.timestamp()) * EPOCH_FORMATS[tf]
+ return dttm.strftime(tf)
+
+ def _engine_literal_resolution(
+ self, dttm: datetime, col: Optional["TableColumn"]
+ ) -> LiteralResolution:
+ """
+ How much of ``dttm`` survives into this engine's literal for ``col``.
+
+ The real predicate compares `dttm_sql_literal(dttm, col)`, so whatever
+ that literal throws away is a bound the engine never sees. A mirror
+ derived from the full precision then describes a *narrower* range than
+ the predicate it stands in for -- and narrower means it drops rows the
+ filter keeps.
+
+ Two things get thrown away in practice:
+
+ - the sub-second part. SQLite renders a timestamp with
+ ``timespec="seconds"``.
+ - the time of day entirely. Every engine spec with a ``types.Date``
+ branch renders ``dttm.date().isoformat()``, so Presto, Trino,
+ BigQuery and some two dozen others answer `DATE '2026-01-01'` for a
+ bound of 10:00 -- and `T(DATE '2026-01-01')` is below the mirror's
+ own lower bound, so the whole first day is dropped.
+
+ Detected rather than enumerated per engine, because the branch depends
+ on the column's type as well as the spec: instants differing only in the
+ part under test render as the same text exactly when the engine has
+ thrown that part away.
+
+ The day test uses two fixed times of day rather than ``dttm`` and one
+ alternative, so a bound that happens to sit on the hour the alternative
+ uses cannot read as "no time at all". Neither probe sits at midnight on
+ purpose: SQLite renders a DATE column at exactly midnight as a bare
+ date, so a midnight probe would differ from its alternative for a
+ reason that has nothing to do with resolution.
+
+ Likewise both sub-second probes carry a non-zero remainder. Comparing
+ against ``dttm`` truncated to the second looks like the obvious test and
+ is wrong for the same formatting-boundary reason.
+ """
+ if col is None or not col.type:
+ return LiteralResolution.FULL
+
+ def render(moment: datetime) -> Optional[str]:
+ return self.db_engine_spec.convert_dttm(
+ col.type, moment, db_extra=self.db_extra
+ )
+
+ try:
+ early = render(dttm.replace(hour=1, minute=2, second=3, microsecond=444444))
+ late = render(
+ dttm.replace(hour=22, minute=33, second=44, microsecond=555555)
+ )
+ if early is not None and early == late:
+ return LiteralResolution.DAY
+
+ # Flooring to the second is a no-op on a bound that has no
+ # sub-second part, so there is nothing to detect.
+ if not dttm.microsecond:
+ return LiteralResolution.FULL
+
+ first = render(dttm.replace(microsecond=111111))
+ second = render(dttm.replace(microsecond=222222))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return LiteralResolution.FULL
+
+ if first is not None and first == second:
+ return LiteralResolution.SECOND
+ return LiteralResolution.FULL
+
+ def _round_bounds_outward(
self,
- time_col: "TableColumn",
+ start_dttm: Optional[datetime],
+ end_dttm: Optional[datetime],
+ col: Optional["TableColumn"],
+ ) -> tuple[Optional[datetime], Optional[datetime]]:
+ """
+ The bounds widened to whatever the engine's literal actually resolves to.
+
+ Rounding outward is never narrower than the predicate being mirrored,
+ which is the only property the mirror has to hold.
+ """
+ resolutions = {
+ self._engine_literal_resolution(bound, col)
+ for bound in (start_dttm, end_dttm)
+ if bound is not None
+ }
+
+ if LiteralResolution.DAY in resolutions:
+ # The engine compares a bare date, so the real predicate's lower
+ # bound is the start of that day and its upper bound admits the
+ # whole of the day before. Anything finer excludes rows it keeps.
+ if start_dttm is not None:
+ start_dttm = start_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ )
+ if end_dttm is not None and end_dttm != end_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ ):
+ end_dttm = end_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ ) + timedelta(days=1)
+ elif LiteralResolution.SECOND in resolutions:
+ if start_dttm is not None:
+ start_dttm = start_dttm.replace(microsecond=0)
+ if end_dttm is not None and end_dttm.microsecond:
+ end_dttm = end_dttm.replace(microsecond=0) + timedelta(seconds=1)
+
+ return start_dttm, end_dttm
+
+ def _literal_is_coarser_than(
+ self, dttm: datetime, col: Optional["TableColumn"]
+ ) -> bool:
+ """
+ Whether the engine's literal for ``dttm`` throws away part of it.
+
+ Unlike a range, an equality cannot be widened outward, so the only safe
+ answer when the engine compares less than the full value is to decline
+ the mirror.
+ """
+ resolution = self._engine_literal_resolution(dttm, col)
+ if resolution is LiteralResolution.DAY:
+ return dttm != dttm.replace(hour=0, minute=0, second=0, microsecond=0)
+ if resolution is LiteralResolution.SECOND:
+ return bool(dttm.microsecond)
+ return False
+
+ def _column_literal_resolution(
+ self, col: Optional["TableColumn"]
+ ) -> LiteralResolution:
+ """
+ How much of *any* value this engine compares on ``col``.
+
+ `_engine_literal_resolution` answers about a particular instant, which
+ is what a mirror derived from one needs. Two callers have no instant to
+ ask about -- the summary the Explore glyph reads, and a filter value
+ `_instant_from_filter_value` cannot read as an instant at all -- and
+ both need the column's own answer. Through one helper so that the glyph
+ and the query path cannot disagree about which column is coarse, which
+ is the same reason `mirrorable_operators` is computed once.
+
+ A non-temporal column has no answer, and asking anyway gets a wrong one:
+ SQLite's ``convert_dttm`` renders for ``types.String`` as well as for the
+ date types, so a reference instant makes a ``VARCHAR`` mapped column look
+ second-resolution -- and ``country = 'US'``, the text half of this
+ feature, reads as a value the engine compares coarsely. The per-instant
+ callers never meet this, because they arrive only with a value that
+ parsed as an instant.
+ """
+ if col is None or not col.is_dttm:
+ return LiteralResolution.FULL
+ return self._engine_literal_resolution(_RESOLUTION_REFERENCE_INSTANT, col)
+
+ def _round_bound_outward(
+ self,
+ instant: datetime,
+ col: Optional["TableColumn"],
+ *,
+ is_upper: bool,
+ ) -> datetime:
+ """
+ One bound widened to whatever the engine resolves ``col`` to.
+
+ `_round_bounds_outward` answers for a since/until pair, because a time
+ range is the shape it was written for. A single comparison is one end of
+ such a pair with the other end absent, and the widening is per-end
+ already -- a lower bound moves back, an upper bound forward.
+
+ Narrowing the return type is the other half of the point: a bound handed
+ in non-`None` comes back non-`None`, and saying so here saves every
+ caller from re-establishing it.
+ """
+ start_dttm, end_dttm = self._round_bounds_outward(
+ None if is_upper else instant,
+ instant if is_upper else None,
+ col,
+ )
+ rounded = end_dttm if is_upper else start_dttm
+ return rounded if rounded is not None else instant
+
+ def _mirror_probe_input(
+ self,
+ operator: utils.FilterOperator,
+ value: Any,
+ col: Optional["TableColumn"],
+ ) -> Any:
+ """
+ ``value`` in the representation the mirror may probe the transform at.
+
+ A simple filter on a temporal column carries a *string*.
+ `filter_values_handler` rewrites only an all-digit value, which it reads
+ as epoch milliseconds, so ``'2026-07-06 10:08:11'`` reaches here exactly
+ as the chart author typed it and is bound as text. The engine compares
+ that text against the column under its own cast, and on a ``DATE``
+ column the cast drops the time of day: the filter keeps the whole of
+ 2026-07-06 while a mirror probed at 10:08:11 keeps one instant of it,
+ which is narrower than the predicate it stands in for.
+
+ So the text is read back into the instant it denotes -- the only way
+ `_engine_literal_resolution`, which answers about a `datetime`, reaches
+ a filter value at all -- and where the engine compares less of that
+ instant than the filter carries, what to do about it is a property of
+ the *operator*:
+
+ * a bound rounds outward, through the helper the range collector uses.
+ Reading one extra bucket at the edge is the trade this feature makes
+ everywhere else too -- see `mirror_operator` -- and the original
+ predicate is still in the query to exclude the rows that bucket adds.
+ * an equality, or one member of an ``IN`` list, has nowhere to widen to.
+ These entries are ``AND``-ed onto the query, so "or the day either
+ side" is not something this sink can express, and the request is
+ declined with `_UNMIRRORABLE`. The query is then correct and unpruned,
+ which is the one failure mode this feature is allowed.
+
+ An instant carrying a UTC offset is declined for every operator, a
+ bound included. Rounding one outward would first have to place it in the
+ frame the partition column was written in, and guessing that frame is
+ how a mirror ends up a whole offset narrower than the filter -- see the
+ load-bearing assumption in
+ `superset.connectors.sqla.partition_mapping`.
+
+ A *string* `_instant_from_filter_value` cannot read at all is declined on
+ the same terms, and for the same reason one more step back: there is no
+ instant to round. ``'07/06/2026 10:08:11'`` is not ISO 8601, so the
+ parser leaves it alone -- and Postgres casts that same text to a DATE and
+ keeps the whole of July 6 while the probe, handed the string verbatim,
+ evaluates the transform at 10:08:11 and asks for a partition key no row
+ holds. That is exactly the narrowing the ISO-only parser was written to
+ prevent, reached through a value it declines to read, so the decline has
+ to travel with it. Which costs a non-ISO *date* its pruning too, because
+ telling July 6 from June 7 is the guess that started this.
+
+ Only a string. `_as_probe_input` has already run, so the engine SQL
+ `filter_values_handler` returns for an epoch-millisecond bound arrives
+ here as a `RawProbeValue` rather than text -- and that literal was
+ rendered by the engine at the engine's own resolution, so it is the one
+ thing on this path with nothing left to resolve.
+
+ Where the engine compares the whole instant, a string is returned
+ exactly as it arrived -- down to the type the probe binds and the cache
+ key it lands on, because every query that was already correct has to
+ stay byte-for-byte correct. A `datetime` is still converted, which it
+ has always needed: on a column stored as an epoch integer the transform
+ is a function of an integer, and a `datetime` is not the value the real
+ predicate compares.
+ """
+ parsed = _instant_from_filter_value(value)
+ if parsed is None:
+ if (
+ isinstance(value, str)
+ and self._column_literal_resolution(col) is not LiteralResolution.FULL
+ ):
+ return _UNMIRRORABLE
+ return value
+
+ if (
+ self._engine_literal_resolution(parsed.replace(tzinfo=None), col)
Review Comment:
This rounds the bound for any mapped column whose engine renders datetimes, not only temporal ones. SQLite's `convert_dttm` renders for VARCHAR as well (the note on `_column_literal_resolution` calls this out and that helper guards on `is_dttm`). With VARCHAR `code` and `p`, a monotonic `:value` transform, a row `code = p = '2026-07-06T09:00:00'` and the filter `code < '2026-07-06T10:08:11.500000'`, the bound is rounded to 10:08:12 and `p <= '2026-07-06 10:08:12.000000'` is added; the space sorts before `T`, so the matching row is dropped from the mirrored query. Should this skip the resolution/rounding path for a non-temporal column the same way `_column_literal_resolution` does?
##########
superset/commands/dataset/importers/v1/utils.py:
##########
@@ -582,6 +734,27 @@ def import_dataset( # noqa: C901
if dataset.id is None:
db.session.flush()
+ # A bundle can name a mapped column and still carry transforms on other
+ # columns; the editor's client-side guard never runs here. Left in place, a
+ # transform on an unmirrored column is invisible and still stored, ready to
+ # go live the moment the mapped column resolves back to it.
+ DatasetDAO.clear_unmapped_partition_transforms(dataset)
+
+ # And repair a reference the import itself broke: a `sync` deletion can
+ # remove the column `partition_column` names, which otherwise leaves the
+ # dataset failing `UpdateDatasetCommand`'s validation on every later edit --
+ # including a description-only PUT, which carries no columns payload and so
+ # cannot reach the forgiveness branch that tolerates a stored-only dangle.
+ #
+ # Flushed and expired first: the `sync` deletion is still pending here, and
+ # reading the relationship without flushing loads the removed rows back and
+ # un-deletes them.
+ db.session.flush()
+ db.session.expire(dataset, ["columns"])
+ DatasetDAO.clear_dangling_partition_mapping(
Review Comment:
This cleanup only drops references to columns that no longer exist. A bundle that sets both `partition_column` and `partition_mapped_column` to `event_time` imports fine, but the mapping validation treats an explicit self-mapping as blocking, so a later description-only PUT on that dataset fails until someone repairs the mapping. Should import clear (or reject) a mapping where the two columns are equal, in line with the dangling-reference repair here?
##########
tests/unit_tests/connectors/sqla/partition_mapping_test.py:
##########
@@ -0,0 +1,2512 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""Unit tests for ``superset.connectors.sqla.partition_mapping``."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from decimal import Decimal
+from importlib import import_module
+from typing import Any, cast
+from unittest.mock import MagicMock, patch, PropertyMock
+
+import pandas as pd
+import pytest
+from dateutil.relativedelta import relativedelta
+from flask import Flask
+from sqlalchemy.dialects import mysql, postgresql
+
+from superset.config import DISALLOWED_SQL_FUNCTIONS
+from superset.connectors.sqla.models import SqlaTable, TableColumn
+from superset.connectors.sqla.partition_mapping import (
+ _mirror_verdict_cache_key,
+ _placeholder_is_bindable,
+ _probe_cache_key,
+ _reads_as_temporal,
+ _render_literal,
+ build_mirrored_predicates,
+ build_probe_sql,
+ contains_executable_comment,
+ contains_jinja,
+ contains_value_placeholder,
+ drop_unmapped_value_transforms,
+ equality_mirrors_safely,
+ evaluate_transform,
+ find_non_deterministic_functions,
+ grain_bucket_width,
+ GRAIN_BUCKET_WIDTHS,
+ is_bare_expression,
+ is_parseable,
+ is_transform_active,
+ is_unfinished,
+ known_mirror_verdict,
+ MappingValidationIssue,
+ mirror_operator,
+ MIRRORABLE_ALWAYS,
+ MIRRORABLE_IF_MONOTONIC,
+ mirrorable_operators,
+ parse_error_detail,
+ placeholder_is_executable,
+ probe_sql_is_evaluable,
+ probed_value_type_error,
+ RawProbeValue,
+ resolve_partition_mapping,
+ stored_expression_error,
+ validate_partition_mapping,
+ validate_transform,
+)
+from superset.constants import TimeGrain
+from superset.db_engine_specs.base import BaseEngineSpec
+from superset.db_engine_specs.oracle import OracleEngineSpec
+from superset.models.core import Database
+from superset.sql.parse import SQLStatement
+from superset.utils.core import FilterOperator, override_user
+
+
+@pytest.fixture(autouse=True)
+def real_probe_cache(app: Flask) -> Any:
+ """
+ The test app runs a null cache, which would make every cache assertion here
+ vacuously pass. Swap in a real in-memory one for the duration.
+ """
+ from flask_caching import Cache
+
+ from superset.extensions import cache_manager
+
+ cache = Cache(config={"CACHE_TYPE": "SimpleCache", "CACHE_DEFAULT_TIMEOUT": 300})
+ cache.init_app(app)
+ original = cache_manager._cache # noqa: SLF001
+ cache_manager._cache = cache # noqa: SLF001
+ yield
+ cache_manager._cache = original # noqa: SLF001
+
+
+@pytest.fixture(autouse=True)
+def enable_partition_filter_mapping(app: Flask) -> Any:
+ """The feature ships off; every test here exercises it on."""
+ original = app.config["DEFAULT_FEATURE_FLAGS"].get("PARTITION_FILTER_MAPPING")
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = True
+ yield
+ if original is None:
+ del app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"]
+ else:
+ app.config["DEFAULT_FEATURE_FLAGS"]["PARTITION_FILTER_MAPPING"] = original
+
+
+def _table(**kwargs: Any) -> SqlaTable:
+ database = Database(database_name="test_db", sqlalchemy_uri="sqlite://")
+ defaults: dict[str, Any] = {
+ "table_name": "web_events",
+ "database": database,
+ "main_dttm_col": "event_time",
+ "columns": [
+ TableColumn(column_name="event_time", is_dttm=True, type="TIMESTAMP"),
+ TableColumn(
+ column_name="dt_epoch",
+ type="BIGINT",
+ partition_value_transform=None,
+ ),
+ TableColumn(column_name="country", type="VARCHAR"),
+ TableColumn(column_name="region_key", type="VARCHAR"),
+ ],
+ }
+ defaults.update(kwargs)
+ return SqlaTable(**defaults)
+
+
+def _mapped_table(
+ *,
+ partition_column: str = "dt_epoch",
+ mapped_column: str = "event_time",
+ transform: str | None = "unix_timestamp(:value)",
+ monotonic: bool = True,
+ partition_mapped_column: str | None = None,
+ main_dttm_col: str | None = "event_time",
+) -> SqlaTable:
+ table = _table(main_dttm_col=main_dttm_col)
+ table.partition_column = partition_column
+ table.partition_mapped_column = partition_mapped_column
+ for column in table.columns:
+ if column.column_name == mapped_column:
+ column.partition_value_transform = transform
+ column.partition_transform_is_monotonic = monotonic
+ return table
+
+
+# ---------------------------------------------------------------------------
+# §2 — operator safety matrix
+# ---------------------------------------------------------------------------
+
+
+def test_equality_and_in_are_always_mirrorable() -> None:
+ """``=`` and ``IN`` are safe for any function ``T``."""
+ assert MIRRORABLE_ALWAYS == {FilterOperator.EQUALS, FilterOperator.IN}
+
+
+def test_range_operators_require_a_monotonic_transform() -> None:
+ assert MIRRORABLE_IF_MONOTONIC == {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+ }
+
+
+def test_mirrorable_operators_excludes_ranges_when_not_monotonic() -> None:
+ assert mirrorable_operators(is_monotonic=False) == MIRRORABLE_ALWAYS
+
+
+def test_mirrorable_operators_includes_ranges_when_monotonic() -> None:
+ assert mirrorable_operators(is_monotonic=True) == (
+ MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+ )
+
+
+@pytest.mark.parametrize(
+ "operator",
+ [
+ FilterOperator.NOT_EQUALS,
+ FilterOperator.NOT_IN,
+ FilterOperator.LIKE,
+ FilterOperator.ILIKE,
+ FilterOperator.NOT_LIKE,
+ FilterOperator.NOT_ILIKE,
+ FilterOperator.IS_NULL,
+ FilterOperator.IS_NOT_NULL,
+ FilterOperator.IS_TRUE,
+ FilterOperator.IS_FALSE,
+ ],
+)
+def test_negations_and_pattern_matches_are_never_mirrorable(
+ operator: FilterOperator,
+) -> None:
+ """
+ ``T`` is not injective, so ``col != v`` does **not** imply ``T(col) != T(v)``:
+ mirroring it would drop rows the original filter keeps.
+ """
+ assert operator not in mirrorable_operators(is_monotonic=True)
+
+
+def test_equality_is_dropped_when_the_engine_does_not_compare_byte_exactly() -> None:
+ """
+ "Safe for any function ``T``" reasons about value equality: ``T`` is a
+ function, so ``col = v`` gives ``T(col) = T(v)``. The engine reasons about
+ *SQL* equality, and the two part company under a case-insensitive
+ collation -- a stored ``'us'`` satisfies a filter for ``'US'`` while the
+ mirror ``hex('US')`` excludes the row, and the chart loses it silently.
+ """
+ assert mirrorable_operators(is_monotonic=False, equality_is_safe=False) == set()
+
+
+def test_ranges_survive_an_unsafe_equality() -> None:
+ """
+ Range mirroring already rests on the owner declaring ``T``
+ order-preserving with respect to the column's own order -- an assertion
+ about the very comparison semantics this gate checks for. Equality has no
+ such declaration behind it, which is why only equality is withdrawn.
+ """
+ assert (
+ mirrorable_operators(is_monotonic=True, equality_is_safe=False)
+ == MIRRORABLE_IF_MONOTONIC
+ )
+
+
+@pytest.mark.parametrize(
+ "operator,expected",
+ [
+ (FilterOperator.GREATER_THAN, FilterOperator.GREATER_THAN_OR_EQUALS),
+ (FilterOperator.LESS_THAN, FilterOperator.LESS_THAN_OR_EQUALS),
+ (
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ ),
+ (FilterOperator.LESS_THAN_OR_EQUALS, FilterOperator.LESS_THAN_OR_EQUALS),
+ (FilterOperator.EQUALS, FilterOperator.EQUALS),
+ (FilterOperator.IN, FilterOperator.IN),
+ ],
+)
+def test_a_strict_bound_mirrors_non_strictly(
+ operator: FilterOperator, expected: FilterOperator
+) -> None:
+ """
+ Order-preserving means non-decreasing, not injective, so ``col < v``
+ implies only ``T(col) <= T(v)``. A day-key transform maps a whole day onto
+ one value and a strict mirror drops the boundary bucket. The non-strict
+ cases are already safe and pass through, which is what makes applying this
+ twice harmless.
+ """
+ assert mirror_operator(operator) == expected
+
+
+def test_relaxing_a_bound_stays_inside_the_mirrorable_set() -> None:
+ """
+ The substitution is about strictness, not about which filters mirror. The
+ Explore indicator reads `mirrorable_operators`, so leaving that set alone is
+ what keeps the glyph from promising pruning the SQL does not do -- and it is
+ also what guarantees `handle_comparison_filter` is never handed an operator
+ it has no case for.
+ """
+ assert {
+ mirror_operator(operator) for operator in MIRRORABLE_IF_MONOTONIC
+ } <= MIRRORABLE_IF_MONOTONIC
+
+
+def _column(type_: str) -> TableColumn:
+ database = Database(database_name="t", sqlalchemy_uri="sqlite://")
+ table = SqlaTable(table_name="t", database=database)
+ return TableColumn(column_name="c", type=type_, table=table)
+
+
+@pytest.mark.parametrize(
+ "type_, binary, expected",
+ [
+ ("VARCHAR", True, True),
+ ("VARCHAR", False, False),
+ # Numeric and temporal comparison is exact everywhere.
+ ("BIGINT", False, True),
+ ("TIMESTAMP", False, True),
+ ("DOUBLE", False, True),
+ ],
+)
+def test_equality_mirrors_safely_only_guards_string_columns(
+ app: Flask, type_: str, binary: bool, expected: bool
+) -> None:
+ class _Spec(BaseEngineSpec):
+ binary_string_comparison = binary
+
+ with app.app_context():
+ assert equality_mirrors_safely(_column(type_), _Spec) is expected
+
+
+def test_equality_mirrors_safely_fails_closed_on_an_unresolvable_type(
+ app: Flask,
+) -> None:
+ """
+ The gate exists to stop a silent wrong answer, so a column whose type it
+ cannot read is treated as the risky case rather than waved through.
+ """
+ column = MagicMock()
+ type(column).type_generic = PropertyMock(side_effect=ValueError("no type"))
+
+ with app.app_context():
+ assert equality_mirrors_safely(column, BaseEngineSpec) is False
+
+
+def test_no_mapped_column_leaves_the_matrix_alone(app: Flask) -> None:
+ """Nothing to reason about, and the resolver bails out on it anyway."""
+ with app.app_context():
+ assert equality_mirrors_safely(None, BaseEngineSpec) is True
+
+
+@pytest.mark.parametrize(
+ "module, spec_name",
+ [
+ ("presto", "PrestoEngineSpec"),
+ ("hive", "HiveEngineSpec"),
+ ("trino", "TrinoEngineSpec"),
+ ("impala", "ImpalaEngineSpec"),
+ ("postgres", "PostgresEngineSpec"),
+ ("bigquery", "BigQueryEngineSpec"),
+ ("sqlite", "SqliteEngineSpec"),
+ ],
+)
+def test_the_byte_exact_engines_opt_in(module: str, spec_name: str) -> None:
+ """
+ The engines this feature targets compare text byte-exactly, so the gate
+ must not cost them the second canonical mapping (`lower(:value)` onto a
+ lowercased key).
+ """
+ spec = getattr(import_module(f"superset.db_engine_specs.{module}"), spec_name)
+ assert spec.binary_string_comparison is True
+
+
+@pytest.mark.parametrize("module, spec_name", [("mysql", "MySQLEngineSpec")])
+def test_a_case_insensitive_engine_does_not_opt_in(module: str, spec_name: str) -> None:
+ """
+ MySQL's default collation is `utf8mb4_0900_ai_ci`, which is exactly the
+ case the reviewer raised.
+ """
+ spec = getattr(import_module(f"superset.db_engine_specs.{module}"), spec_name)
+ assert spec.binary_string_comparison is False
+
+
+def test_the_base_spec_does_not_opt_in() -> None:
+ """A spec that has not said so does not mirror string equality."""
+ assert BaseEngineSpec.binary_string_comparison is False
+
+
+# ---------------------------------------------------------------------------
+# Time grain bucket widths
+# ---------------------------------------------------------------------------
+
+
+@pytest.mark.parametrize("grain", list(TimeGrain))
+def test_every_builtin_grain_has_a_known_bucket_width(
+ app: Flask, grain: TimeGrain
+) -> None:
+ """
+ The widening is only sound for a grain whose bucket width we know, so a
+ grain added upstream without a width here would silently stop mirroring.
+ This is the test that notices.
+ """
+ with app.app_context():
+ assert grain_bucket_width(grain.value, "sqlite") is not None
+
+
+def test_a_calendar_grain_widens_by_a_calendar_month(app: Flask) -> None:
+ """A month is not thirty days, and the month it lands in decides its width."""
+ with app.app_context():
+ width = grain_bucket_width(TimeGrain.MONTH.value, "sqlite")
+
+ assert width is not None
+ assert datetime(2026, 1, 31) + width == datetime(2026, 2, 28)
+ assert datetime(2026, 2, 1) + width == datetime(2026, 3, 1)
+
+
+def test_a_fractional_grain_has_a_width(app: Flask) -> None:
+ """
+ ``PT0.5H`` and ``P0.25Y`` are why the widths are written out rather than
+ parsed -- and the anchored week grains are intervals ``parse_duration``
+ rejects outright.
+ """
+ with app.app_context():
+ assert grain_bucket_width(TimeGrain.HALF_HOUR.value, "sqlite") == relativedelta(
+ minutes=30
+ )
+ assert grain_bucket_width(
+ TimeGrain.WEEK_ENDING_SATURDAY.value, "sqlite"
+ ) == relativedelta(days=7)
+
+
+def test_an_unknown_grain_has_no_known_width(app: Flask) -> None:
+ with app.app_context():
+ assert grain_bucket_width("P13X", "sqlite") is None
+ assert grain_bucket_width(None, "sqlite") is None
+
+
+def test_an_addon_grain_has_no_known_width(app: Flask) -> None:
+ """An operator-declared grain carries whatever duration string they typed."""
+ with app.app_context():
+ app.config["TIME_GRAIN_ADDONS"] = {"PT2S": "2 second"}
+ try:
+ assert grain_bucket_width("PT2S", "sqlite") is None
+ finally:
+ app.config["TIME_GRAIN_ADDONS"] = {}
+
+
+def test_a_builtin_grain_an_operator_redefined_has_no_known_width(
+ app: Flask,
+) -> None:
+ """
+ ``TIME_GRAIN_ADDON_EXPRESSIONS`` replaces a built-in grain's SQL for one
+ engine, so its duration no longer bounds the displacement *there* -- but it
+ still does on every other engine.
+ """
+ with app.app_context():
+ app.config["TIME_GRAIN_ADDON_EXPRESSIONS"] = {
+ "sqlite": {"P1D": "DATETIME({col}, 'start of year')"}
+ }
+ try:
+ assert grain_bucket_width(TimeGrain.DAY.value, "sqlite") is None
+ assert grain_bucket_width(TimeGrain.DAY.value, "hive") is not None
+ finally:
+ app.config["TIME_GRAIN_ADDON_EXPRESSIONS"] = {}
+
+
+def test_the_width_table_is_keyed_on_grain_durations(app: Flask) -> None:
+ """Keys are the ISO duration a filter carries, not the enum member name."""
+ assert GRAIN_BUCKET_WIDTHS[TimeGrain.DAY] == relativedelta(days=1)
+ assert set(GRAIN_BUCKET_WIDTHS) == {grain.value for grain in TimeGrain}
+
+
+# ---------------------------------------------------------------------------
+# §4.1 — resolving the effective mapping, and the defensive bail-outs
+# ---------------------------------------------------------------------------
+
+
+def test_resolve_returns_the_mapping_when_everything_lines_up(app: Flask) -> None:
+ with app.app_context():
+ mapping = resolve_partition_mapping(_mapped_table())
+
+ assert mapping is not None
+ assert mapping.partition_column == "dt_epoch"
+ assert mapping.mapped_column == "event_time"
+ assert mapping.value_transform == "unix_timestamp(:value)"
+ assert mapping.is_monotonic is True
+
+
+def test_effective_mapped_column_follows_main_dttm_col(app: Flask) -> None:
+ """No explicit override: the mapping follows the default datetime column."""
+ with app.app_context():
+ mapping = resolve_partition_mapping(_mapped_table())
+
+ assert mapping is not None
+ assert mapping.mapped_column == "event_time"
+
+
+def test_explicit_override_wins_over_main_dttm_col(app: Flask) -> None:
+ table = _mapped_table(
+ mapped_column="country",
+ transform="lower(:value)",
+ monotonic=False,
+ partition_mapped_column="country",
+ )
+ table.partition_column = "region_key"
+
+ with app.app_context():
+ mapping = resolve_partition_mapping(table)
+
+ assert mapping is not None
+ assert mapping.mapped_column == "country"
+ assert mapping.partition_column == "region_key"
+ assert mapping.is_monotonic is False
+
+
+def test_resolve_returns_none_when_the_feature_flag_is_off(app: Flask) -> None:
+ table = _mapped_table()
+ with app.app_context():
+ with patch(
+ "superset.connectors.sqla.partition_mapping.feature_flag_manager."
+ "is_feature_enabled",
+ return_value=False,
+ ):
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_without_a_partition_column(app: Flask) -> None:
+ table = _mapped_table()
+ table.partition_column = None
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_partition_column_no_longer_exists(
+ app: Flask,
+) -> None:
+ """A column sync can drop the physical partition column out from under us."""
+ table = _mapped_table()
+ table.partition_column = "dt_epoch_gone"
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_the_mapped_column_no_longer_exists(
+ app: Flask,
+) -> None:
+ table = _mapped_table(main_dttm_col="vanished")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_on_self_mapping(app: Flask) -> None:
+ """
+ ``partition_column == effective mapped column`` mirrors a column onto itself.
+ Save-time validation rejects it, but rows predating that validation exist.
+ """
+ table = _mapped_table(
+ partition_column="event_time",
+ mapped_column="event_time",
+ )
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+@pytest.mark.parametrize("transform", [None, "", " "])
+def test_resolve_returns_none_without_a_transform(
+ app: Flask, transform: str | None
+) -> None:
+ table = _mapped_table(transform=transform)
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_the_transform_lacks_the_placeholder(
+ app: Flask,
+) -> None:
+ table = _mapped_table(transform="unix_timestamp(event_time)")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_for_a_non_deterministic_transform(app: Flask) -> None:
+ """
+ The query-time gate is `is_transform_active`, the same one the Explore
+ indicator reads. Anything narrower would let a transform that reached
+ storage without passing `UpdateDatasetCommand` -- through import, or a
+ hand-written bundle -- mirror a filter with a value frozen at probe time,
+ while the editor reported the mapping as inactive and nothing on screen
+ said otherwise.
+ """
+ table = _mapped_table(transform="unix_timestamp(:value) + rand()")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_for_a_multi_expression_transform(app: Flask) -> None:
+ """A select list is not an expression; the probe cannot align its columns."""
+ table = _mapped_table(transform="lower(:value), 'x'")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_for_an_unparseable_transform(app: Flask) -> None:
+ table = _mapped_table(transform="unix_timestamp(:value")
+ with app.app_context():
+ assert resolve_partition_mapping(table) is None
+
+
+def test_resolve_returns_none_when_the_mapped_column_has_an_advanced_data_type(
+ app: Flask,
+) -> None:
+ """
+ ``translate_filter`` builds its own predicate shape from *translated* values,
+ so the ``(operator, value)`` pair the operator matrix reasons about does not
+ exist. Mirroring anyway would silently apply the wrong values (§4.1).
+ """
+ table = _mapped_table()
+ for column in table.columns:
+ if column.column_name == "event_time":
+ column.advanced_data_type = "port"
+
+ with app.app_context():
+ with patch.dict(app.config["ADVANCED_DATA_TYPES"], {"port": MagicMock()}):
+ with patch(
+ "superset.connectors.sqla.partition_mapping.feature_flag_manager."
+ "is_feature_enabled",
+ side_effect=lambda flag: (
+ flag in {"PARTITION_FILTER_MAPPING", "ENABLE_ADVANCED_DATA_TYPES"}
+ ),
+ ):
+ assert resolve_partition_mapping(table) is None
+
+
+def test_advanced_data_type_does_not_block_when_the_flag_is_off(app: Flask) -> None:
+ """An inert ``advanced_data_type`` is not a reason to skip mirroring."""
+ table = _mapped_table()
+ for column in table.columns:
+ if column.column_name == "event_time":
+ column.advanced_data_type = "port"
+
+ with app.app_context():
+ with patch(
+ "superset.connectors.sqla.partition_mapping.feature_flag_manager."
+ "is_feature_enabled",
+ side_effect=lambda flag: flag == "PARTITION_FILTER_MAPPING",
+ ):
+ assert resolve_partition_mapping(table) is not None
+
+
+# ---------------------------------------------------------------------------
+# §5 — transform inspection helpers
+# ---------------------------------------------------------------------------
+
+
+@pytest.mark.parametrize(
+ "transform,expected",
+ [
+ ("unix_timestamp(:value)", True),
+ ("lower(:value)", True),
+ ("CAST(:value AS BIGINT)", True),
+ ("unix_timestamp(event_time)", False),
+ (":values", False),
+ ("", False),
+ (None, False),
+ ],
+)
+def test_contains_value_placeholder(transform: str | None, expected: bool) -> None:
+ assert contains_value_placeholder(transform) is expected
+
+
+@pytest.mark.parametrize(
+ "transform,expected",
+ [
+ ("unix_timestamp(:value)", False),
+ ("{{ current_username() }}", True),
+ ("lower({% if x %}:value{% endif %})", True),
+ ("lower(:value) -- {# comment #}", True),
+ ],
+)
+def test_contains_jinja(transform: str, expected: bool) -> None:
+ assert contains_jinja(transform) is expected
+
+
+@pytest.mark.parametrize(
+ ("transform", "expected"),
+ [
+ ("lower(:value)", False),
+ ("lower(:value) /* an ordinary comment */", False),
+ ("lower(:value) -- a line comment", False),
+ (":value /*!50000 + 1 */", True),
+ (":value /*M!50000 + 1 */", True),
+ (":value /*! + 1 */", True),
+ ("", False),
+ (None, False),
+ ],
+)
+def test_contains_executable_comment(transform: str | None, expected: bool) -> None:
+ assert contains_executable_comment(transform) is expected
+
+
+@pytest.mark.parametrize(
+ "transform",
+ [
+ "unix_timestamp(:value)",
+ "lower(:value)",
+ "CAST(:value AS BIGINT)",
+ "date_format(:value, 'yyyyMMdd')",
+ ],
+)
+def test_pure_transforms_report_no_non_deterministic_functions(
+ transform: str,
+) -> None:
+ assert find_non_deterministic_functions(transform, "hive") == set()
+
+
+@pytest.mark.parametrize(
+ "transform,expected_name",
+ [
+ ("date_diff(:value, now())", "NOW"),
+ ("CAST(:value AS BIGINT) + rand()", "RAND"),
+ ("CAST(:value AS DATE) - current_date", "CURRENT_DATE"),
+ ],
+)
+def test_non_deterministic_functions_are_reported(
+ transform: str, expected_name: str
+) -> None:
+ """
+ The probe runs at a different moment and in a different session from the
+ chart query, and its result is cached, so anything time- or
+ randomness-dependent freezes a snapshot of probe time into the predicate.
+ """
+ assert expected_name in find_non_deterministic_functions(transform, "hive")
+
+
+def test_niladic_unix_timestamp_is_rejected_but_the_unary_form_is_not() -> None:
+ """
+ On Hive/Impala ``unix_timestamp()`` means "now" while ``unix_timestamp(x)``
+ -- the canonical temporal transform -- is pure. The distinction is the whole
+ reason this check inspects arity rather than just the name.
+ """
+ assert find_non_deterministic_functions("unix_timestamp(:value)", "hive") == set()
+ assert find_non_deterministic_functions(
+ "unix_timestamp(:value) - unix_timestamp()", "hive"
+ )
+
+
+# ---------------------------------------------------------------------------
+# §4.2 — probe evaluation
+# ---------------------------------------------------------------------------
+
+
+def _user(username: str) -> Any:
+ """A stand-in for `override_user`, which only needs `.username` here."""
+ user = MagicMock()
+ user.username = username
+ user.is_anonymous = False
+ return user
+
+
+def _database_returning(values: list[Any]) -> Database:
+ """A real ``Database`` (so the dialect is real) with only ``get_df`` stubbed."""
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ return_value=pd.DataFrame(
+ [values], columns=[f"v{i}" for i in range(len(values))]
+ )
+ )
+ return database
+
+
+def _database_returning_frame(frame: pd.DataFrame) -> Database:
+ """
+ ``_database_returning`` for a probe result whose column dtypes matter.
+
+ The flat-list sibling builds its frame from one Python list, so pandas
+ infers a single dtype and the row-versus-cell distinction cannot be seen.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ return_value=frame
+ )
+ return database
+
+
+def _probe(database: Database) -> MagicMock:
+ """
+ The stubbed ``get_df``, typed for call assertions.
+
+ ``Database.get_df`` is a real method, so mypy reads its declared signature
+ rather than the mock that replaced it and rejects ``.call_args`` and
+ friends.
+ """
+ return cast(MagicMock, database.get_df)
+
+
+def test_evaluate_transform_returns_one_value_per_input(app: Flask) -> None:
+ database = _database_returning([1767225600, 1769904000])
+
+ with app.app_context():
+ result = evaluate_transform(
+ database,
+ None,
+ "default",
+ "unix_timestamp(:value)",
+ ["2026-01-01 00:00:00", "2026-02-01 00:00:00"],
+ )
+
+ assert result == [1767225600, 1769904000]
+ _probe(database).assert_called_once()
+
+
+def test_evaluate_transform_binds_values_rather_than_interpolating(
+ app: Flask,
+) -> None:
+ """
+ Filter values are attacker-controlled (a Gamma user picks them), so they must
+ be bound and escaped, never pasted into the probe SQL.
+ """
+ database = _database_returning(["o''brien"])
+
+ with app.app_context():
+ evaluate_transform(database, None, None, "lower(:value)", ["O'Brien"])
+
+ sql = _probe(database).call_args.kwargs["sql"]
+ assert "O'Brien" not in sql
+ assert "O''Brien" in sql
+
+
+@pytest.mark.parametrize(
+ ("transform", "expected"),
+ [
+ ("lower(:value)", True),
+ ("CAST(:value AS BIGINT)", True),
+ ("date_format(:value, '%Y%m%d')", True),
+ # The cast shorthand: a trailing colon stops SQLAlchemy's bind scan.
+ (":value::bigint", False),
+ ("(:value::date)::text", False),
+ ],
+)
+def test_a_postgres_cast_shorthand_is_not_bindable(
+ transform: str, expected: bool
+) -> None:
+ """
+ `VALUE_PLACEHOLDER_RE` is `:value\b`, which matches inside `:value::bigint`.
+ SQLAlchemy's own scan ends with `(?![:\\w$])`, so the following colon stops
+ it: `text(":value::bigint")` reports a parameter named `valu`, and asking it
+ to bind `value` raises.
+
+ Pinned because the two regexes disagreeing is the whole bug: every
+ write-side gate accepted the transform and the probe then died on an
+ `ArgumentError` that `_probe` swallows.
+ """
+ assert _placeholder_is_bindable(transform) is expected
+
+
+def test_a_cast_shorthand_transform_still_probes(app: Flask) -> None:
+ """
+ The transform is valid SQL, passes every gate, and used to prune nothing:
+ `build_probe_sql` raised, `_probe` swallowed it, and the only symptom was a
+ mapping that silently never mirrored -- with the preview reporting an engine
+ failure for SQL that was never sent.
+ """
+ database = _database_returning([20260115])
+
+ with app.app_context():
+ result = evaluate_transform(
+ database, None, None, ":value::bigint", ["20260115"]
+ )
+
+ assert result == [20260115]
+ assert _probe(database).call_count == 1
+ assert "::bigint" in _probe(database).call_args.kwargs["sql"]
+
+
+def test_a_cast_shorthand_value_is_still_escaped_by_the_dialect(
+ app: Flask,
+) -> None:
+ """
+ The fallback substitutes where the bind path binds, so it has to earn the
+ same guarantee its sibling above pins: the value is rendered by the
+ dialect's literal processor, not pasted in.
+
+ Binding was only ever the vehicle for reaching that processor --
+ `_compile_literal` inlines the result either way -- so this renders first
+ and substitutes second. Same string, different order.
+ """
+ database = _database_returning(["x"])
+
+ with app.app_context():
+ evaluate_transform(database, None, None, ":value::text", ["O'Brien"])
+
+ sql = _probe(database).call_args.kwargs["sql"]
+ assert "O'Brien" not in sql
+ assert "O''Brien" in sql
+
+
+def test_evaluate_transform_dedupes_repeated_values(app: Flask) -> None:
+ """Three inputs, two distinct: the probe evaluates the transform twice."""
+ database = _database_returning(["us", "us"])
+
+ with app.app_context():
+ result = evaluate_transform(
+ database, None, None, "lower(:value)", ["US", "US", "us"]
+ )
+
+ assert result == ["us", "us", "us"]
+ sql = _probe(database).call_args.kwargs["sql"]
+ assert sql.count("lower") == 2
+
+
+def test_evaluate_transform_fails_open_on_a_short_result_row(app: Flask) -> None:
+ """A row narrower than the probe asked for means the results cannot be
+ aligned back to their inputs; pruning is skipped rather than guessed at."""
+ database = _database_returning(["us"])
+
+ with app.app_context():
+ assert (
+ evaluate_transform(database, None, None, "lower(:value)", ["US", "CA"])
+ is None
+ )
+
+
+def test_evaluate_transform_fails_open_on_a_wide_result_row(app: Flask) -> None:
+ """
+ Too many columns is the dangerous direction. A transform whose select list
+ holds two expressions returns 2N columns for N inputs, and reading the first
+ N interleaves the expressions instead of taking one per value -- a predicate
+ built from the wrong values rather than one that is merely short. A frame of
+ `('us', 'x', 'ca', 'x')` read as the first two columns would have yielded
+ `('us', 'x')` and dropped every CA row.
+
+ The transform is a perfectly ordinary `lower(:value)` and the width comes
+ from the stubbed frame, which is the only way to reach the guard: a
+ transform that really does carry two expressions -- `lower(:value), 'x'` --
+ is refused by `stored_expression_error` for not being a single expression,
+ so `get_df` is never called and `None` comes back for an unrelated reason.
+ Asserting the probe *ran* is what separates the two, and it is what makes
+ relaxing the guard from `!=` to `<` fail here rather than pass: four columns
+ for two inputs is not fewer than two.
+ """
+ database = _database_returning(["us", "x", "ca", "x"])
+
+ with app.app_context():
+ assert (
+ evaluate_transform(database, None, None, "lower(:value)", ["US", "CA"])
+ is None
+ )
+
+ assert _probe(database).call_count == 1
+
+
+def test_the_probe_select_carries_the_engine_s_from_clause(app: Flask) -> None:
+ """
+ A `SELECT` with no `FROM` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from. Without this every probe on those engines
+ raises, which `evaluate_transform` swallows -- so the only symptom is a
+ correctly configured mapping that silently never prunes.
+ """
+ assert build_probe_sql("lower(:value)", ["US"]) == "SELECT lower('US') AS v0"
+ assert build_probe_sql("lower(:value)", ["US"], None, " FROM DUAL").endswith(
+ " FROM DUAL"
+ )
+ assert OracleEngineSpec.select_without_from_suffix == " FROM DUAL"
+ assert BaseEngineSpec.select_without_from_suffix == ""
+
+
+@pytest.mark.parametrize("dialect", [mysql.dialect(), postgresql.dialect()])
+def test_the_probe_select_does_not_double_percent_signs(dialect: Any) -> None:
+ """
+ `TextClause` compilation runs the dialect's `post_process_text`, which
+ doubles every `%` on any paramstyle whose DBAPI later interpolates
+ parameters -- MySQL and Postgres, and every spec inheriting from them. The
+ probe has no such interpolation pass: it executes with no bound parameters
+ at all. Left doubled, `date_format(:value, '%Y%m%d')` asks the warehouse
+ for the literal string `%%Y%%m%%d`, so the probe returns that instead of a
+ date and the mirrored predicate drops every row the filter keeps.
+ """
+ sql = build_probe_sql("date_format(:value, '%Y%m%d')", ["2026-01-15"], dialect)
+
+ assert "'%Y%m%d'" in sql
+ assert "%%" not in sql
+
+
+def test_the_probe_select_is_unchanged_on_a_dialect_that_does_not_double() -> None:
+ """
+ Pins the no-dialect path, which is also the blind spot: the default dialect
+ does not double percent signs, so no assertion made through it can see the
+ bug the two cases above cover.
+ """
+ assert (
+ build_probe_sql("date_format(:value, '%Y%m%d')", ["2026-01-15"])
+ == "SELECT date_format('2026-01-15', '%Y%m%d') AS v0"
+ )
+
+
+def test_a_raw_probe_value_is_substituted_literally() -> None:
+ r"""
+ `RawProbeValue.sql` is rendered from a filter value, so it reaches
+ `parse_skeleton` as the *replacement* for `:value`. Read as a replacement
+ template, a backslash in it is an escape: `array('a\nb')` -- which is how a
+ dialect renders the two characters `\` and `n` -- would become a real
+ newline, so the engine is asked about a different array than the predicate
+ compares and the mirror can exclude rows the filter keeps.
+ """
+ sql = build_probe_sql("toYYYYMM(:value)", [RawProbeValue(r"array('a\nb')")])
+
+ assert sql == r"SELECT toYYYYMM(array('a\nb')) AS v0"
+
+
+def test_a_raw_probe_value_does_not_re_inject_the_placeholder() -> None:
+ r"""
+ `\g<0>` in a replacement template expands to the whole match, which would
+ put `:value` back into the probe -- an unbound parameter the engine refuses.
+ """
+ sql = build_probe_sql("toYYYYMM(:value)", [RawProbeValue(r"'a\g<0>b'")])
+
+ assert sql == r"SELECT toYYYYMM('a\g<0>b') AS v0"
+ assert ":value" not in sql
+
+
+def test_a_raw_probe_value_with_a_group_reference_does_not_raise() -> None:
+ r"""
+ `\1` is an invalid group reference for this pattern, so as a replacement
+ template it raised `re.PatternError` rather than probing anything.
+ """
+ sql = build_probe_sql("toYYYYMM(:value)", [RawProbeValue(r"'a\1b'")])
+
+ assert sql == r"SELECT toYYYYMM('a\1b') AS v0"
+
+
+def test_a_probed_literal_keeps_its_percent_sign(app: Flask) -> None:
+ """
+ The preview panel renders probed values through the same dialect, so a
+ value that merely contains a `%` would be shown doubled.
+ """
+ database = Database(database_name="pct_db", sqlalchemy_uri="postgresql://h/d")
+
+ with app.app_context():
+ assert _render_literal(database, "100%") == "'100%'"
+
+
+def test_the_probe_reads_each_cell_without_row_wide_dtype_coercion(
+ app: Flask,
+) -> None:
+ """
+ A row is a Series, so it carries one dtype across every probe column: a row
+ mixing an exact int64 with a float unifies to float64 and an integer
+ partition key above 2^53 comes back rounded. The mirror then asks for a key
+ the warehouse does not hold, and the row the filter matched is dropped.
+ """
+ database = _database_returning_frame(
+ pd.DataFrame({"v0": [9007199254740993], "v1": [1.5]})
+ )
+
+ with app.app_context():
+ probed = evaluate_transform(
+ database, None, None, "CAST(:value AS NUMERIC)", ["9007199254740993", "1.5"]
+ )
+
+ assert probed == [9007199254740993, 1.5]
+
+
+def test_evaluate_transform_pins_catalog_and_schema(app: Flask) -> None:
+ """
+ The probe runs in a different session from the chart query; pinning the
+ catalog and schema keeps session settings as close as the pool allows.
+ """
+ database = _database_returning([1])
+
+ with app.app_context():
+ evaluate_transform(database, "prod", "analytics", "lower(:value)", ["x"])
+
+ kwargs = _probe(database).call_args.kwargs
+ assert kwargs["catalog"] == "prod"
+ assert kwargs["schema"] == "analytics"
+
+
+def test_evaluate_transform_fails_open_when_the_probe_raises(app: Flask) -> None:
+ """A wedged engine must not break the chart — it just stops pruning."""
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ side_effect=RuntimeError("connection reset")
+ )
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, "lower(:value)", ["x"]) is None
+
+
+def test_evaluate_transform_fails_open_on_an_empty_result(app: Flask) -> None:
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ database.get_df = MagicMock( # type: ignore[method-assign]
+ return_value=pd.DataFrame()
+ )
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, "lower(:value)", ["x"]) is None
+
+
+def test_evaluate_transform_returns_none_for_no_values(app: Flask) -> None:
+ database = _database_returning([])
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, "lower(:value)", []) is None
+
+ _probe(database).assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "transform",
+ [
+ "(SELECT password FROM ab_user LIMIT 1) || :value",
+ "lower(:value) UNION ALL SELECT password FROM ab_user",
+ "lower(:value); DROP TABLE ab_user",
+ "password || :value FROM ab_user",
+ "lower(:value) FROM ab_user WHERE 1 = 1",
+ ],
+ ids=[
+ "subquery",
+ "set-operation",
+ "multi-statement",
+ "bare-from",
+ "from-and-where",
+ ],
+)
+def test_a_transform_that_is_not_a_storable_expression_never_runs(
+ app: Flask, transform: str
+) -> None:
+ """
+ The probe is where a transform stops being text and becomes SQL.
+
+ `build_probe_sql` binds `:value` and splices the rest in verbatim, so a
+ transform that was never a single harmless expression is arbitrary SQL
+ against the dataset's database -- read back out of the emitted predicate
+ by anyone who can open "View query". The write-side gates refuse these,
+ but they can only speak for rows written after they existed, so the last
+ word belongs here.
+ """
+ database = _database_returning(["irrelevant"])
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, transform, ["us"]) is None
+
+ _probe(database).assert_not_called()
+
+
+@pytest.mark.parametrize(
+ "transform, unfinished",
+ [
+ ("unix_timestamp(:value", True),
+ ("unix_timestamp(:value))", True),
+ ("unix_timestamp(:value) +", True),
+ ("unix_timestamp(:value)", False),
+ ("unix_timestamp(:value); DROP TABLE ab_user", False),
+ ("unix_timestamp(:value) UNION ALL SELECT password FROM ab_user", False),
+ ("password || :value FROM ab_user", False),
+ ],
+)
+def test_is_unfinished_separates_not_sql_yet_from_the_wrong_sql(
+ transform: str, unfinished: bool
+) -> None:
+ """
+ The two deserve opposite treatment -- a half-typed transform is stored and
+ parked inactive, the wrong SQL is refused -- and neither `is_parseable` nor
+ parsing as a single statement tells them apart, because the multi-statement
+ form fails both exactly as unfinished text does. Parsing as a script does.
+ """
+ assert is_unfinished(transform, "hive") is unfinished
+
+
+def test_a_transform_smuggling_its_own_from_clause_is_refused(app: Flask) -> None:
+ """
+ The hole this gate was added for.
+
+ `is_parseable` counts only the projection, so `password || :value FROM
+ ab_user` reads as a single select expression and passed every write-side
+ gate -- including with `ALLOW_ADHOC_SUBQUERY` off, since a top-level FROM
+ is not a sub-query. `build_probe_sql` then emitted `SELECT password || 'us'
+ AS v0 FROM ab_user`, where its own alias is read as a table alias on the
+ FROM clause the transform brought with it: valid SQL, one row, and the
+ secret handed back through the predicate the preview panel renders.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ transform = "password || :value FROM ab_user"
+
+ assert is_parseable(transform, "sqlite") is True
+ assert is_bare_expression(transform, "sqlite") is False
+
+ with app.app_context():
+ reason = stored_expression_error(database, None, None, transform)
+ assert reason is not None
+
+ blocking = _blocking(validate_transform(transform, "sqlite"))
+ assert len(blocking) == 1
+ assert "single SQL expression" in str(blocking[0].message)
+ assert is_transform_active(transform, "sqlite") is False
+
+
+def test_a_subquery_transform_is_refused_even_with_adhoc_subquery_enabled(
+ app: Flask,
+) -> None:
+ """
+ `validate_adhoc_subquery` admits a sub-query under `ALLOW_ADHOC_SUBQUERY`
+ and returns RLS-rewritten SQL -- which this path has no way to propagate,
+ because `build_probe_sql` splices the original transform text. So the probe
+ ran a sub-query with no row-level-security predicates at all and reported
+ the hidden row in `emitted_predicate`. A transform is a scalar function of
+ `:value`, so refusing the sub-query outright is both correct and what makes
+ the missing RLS rewrite moot.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ transform = "(SELECT secret FROM vault LIMIT 1) || :value"
+
+ with app.app_context():
+ app.config["DEFAULT_FEATURE_FLAGS"]["ALLOW_ADHOC_SUBQUERY"] = True
+ try:
+ reason = stored_expression_error(database, None, None, transform)
+ finally:
+ del app.config["DEFAULT_FEATURE_FLAGS"]["ALLOW_ADHOC_SUBQUERY"]
+
+ assert reason is not None
+ assert "sub-query" in reason
+
+
+@pytest.mark.parametrize(
+ "comment",
+ ["/*!50000 + (SELECT secret FROM vault LIMIT 1) */", "/*M!50000 + 1 */"],
+)
+def test_an_executable_comment_is_refused_by_every_gate(
+ app: Flask, comment: str
+) -> None:
+ """
+ The one construct that made the shape gates describe a statement the engine
+ would not run.
+
+ sqlglot reads a MySQL executable comment as comment data: the pinned parse
+ below reports no sub-query and no clause, so `stored_expression_error` and
+ `probe_sql_is_evaluable` both passed it, while MySQL and MariaDB execute
+ what is inside. An owner with dataset write and no SQL Lab could put one in
+ a transform, call the preview and read a table back out of
+ `emitted_predicate`, with no RLS on the hidden query.
+
+ Refused on every engine, not only the two that honour it -- hence SQLite
+ here. There is no legitimate transform carrying one, and a per-engine gate
+ would store on Postgres what detonates after the dataset is re-pointed.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ transform = f"(:value {comment})"
+
+ # The premise: no parse-tree gate can see it.
+ statement = SQLStatement(f"SELECT (1 {comment}) AS v0", "mysql")
+ assert statement.has_subquery() is False
+ assert statement.get_clause_names() == set()
+
+ with app.app_context():
+ assert stored_expression_error(database, None, None, transform) is not None
+
+ blocking = [
+ issue for issue in validate_transform(transform, "mysql") if issue.blocking
+ ]
+ assert len(blocking) == 1
+ assert "executable comment" in str(blocking[0].message)
+
+
+def test_an_executable_comment_stops_the_probe_before_the_engine(app: Flask) -> None:
+ """
+ The gate above is the save path. This is the row an earlier release stored:
+ `_probe` consults `stored_expression_error` on every call, so a transform
+ already in the metadata database never reaches `get_df`.
+ """
+ database = _database_returning(["x"])
+ transform = "(:value /*!50000 + (SELECT secret FROM vault LIMIT 1) */)"
+
+ with app.app_context():
+ assert evaluate_transform(database, None, None, transform, ["US"]) is None
+
+ assert _probe(database).call_count == 0
+
+
+def test_a_plain_comment_is_still_allowed_through_the_shape_gates(
+ app: Flask,
+) -> None:
+ """
+ Only the executable form is refused. An ordinary comment is inert on every
+ engine, so rejecting it would cost an owner a transform that works -- and
+ the placeholder gate already covers the case that matters, a `:value` the
+ comment swallows.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+
+ with app.app_context():
+ assert (
+ stored_expression_error(database, None, None, "lower(:value) /* ok */")
+ is None
+ )
+
+
+def test_a_transform_calling_a_disallowed_function_is_refused(app: Flask) -> None:
+ """
+ The probe executes the transform, so the operator's function denylist has
+ to apply to it for the same reason it applies in SQL Lab.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
+ transform = "version() || :value"
+
+ with app.app_context():
+ original = app.config["DISALLOWED_SQL_FUNCTIONS"]
+ try:
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = {"sqlite": {"version"}}
+ reason = stored_expression_error(database, None, None, transform)
+ assert reason is not None
+ assert "version" in reason
+
+ # Named, rather than echoing the operator's whole denylist back.
+ assert "current_user" not in reason
+
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = {}
+ assert stored_expression_error(database, None, None, transform) is None
+ finally:
+ # Restored: `app.config` is shared, and leaving it emptied silently
+ # disabled this gate for every test that ran afterwards.
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = original
+
+
+@pytest.mark.parametrize(
+ "function",
+ [
+ "database_to_xml",
+ "database_to_xmlschema",
+ "database_to_xml_and_xmlschema",
+ "schema_to_xml",
+ "schema_to_xmlschema",
+ "schema_to_xml_and_xmlschema",
+ "table_to_xml",
+ "table_to_xmlschema",
+ "table_to_xml_and_xmlschema",
+ "query_to_xml",
+ "query_to_xmlschema",
+ "query_to_xml_and_xmlschema",
+ ],
+)
+def test_the_whole_postgres_xml_family_is_denied_by_default(function: str) -> None:
+ """
+ These read tables with no FROM clause and no sub-query, so every gate that
+ reasons about table references is blind to them -- the denylist is the only
+ thing that can refuse them, and it has to name each shape. `schema_to_xml`
+ and three siblings were missing, so a bare scalar call cleared
+ `stored_expression_error` entirely and returned connection-user-readable
+ schema contents through preview.
+
+ Asserted against the shipped default rather than through the gate, because
+ the gap was an incomplete enumeration rather than broken wiring -- and
+ because `app.config` is ambient here, which the behavioural test below
+ handles by setting the denylist itself.
+ """
+ assert function in DISALLOWED_SQL_FUNCTIONS["postgresql"]
+
+
+def test_a_denied_read_capable_function_is_refused_despite_having_no_from(
+ app: Flask,
+) -> None:
+ """
+ The wiring half: a bare scalar call passes the length, single-statement,
+ bare-expression, sub-query and placeholder gates, so the denylist is what
+ has to stop it.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="postgresql://u@h/d")
+ transform = "schema_to_xml('public', true, false, '') || :value"
+
+ with app.app_context():
+ original = app.config["DISALLOWED_SQL_FUNCTIONS"]
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = {"postgresql": {"schema_to_xml"}}
+ try:
+ reason = stored_expression_error(database, None, None, transform)
+ finally:
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = original
+
+ assert reason is not None
+ assert "schema_to_xml" in reason
+
+
+@pytest.mark.parametrize("function", ["ts_rewrite", "ts_stat"])
+def test_the_postgres_full_text_query_functions_are_denied_by_default(
+ function: str,
+) -> None:
+ """
+ `ts_stat('select ...')` and `ts_rewrite(q, 'select ...')` run their *text*
+ argument as a query. The query is a string, so these have the same blind
+ spot the XML family above does: no FROM clause and no sub-query for a
+ table-reference gate to reason about, which leaves the denylist as the only
+ thing that can refuse them.
+ """
+ assert function in DISALLOWED_SQL_FUNCTIONS["postgresql"]
+
+
+def test_a_denied_query_running_text_function_is_refused(app: Flask) -> None:
+ """
+ The wiring half, and the only thing that proves the *name* matching works
+ for these two: neither is a function sqlglot models, so each reaches
+ `get_disallowed_functions` through its ANONYMOUS branch rather than as a
+ typed node. A denylist entry that only matched modelled functions would
+ pass the enumeration test above and still let these through.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="postgresql://u@h/d")
+ transform = "ts_stat('select 1') || :value"
+
+ with app.app_context():
+ original = app.config["DISALLOWED_SQL_FUNCTIONS"]
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = {"postgresql": {"ts_stat"}}
+ try:
+ reason = stored_expression_error(database, None, None, transform)
+ finally:
+ app.config["DISALLOWED_SQL_FUNCTIONS"] = original
+
+ assert reason is not None
+ assert "ts_stat" in reason
+
+
+def test_the_function_denylist_is_keyed_on_the_engine_spec_name(app: Flask) -> None:
+ """
+ Every other denylist gate in the codebase keys on the engine spec's own
+ name, which is also the name the config documentation tells an operator to
+ write, so this one does too -- a spec covering several SQLAlchemy backends
+ through `engine_aliases` reports the one canonical name under which its
+ entry exists.
+ """
+ database = Database(database_name="probe_db", sqlalchemy_uri="sqlite://")
Review Comment:
On `sqlite://` both `database.backend` and `database.db_engine_spec.engine` are `"sqlite"`, so this passes even if the gate keyed on `database.backend` instead of the engine spec name. Could this use an aliased engine (backend `postgres`, spec `postgresql`) with a function denied only under `postgresql`, and assert `stored_expression_error` rejects it? That is the case the test name promises.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "eschutho (via GitHub)" <gi...@apache.org>.
eschutho commented on PR #43870:
URL: https://github.com/apache/superset/pull/43870#issuecomment-6087229460
Rebased and updated on Hugh's behalf (I'm helping out at Elizabeth's request).
**Rebase.** The branch is rebased onto current `master` and is now **d808efd1f0**. The history is linear: the stacked-branch and `master` merges are gone, and Hugh's 103 commits are replayed on top. Conflicts were only in `UPDATING.md` (both sides kept), the message catalogs, and test files that both sides had appended to. Before adding any new commits, I checked that the rebased tree was **identical** to the old head merged with `master`. Where linearizing left an intermediate commit differing from Hugh's own merge result, I folded the correction into the last commit that touches that file. A backup of the old head (b83e550984) is kept locally.
**New commits for open review threads** (each has a regression test that fails without the fix; replies are on the threads):
| Thread | Commit | Change |
|---|---|---|
| [`helpers.py` unflagged DATE column](https://github.com/apache/superset/pull/43870#discussion_r4227028394) | f1dce85766 | the resolution check keys on `type_generic`, not `is_dttm` |
| [migration `Revises:`](https://github.com/apache/superset/pull/43870#discussion_r4227028421) | 8f4085c62a | docstring now names `e4a7c2b9d1f3` |
| [offset-bearing string bound](https://github.com/apache/superset/pull/43870#discussion_r4226585536) | 1ee6c37feb | declined before the full-resolution return |
| [numeric equality vs. representation](https://github.com/apache/superset/pull/43870#discussion_r4226585540) | 159185ed03 | probe value coerced losslessly to the column's int/float type |
| [preview reason for text equality](https://github.com/apache/superset/pull/43870#discussion_r4226585543) | a533814e7b | separate message when `equality_mirrors_safely` withdraws `=`/`IN` |
| [preview on array columns](https://github.com/apache/superset/pull/43870#discussion_r4226585547) | 1fa334d289 | preview probes the same array literal as the chart path |
| [sample for numeric temporal columns](https://github.com/apache/superset/pull/43870#discussion_r4226585551) | dee9cca8f8 | epoch sample for `epoch_s`/`epoch_ms` BIGINT columns |
| [partition column help text](https://github.com/apache/superset/pull/43870#discussion_r4200141981) | e61585070e | help text no longer says the column is hidden from Explore |
| — | d808efd1f0 | regenerated message catalogs for the strings above |
**Left open for Hugh / reviewers:**
- [Per-column collation for equality mirroring](https://github.com/apache/superset/pull/43870#discussion_r4174107534). Engine-level semantics are handled (f3f49af437), but a column-level `COLLATE` on a byte-exact engine can't be detected. Closing it needs a product decision (an owner opt-in, or collation reflection), so I didn't guess. Details are on the thread.
**Unresolved threads already addressed by Hugh's earlier commits.** These had no reply. I checked each one against the current code and found it fixed; SHAs refer to the rebased history. I haven't resolved any threads, so that's for the reviewers.
<details><summary>59 threads</summary>
| Thread | Finding | Fixed in |
|---|---|---|
| [partition_mapping.py](https://github.com/apache/superset/pull/43870#discussion_r4174107532) | On MySQL, this compilation doubles the percent signs in `date_format(:value, '%Y%m%d')`, but the probe… | 1f65535fe4 |
| [DatasourceEditor.tsx](https://github.com/apache/superset/pull/43870#discussion_r4174107536) | With partition filter mapping disabled, changing the default datetime column away and back still clears… | 24ca0e49b2 |
| [schemas.py](https://github.com/apache/superset/pull/43870#discussion_r4174107539) | PUT accepts a null monotonicity flag and export includes that null, but this import field rejects it, so… | b9e388c6c4 |
| [partition_mapping.py](https://github.com/apache/superset/pull/43870#discussion_r4174107543) | Preview can return a valid emitted predicate for a mapped column with an active advanced data type,… | 3fc2465e6b |
| [partition_mapping.py](https://github.com/apache/superset/pull/43870#discussion_r4175105706) | A transform such as `secret \|\| :value FROM vault` passes the single-expression and subquery checks even… | 681400f504 |
| [helpers.py](https://github.com/apache/superset/pull/43870#discussion_r4175105710) | These outer-window partition predicates also enter the series-limit subquery through `where_clause_and`,… | 84439af53b |
| [helpers.py](https://github.com/apache/superset/pull/43870#discussion_r4175105716) | The probe uses this Python datetime, while the original filter renders it through `dttm_sql_literal` and… | 2bc3d778d3 |
| [utils.py](https://github.com/apache/superset/pull/43870#discussion_r4175105718) | PUT deliberately saves an unfinished transform such as `unix_timestamp(:value` as inactive, but exporting… | 4e9e76c629 |
| [useDebouncedCommit.ts](https://github.com/apache/superset/pull/43870#discussion_r4175105723) | This queues the commit callback from the input event, whose `CollectionTable.onFieldsetChange` still… | 24ca0e49b2 |
| [DatasourceEditor.tsx](https://github.com/apache/superset/pull/43870#discussion_r4175105726) | These partition defaults and the edited transform live in `databaseColumns`, but `syncMetadata` merges… | 24ca0e49b2 |
| [create.py](https://github.com/apache/superset/pull/43870#discussion_r4175105730) | Passing `main_dttm_col=None` lets POST accept `partition_column='event_time'` without an override when… | 85b1addb68 |
| [api.py](https://github.com/apache/superset/pull/43870#discussion_r4175105733) | Saving the dataset from Explore reloads this GET response and replaces the Explore datasource with it, but… | e722491958 |
| [partition_mapping.py](https://github.com/apache/superset/pull/43870#discussion_r4175105736) | Reading the probe through `frame.iloc[0]` coerces mixed numeric columns to a common float dtype. On… | 1f65535fe4 |
| [dataset.py](https://github.com/apache/superset/pull/43870#discussion_r4175105739) | When one PUT renames the partition column from `old_part` to `new_part` and updates `partition_column`,… | fced8ba878 |
| [partition_mapping.py](https://github.com/apache/superset/pull/43870#discussion_r4179203234) | With a transform of `':value'`, a sample of ` \|\| (SELECT secret FROM vault LIMIT 1) \|\| ` compiles into… | e84b6d2abb |
| [partition_mapping.py](https://github.com/apache/superset/pull/43870#discussion_r4179203236) | Mixed probe results such as `[33, 29.02]` make SQLAlchemy infer an integer IN bind from the first value,… | e84b6d2abb |
| [helpers.py](https://github.com/apache/superset/pull/43870#discussion_r4179203238) | For a numeric IN filter containing `['9007199254740993', '1.5']`, the original predicate later normalizes… | e84b6d2abb |
| [helpers.py](https://github.com/apache/superset/pull/43870#discussion_r4179203241) | On ClickHouse, `time_groupby_inline` skips the ranking subquery's time predicate, but these mirrors still… | e84b6d2abb |
| [DatasourceEditor.tsx](https://github.com/apache/superset/pull/43870#discussion_r4179203243) | A calculated mapped-column override accepted by PUT/import is absent from `databaseColumns`, so reopening… | 3ba0f3cce6 |
| [partition_mapping.py](https://github.com/apache/superset/pull/43870#discussion_r4179203246) | Preview passes string samples directly to the probe, while chart filters first coerce numeric-column… | e84b6d2abb |
| [views.py](https://github.com/apache/superset/pull/43870#discussion_r4179203248) | This legacy save accepts a valid transform longer than 1,024 characters, such as `lower(` plus 1,100… | e84b6d2abb |
| [partition_mapping.py](https://github.com/apache/superset/pull/43870#discussion_r4179203251) | This error and seven other new strings are absent from `messages.pot`, leaving them outside the… | 6b25a733cb |
| [update_test.py](https://github.com/apache/superset/pull/43870#discussion_r4179203253) | The pre-commit mypy check fails here because `_model` is typed as `SqlaTable \| None`; setting it in the… | e84b6d2abb |
| [partition_mapping.py](https://github.com/apache/superset/pull/43870#discussion_r4185020713) | A bare scalar can still read tables: PostgreSQL's `schema_to_xml` passes these checks and the default… | 90bc18f54a |
| [helpers.py](https://github.com/apache/superset/pull/43870#discussion_r4185020733) | On a mapped virtual dataset using `current_username()`, cache-key extraction calls `get_sqla_query()`… | 380956a582 |
| [DatasourceEditor.tsx](https://github.com/apache/superset/pull/43870#discussion_r4185020751) | Clicking Customize the value transform now filters to the mapped column but leaves its row collapsed: the… | ea3ecf6514 |
| [models.py](https://github.com/apache/superset/pull/43870#discussion_r4185020761) | Duplicating a mapped virtual dataset copies these references through `table.override()`, but… | e278dd0368 |
| [update.py](https://github.com/apache/superset/pull/43870#discussion_r4185020773) | After the dedicated metadata-refresh endpoint removes a dropped partition column, its stored mapping… | 4b93825cd9 |
| [partition-filter-mapping.mdx](https://github.com/apache/superset/pull/43870#discussion_r4185020783) | With the default `CACHE_CONFIG` (NullCache), enabling this feature leaves previews unthrottled and probe… | 9c93e1072d |
| [partition_mapping.py](https://github.com/apache/superset/pull/43870#discussion_r4186147475) | For an array filter whose rendered literal contains escaped backslashes, this regex replacement changes… | 0690d1eb10 |
| [helpers.py](https://github.com/apache/superset/pull/43870#discussion_r4186147491) | For TIMESTAMP equality/IN filters supplied as epoch milliseconds, the handler returns SQLAlchemy… | 63cb0cdd98 |
| [schemas.py](https://github.com/apache/superset/pull/43870#discussion_r4186147507) | On overwrite import, replacing a declared-monotonic transform with `hour(:value)` while omitting this… | 605276f407 |
| [utils.py](https://github.com/apache/superset/pull/43870#discussion_r4186147517) | An overwrite import that clears the mapped-column override can activate an old transform parked on the… | 52c758a4dd |
| [partition_mapping.py](https://github.com/apache/superset/pull/43870#discussion_r4191232092) | The count check can be satisfied by the owner writing `superset_pfm_value_standin` themselves. In… | 770a0e00c8 |
| [partition_mapping.py](https://github.com/apache/superset/pull/43870#discussion_r4191232095) | The exemption for `STRING` partition columns assumes every engine accepts a number in a text comparison,… | e61f2905af |
| [partition_mapping.py](https://github.com/apache/superset/pull/43870#discussion_r4191232101) | Preview passes `_probe_input` straight into `build_mirrored_predicates`, but chart filters go through… | 8dd7a5449d |
| [helpers.py](https://github.com/apache/superset/pull/43870#discussion_r4191232106) | This adds an inner-window partition mirror for `main_dttm_col`, but the series-limit subquery only gets a… | b6df89506e |
| [refresh.py](https://github.com/apache/superset/pull/43870#discussion_r4198455452) | A metadata refresh can switch on a transform nobody chose: if `fetch_metadata` or the dangling-reference… | 403df88c48 |
| [partition_mapping.py](https://github.com/apache/superset/pull/43870#discussion_r4198455460) | A transform such as `:value::bigint` passes validation (`:value\b` matches) but never binds here:… | 403df88c48 |
| [partition_mapping.py](https://github.com/apache/superset/pull/43870#discussion_r4198455475) | Accepting any `str` for a temporal partition column means a mirror can fail the chart rather than decline:… | 403df88c48 |
| [partition_mapping.py](https://github.com/apache/superset/pull/43870#discussion_r4198455483) | The probe cache key covers the database record but not the identity the warehouse runs the query as, so… | 403df88c48 |
| [DatasourceEditor.tsx](https://github.com/apache/superset/pull/43870#discussion_r4198455490) | `handleNavigateToColumn` sets `activeTabKey`, but the tabs only receive `defaultActiveKey`, which antd… | 403df88c48 |
| [PartitionMappingSection.tsx](https://github.com/apache/superset/pull/43870#discussion_r4198455495) | Every expanded row reports to the same `onPreviewVerdict`, and rows that aren't the mapped column report… | 403df88c48 |
| [PartitionColumnFields.tsx](https://github.com/apache/superset/pull/43870#discussion_r4198455505) | `datasource.partition_filter_mapping?.evaluable !== false` is the summary from when the editor opened, so… | 403df88c48 |
| [utils.ts](https://github.com/apache/superset/pull/43870#discussion_r4198455517) | This rejects every resolved self-mapping, but the backend deliberately lets the implicit one through as a… | 403df88c48 |
| [partition_mapping.py](https://github.com/apache/superset/pull/43870#discussion_r4200141993) | `_probe_input` always returns `handled` and never `UNMIRRORABLE`; the decline happens in… | 403df88c48 |
| [partition_mapping.py](https://github.com/apache/superset/pull/43870#discussion_r4202018855) | The shape gates here inspect sqlglot's parse of the SQL, but this executes the original text, and sqlglot… | 403df88c48 |
| [partition_mapping.py](https://github.com/apache/superset/pull/43870#discussion_r4202018858) | This records a dataset-specific outcome (this partition column can't hold the probed type) under… | 403df88c48 |
| [usePartitionMappingPreview.ts](https://github.com/apache/superset/pull/43870#discussion_r4202018863) | A transform longer than 1,024 characters that contains `:value` makes the preview schema return HTTP 400… | 403df88c48 |
| [UPDATING.md](https://github.com/apache/superset/pull/43870#discussion_r4202018869) | The note lists only the four newly denied XML functions, but this PR also adds `ts_rewrite` and `ts_stat`… | 403df88c48 |
| [partition-filter-mapping.mdx](https://github.com/apache/superset/pull/43870#discussion_r4202018871) | `FEATURE_FLAGS` values aren't evaluated per request: `FeatureFlagManager` returns configured values… | 403df88c48 |
| [partition_mapping_preview_test.py](https://github.com/apache/superset/pull/43870#discussion_r4202018874) | Every preview endpoint test runs with `raise_for_editorship` patched out here, and… | 403df88c48 |
| [helpers.py](https://github.com/apache/superset/pull/43870#discussion_r4202688638) | The mirror is probed with `dttm.strftime(tf)` whenever a `python_date_format` is set, but… | 403df88c48 |
| [partition_mapping_test.py](https://github.com/apache/superset/pull/43870#discussion_r4202688644) | `lower(:value), 'x'` is refused by `stored_expression_error` (not a single expression) before `get_df` is… | 403df88c48 |
| [views.py](https://github.com/apache/superset/pull/43870#discussion_r4202688646) | The legacy save now refuses an unsafe transform, but `partition_column` and `partition_mapped_column` ride… | 403df88c48 |
| [helpers.py](https://github.com/apache/superset/pull/43870#discussion_r4224320536) | This rounds the bound for any mapped column whose engine renders datetimes, not only temporal ones.… | 32f997b826 |
| [views.py](https://github.com/apache/superset/pull/43870#discussion_r4224320545) | The legacy save only runs `stored_expression_error` on a changed transform, while the REST path and the… | 32f997b826 |
| [utils.py](https://github.com/apache/superset/pull/43870#discussion_r4224320560) | This cleanup only drops references to columns that no longer exist. A bundle that sets both… | 32f997b826 |
| [partition_mapping_test.py](https://github.com/apache/superset/pull/43870#discussion_r4224320575) | On `sqlite://` both `database.backend` and `database.db_engine_spec.engine` are `"sqlite"`, so this passes… | 32f997b826 |
</details>
**Testing.** Backend unit suites for the touched areas pass locally: connectors, models, datasets, dataset DAO and commands, SQL parsing, datasource views, translations, engine specs and migrations — 5,483 passed. Ruff, pylint and mypy pre-commit hooks pass on the changed files, and `check_pot_drift.py` is clean. `node_modules` wasn't available here, so the frontend change (dee9cca8f8, e61585070e) relies on CI for jest/tsc.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4234427163
##########
superset/models/helpers.py:
##########
@@ -4334,36 +4432,715 @@ def dttm_sql_literal(self, dttm: datetime, col: "TableColumn") -> str:
return f"""'{dttm.strftime("%Y-%m-%d %H:%M:%S.%f")}'"""
- def get_time_filter( # pylint: disable=too-many-arguments # noqa: C901
+ def _mirror_probe_value(self, dttm: datetime, col: Optional["TableColumn"]) -> Any:
+ """
+ ``dttm`` in the mapped column's own stored representation.
+
+ The predicate this mirror stands in for compares the column against
+ `dttm_sql_literal(dttm, col)`, so the transform has to be probed with
+ the same value. On a column stored as an epoch integer, ``T`` is a
+ function of an integer: probing it with a `datetime` either returns
+ something unrelated to the partition keys or raises, and a raise costs
+ the dataset its pruning silently.
+
+ Only the ``python_date_format`` branches of `dttm_sql_literal` are
+ reproduced, because only those produce a *value*. `convert_dttm` yields
+ engine-specific SQL text, which cannot be bound as a parameter; its own
+ divergence from the probe is handled by widening the bounds instead
+ (`_engine_literal_resolution`).
+
+ In `dttm_sql_literal`'s own order, though: it asks ``convert_dttm``
+ first and reaches the format only when the engine answers nothing. A
+ column can carry both -- a TIMESTAMP with a ``%Y%m%d``
+ ``python_date_format``, or an entry in
+ ``python_date_format_by_column_name`` -- and applying the format
+ unconditionally probed a value the real predicate never compares.
+ ``event_time >= '2026-01-01 00:00:00'`` mirrored as
+ ``partition_col >= '20260101'``, and a January 15 row keyed
+ ``2026-01-15`` sorts below that string, so the chart lost a row the
+ filter keeps.
+
+ Where the engine does answer, the `datetime` is returned unchanged and
+ the widening path takes over -- which is exactly what already happens
+ for every temporal column that carries no format at all.
+ """
+ if col is None:
+ return dttm
+
+ if col.type and self.db_engine_spec.convert_dttm(
+ col.type, dttm, db_extra=self.db_extra
+ ):
+ # The format is unreachable in `dttm_sql_literal` for this column,
+ # so reproducing it here would describe a different bound.
+ return dttm
+
+ tf = col.python_date_format
+ if not tf and self.db_extra:
+ tf = self.db_extra.get("python_date_format_by_column_name", {}).get(
+ col.column_name
+ )
+ if not tf:
+ return dttm
+
+ if tf in EPOCH_FORMATS:
+ dttm_tz_aware = dttm
+ if dttm_tz_aware.tzinfo is None:
+ dttm_tz_aware = dttm_tz_aware.replace(tzinfo=timezone.utc)
+ return int(dttm_tz_aware.timestamp()) * EPOCH_FORMATS[tf]
+ return dttm.strftime(tf)
+
+ def _engine_literal_resolution(
+ self, dttm: datetime, col: Optional["TableColumn"]
+ ) -> LiteralResolution:
+ """
+ How much of ``dttm`` survives into this engine's literal for ``col``.
+
+ The real predicate compares `dttm_sql_literal(dttm, col)`, so whatever
+ that literal throws away is a bound the engine never sees. A mirror
+ derived from the full precision then describes a *narrower* range than
+ the predicate it stands in for -- and narrower means it drops rows the
+ filter keeps.
+
+ Two things get thrown away in practice:
+
+ - the sub-second part. SQLite renders a timestamp with
+ ``timespec="seconds"``.
+ - the time of day entirely. Every engine spec with a ``types.Date``
+ branch renders ``dttm.date().isoformat()``, so Presto, Trino,
+ BigQuery and some two dozen others answer `DATE '2026-01-01'` for a
+ bound of 10:00 -- and `T(DATE '2026-01-01')` is below the mirror's
+ own lower bound, so the whole first day is dropped.
+
+ Detected rather than enumerated per engine, because the branch depends
+ on the column's type as well as the spec: instants differing only in the
+ part under test render as the same text exactly when the engine has
+ thrown that part away.
+
+ The day test uses two fixed times of day rather than ``dttm`` and one
+ alternative, so a bound that happens to sit on the hour the alternative
+ uses cannot read as "no time at all". Neither probe sits at midnight on
+ purpose: SQLite renders a DATE column at exactly midnight as a bare
+ date, so a midnight probe would differ from its alternative for a
+ reason that has nothing to do with resolution.
+
+ Likewise both sub-second probes carry a non-zero remainder. Comparing
+ against ``dttm`` truncated to the second looks like the obvious test and
+ is wrong for the same formatting-boundary reason.
+
+ A non-temporal column has no answer here, and asking anyway gets a wrong
+ one. SQLite's ``convert_dttm`` renders for ``types.String`` as well as
+ for the date types, so a ``VARCHAR`` mapped column reads as
+ second-resolution -- and a filter value that happens to *look* like an
+ instant then has its bound rounded as though the engine had truncated
+ it. On a VARCHAR ``code`` mapped onto a VARCHAR ``p`` by ``:value``,
+ ``code < '2026-07-06T10:08:11.500000'`` was mirrored as
+ ``p <= '2026-07-06 10:08:12.000000'``; a space sorts before ``T``, so a
+ row holding ``2026-07-06T09:00:00`` fell outside the mirror while
+ matching the filter.
+
+ The guard lives here rather than in each caller so this and
+ `_column_literal_resolution` cannot disagree about which column is
+ coarse -- which is the same reason that helper delegates to this one.
+
+ "Temporal" is the column's generic type, not just its ``is_dttm`` flag.
+ `get_time_filter` renders a bound through ``convert_dttm`` for any
+ ``DATE`` column, flagged or not, so a ``DATE`` column left unflagged
+ still compares a bare day -- and skipping the resolution check there
+ would hand the probe 10:00 for a bound the engine reads as midnight.
+ """
+ if col is None or not col.type or col.type_generic != GenericDataType.TEMPORAL:
+ return LiteralResolution.FULL
+
+ def render(moment: datetime) -> Optional[str]:
+ return self.db_engine_spec.convert_dttm(
+ col.type, moment, db_extra=self.db_extra
+ )
+
+ try:
+ early = render(dttm.replace(hour=1, minute=2, second=3, microsecond=444444))
+ late = render(
+ dttm.replace(hour=22, minute=33, second=44, microsecond=555555)
+ )
+ if early is not None and early == late:
+ return LiteralResolution.DAY
+
+ # Flooring to the second is a no-op on a bound that has no
+ # sub-second part, so there is nothing to detect.
+ if not dttm.microsecond:
+ return LiteralResolution.FULL
+
+ first = render(dttm.replace(microsecond=111111))
+ second = render(dttm.replace(microsecond=222222))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return LiteralResolution.FULL
+
+ if first is not None and first == second:
+ return LiteralResolution.SECOND
+ return LiteralResolution.FULL
+
+ def _round_bounds_outward(
self,
- time_col: "TableColumn",
+ start_dttm: Optional[datetime],
+ end_dttm: Optional[datetime],
+ col: Optional["TableColumn"],
+ ) -> tuple[Optional[datetime], Optional[datetime]]:
+ """
+ The bounds widened to whatever the engine's literal actually resolves to.
+
+ Rounding outward is never narrower than the predicate being mirrored,
+ which is the only property the mirror has to hold.
+ """
+ resolutions = {
+ self._engine_literal_resolution(bound, col)
+ for bound in (start_dttm, end_dttm)
+ if bound is not None
+ }
+
+ if LiteralResolution.DAY in resolutions:
+ # The engine compares a bare date, so the real predicate's lower
+ # bound is the start of that day and its upper bound admits the
+ # whole of the day before. Anything finer excludes rows it keeps.
+ if start_dttm is not None:
+ start_dttm = start_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ )
+ if end_dttm is not None and end_dttm != end_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ ):
+ end_dttm = end_dttm.replace(
+ hour=0, minute=0, second=0, microsecond=0
+ ) + timedelta(days=1)
+ elif LiteralResolution.SECOND in resolutions:
+ if start_dttm is not None:
+ start_dttm = start_dttm.replace(microsecond=0)
+ if end_dttm is not None and end_dttm.microsecond:
+ end_dttm = end_dttm.replace(microsecond=0) + timedelta(seconds=1)
+
+ return start_dttm, end_dttm
+
+ def _literal_is_coarser_than(
+ self, dttm: datetime, col: Optional["TableColumn"]
+ ) -> bool:
+ """
+ Whether the engine's literal for ``dttm`` throws away part of it.
+
+ Unlike a range, an equality cannot be widened outward, so the only safe
+ answer when the engine compares less than the full value is to decline
+ the mirror.
+ """
+ resolution = self._engine_literal_resolution(dttm, col)
+ if resolution is LiteralResolution.DAY:
+ return dttm != dttm.replace(hour=0, minute=0, second=0, microsecond=0)
+ if resolution is LiteralResolution.SECOND:
+ return bool(dttm.microsecond)
+ return False
+
+ def _column_literal_resolution(
+ self, col: Optional["TableColumn"]
+ ) -> LiteralResolution:
+ """
+ How much of *any* value this engine compares on ``col``.
+
+ `_engine_literal_resolution` answers about a particular instant, which
+ is what a mirror derived from one needs. Two callers have no instant to
+ ask about -- the summary the Explore glyph reads, and a filter value
+ `_instant_from_filter_value` cannot read as an instant at all -- and
+ both need the column's own answer. Through one helper so that the glyph
+ and the query path cannot disagree about which column is coarse, which
+ is the same reason `mirrorable_operators` is computed once.
+
+ A non-temporal column has no answer, and asking anyway gets a wrong one:
+ SQLite's ``convert_dttm`` renders for ``types.String`` as well as for the
+ date types, so a reference instant makes a ``VARCHAR`` mapped column look
+ second-resolution -- and ``country = 'US'``, the text half of this
+ feature, reads as a value the engine compares coarsely.
+
+ That guard is `_engine_literal_resolution`'s, not this function's. It
+ used to be here, on the belief that the per-instant callers never met
+ the case because they arrive only with a value that parsed as an
+ instant -- which is untrue of a text column holding ISO-shaped text,
+ where the value parses and the column is still not temporal.
+ """
+ return self._engine_literal_resolution(_RESOLUTION_REFERENCE_INSTANT, col)
+
+ def _round_bound_outward(
+ self,
+ instant: datetime,
+ col: Optional["TableColumn"],
+ *,
+ is_upper: bool,
+ ) -> datetime:
+ """
+ One bound widened to whatever the engine resolves ``col`` to.
+
+ `_round_bounds_outward` answers for a since/until pair, because a time
+ range is the shape it was written for. A single comparison is one end of
+ such a pair with the other end absent, and the widening is per-end
+ already -- a lower bound moves back, an upper bound forward.
+
+ Narrowing the return type is the other half of the point: a bound handed
+ in non-`None` comes back non-`None`, and saying so here saves every
+ caller from re-establishing it.
+ """
+ start_dttm, end_dttm = self._round_bounds_outward(
+ None if is_upper else instant,
+ instant if is_upper else None,
+ col,
+ )
+ rounded = end_dttm if is_upper else start_dttm
+ return rounded if rounded is not None else instant
+
+ def _in_column_number_type(self, value: Any, col: Optional["TableColumn"]) -> Any:
+ """
+ A numeric ``value`` in the number type the mapped column stores.
+
+ The engine compares a number against the column in the column's own
+ domain, so ``n = '1.0'`` on an integer ``n`` matches the row holding
+ ``1``. `filter_values_handler` hands over ``1.0``, though, and a
+ transform whose output depends on the representation --
+ ``CAST(:value AS TEXT)`` answers ``'1.0'`` where the row's key is
+ ``'1'`` -- then mirrors to a partition value no matching row holds.
+ Probing at the value the column would hold keeps ``T(col) = T(v)``.
+
+ Only lossless conversions: an integral number for an integer column, a
+ number a float represents exactly for a float column. Anything else is
+ returned unchanged -- a non-integral value on an integer column matches
+ no row, so its mirror cannot drop one, and a ``DECIMAL`` column's text
+ depends on a scale the spec does not expose.
+ """
+ if (
+ col is None
+ or not col.type
+ or isinstance(value, bool)
+ or not isinstance(value, (int, float, Decimal))
+ ):
+ return value
+ try:
+ column_spec = self.db_engine_spec.get_column_spec(
+ col.type, db_extra=self.db_extra
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return value
+ if column_spec is None:
+ return value
+ sqla_type = column_spec.sqla_type
+ type_class = sqla_type if isinstance(sqla_type, type) else type(sqla_type)
+ if issubclass(type_class, sa.Integer):
+ if isinstance(value, int):
+ return value
+ try:
+ return int(value) if value == int(value) else value
+ except (OverflowError, ValueError):
+ # Infinity and NaN have no integer, and match no integer row.
+ return value
+ if issubclass(type_class, sa.Float) and float(value) == value:
+ return float(value)
+ return value
+
+ def _mirror_probe_input(
+ self,
+ operator: utils.FilterOperator,
+ value: Any,
+ col: Optional["TableColumn"],
+ ) -> Any:
+ """
+ ``value`` in the representation the mirror may probe the transform at.
+
+ A simple filter on a temporal column carries a *string*.
+ `filter_values_handler` rewrites only an all-digit value, which it reads
+ as epoch milliseconds, so ``'2026-07-06 10:08:11'`` reaches here exactly
+ as the chart author typed it and is bound as text. The engine compares
+ that text against the column under its own cast, and on a ``DATE``
+ column the cast drops the time of day: the filter keeps the whole of
+ 2026-07-06 while a mirror probed at 10:08:11 keeps one instant of it,
+ which is narrower than the predicate it stands in for.
+
+ So the text is read back into the instant it denotes -- the only way
+ `_engine_literal_resolution`, which answers about a `datetime`, reaches
+ a filter value at all -- and where the engine compares less of that
+ instant than the filter carries, what to do about it is a property of
+ the *operator*:
+
+ * a bound rounds outward, through the helper the range collector uses.
+ Reading one extra bucket at the edge is the trade this feature makes
+ everywhere else too -- see `mirror_operator` -- and the original
+ predicate is still in the query to exclude the rows that bucket adds.
+ * an equality, or one member of an ``IN`` list, has nowhere to widen to.
+ These entries are ``AND``-ed onto the query, so "or the day either
+ side" is not something this sink can express, and the request is
+ declined with `_UNMIRRORABLE`. The query is then correct and unpruned,
+ which is the one failure mode this feature is allowed.
+
+ An instant carrying a UTC offset is declined for every operator, a
+ bound included. Rounding one outward would first have to place it in the
+ frame the partition column was written in, and guessing that frame is
+ how a mirror ends up a whole offset narrower than the filter -- see the
+ load-bearing assumption in
+ `superset.connectors.sqla.partition_mapping`.
+
+ A *string* `_instant_from_filter_value` cannot read at all is declined on
+ the same terms, and for the same reason one more step back: there is no
+ instant to round. ``'07/06/2026 10:08:11'`` is not ISO 8601, so the
+ parser leaves it alone -- and Postgres casts that same text to a DATE and
+ keeps the whole of July 6 while the probe, handed the string verbatim,
+ evaluates the transform at 10:08:11 and asks for a partition key no row
+ holds. That is exactly the narrowing the ISO-only parser was written to
+ prevent, reached through a value it declines to read, so the decline has
+ to travel with it. Which costs a non-ISO *date* its pruning too, because
+ telling July 6 from June 7 is the guess that started this.
+
+ Only a string. `_as_probe_input` has already run, so the engine SQL
+ `filter_values_handler` returns for an epoch-millisecond bound arrives
+ here as a `RawProbeValue` rather than text -- and that literal was
+ rendered by the engine at the engine's own resolution, so it is the one
+ thing on this path with nothing left to resolve.
+
+ Where the engine compares the whole instant, a string is returned
+ exactly as it arrived -- down to the type the probe binds and the cache
+ key it lands on, because every query that was already correct has to
+ stay byte-for-byte correct. A `datetime` is still converted, which it
+ has always needed: on a column stored as an epoch integer the transform
+ is a function of an integer, and a `datetime` is not the value the real
+ predicate compares.
+ """
+ value = self._in_column_number_type(value, col)
+ parsed = _instant_from_filter_value(value)
+ if parsed is None:
+ if (
+ isinstance(value, str)
+ and self._column_literal_resolution(col) is not LiteralResolution.FULL
+ ):
+ return _UNMIRRORABLE
+ return value
+
+ # Ahead of the full-resolution return: a transform such as
+ # `CAST(:value AS TIMESTAMP)` drops the offset, so even an engine that
+ # compares the whole instant would probe it in the wrong frame.
+ if parsed.tzinfo is not None:
+ return _UNMIRRORABLE
+
+ if self._engine_literal_resolution(parsed, col) is LiteralResolution.FULL:
+ return (
+ self._mirror_probe_value(parsed, col)
+ if isinstance(value, datetime)
+ else value
+ )
+
+ if operator in LOWER_BOUND_OPERATORS:
+ instant = self._round_bound_outward(parsed, col, is_upper=False)
+ elif operator in UPPER_BOUND_OPERATORS:
+ instant = self._round_bound_outward(parsed, col, is_upper=True)
+ elif self._literal_is_coarser_than(parsed, col):
+ return _UNMIRRORABLE
+ else:
+ instant = parsed
+
+ if instant == parsed and not isinstance(value, datetime):
+ return value
+ return self._mirror_probe_value(instant, col)
+
+ def _collect_partition_mirror_range(
+ self,
+ mapping: Optional["PartitionMapping"],
+ sink: list[tuple[utils.FilterOperator, Any]],
+ column_name: str,
start_dttm: Optional[sa.DateTime],
end_dttm: Optional[sa.DateTime],
- time_grain: Optional[str] = None,
- label: Optional[str] = "__time",
- template_processor: Optional[BaseTemplateProcessor] = None,
- ) -> Optional[ColumnElement]:
- col = (
- time_col.get_timestamp_expression(
- time_grain=time_grain,
- label=label,
- template_processor=template_processor,
+ widen_bounds_by: Optional[relativedelta] = None,
+ ) -> None:
+ """
+ Record a time range for mirroring onto the partition column.
+
+ The bounds are adjusted first, by the same helper `get_time_filter` uses:
+ the mirrored predicate has to describe the same instants as the
+ timestamp predicate it stands in for, or the pruning is wrong by exactly
+ the dataset's timezone offset -- silently.
+
+ Either bound may be `None` for an open-ended range, in which case only
+ the bound that exists is mirrored.
+
+ Both bounds are recorded with the operators the real predicate uses,
+ `>=` and `<`. Relaxing the strict one is `mirror_operator`'s job, at the
+ single point where an operator becomes SQL -- which is also the point
+ the preview endpoint goes through.
+
+ `widen_bounds_by` is one grain bucket width, passed when the filter this
+ stands in for compares a *truncated* column. The real predicate then
+ keeps rows the raw bounds exclude, and widening both ends by one bucket
+ is the smallest range guaranteed to contain all of them -- see the "Time
+ grains" section of `superset.connectors.sqla.partition_mapping`.
+
+ A widened range can also be wide enough to fail `_bounds_are_ordered`
+ against a tighter filter on the same column. That fails open -- no
+ mirroring, no pruning, no dropped rows.
+ """
+ if mapping is None or column_name != mapping.mapped_column:
+ return
+ if not mapping.mirrors(utils.FilterOperator.TEMPORAL_RANGE):
+ return
+
+ # Resolve the column so the offset adjustment sees the same type
+ # `get_time_filter` does -- an offset the column's type cannot represent
+ # is dropped, and the mirrored bounds have to agree with the originals.
+ mapped_col = next(
+ (col for col in self.columns if col.column_name == column_name), None
+ )
+ start_dttm, end_dttm = self.adjust_time_bounds(start_dttm, end_dttm, mapped_col)
+
+ # Adjust first, then widen. `adjust_time_bounds` moves the naive UI
+ # bounds into the frame the column is *stored* in, and the grain
+ # truncation in the real predicate happens in that same frame, so the
+ # bucket width has to be added there too. The two commute for the
+ # hour-offset branch but not for the `ZoneInfo` one, where widening
+ # across a DST boundary first lands an hour out.
+ if widen_bounds_by is not None:
+ if start_dttm is not None:
+ start_dttm -= widen_bounds_by
+ if end_dttm is not None:
+ end_dttm += widen_bounds_by
+
+ # Then round outward, to whatever the engine's literal resolves to.
+ start_dttm, end_dttm = self._round_bounds_outward(
+ start_dttm, end_dttm, mapped_col
+ )
+
+ # Converted last. The widening and rounding above are `datetime`
+ # arithmetic, and the stored representation may be an integer.
+ if start_dttm is not None:
+ sink.append(
+ (
+ utils.FilterOperator.GREATER_THAN_OR_EQUALS,
+ self._mirror_probe_value(start_dttm, mapped_col),
+ )
)
- if time_grain
- else self.convert_tbl_column_to_sqla_col(
- time_col, label=label, template_processor=template_processor
+ if end_dttm is not None:
+ sink.append(
+ (
+ utils.FilterOperator.LESS_THAN,
+ self._mirror_probe_value(end_dttm, mapped_col),
+ )
)
+
+ def _array_mirror_probe_value(
+ self,
+ value: Any,
+ operator: utils.FilterOperator,
+ element_type: Optional[utils.GenericDataType],
+ db_engine_spec: builtins.type["BaseEngineSpec"],
+ ) -> Any:
+ """
+ The array literal the real predicate compares, ready to probe with.
+
+ On an array column the predicate is not built from `eq` at all: the
+ branch below reads the raw `val`, parses the pasted literal into
+ elements, coerces them to the array's element type and asks the engine
+ spec for its own array syntax. Mirroring `eq` would probe the transform
+ at a value the query never compares, so this reproduces that chain
+ instead -- the mirror then probes exactly what the predicate holds.
+
+ The result is SQL text rather than a value, because an array literal is
+ an expression; `RawProbeValue` carries it and `build_probe_sql`
+ substitutes rather than binds. Returns `None` when the engine spec
+ claims multi-value columns without implementing a literal for them,
+ which costs the query its pruning and nothing else.
+ """
+
+ def literal(entry: Any) -> Any:
+ return raw_probe_value(
+ self.database,
+ db_engine_spec.array_literal(
+ coerce_array_values(parse_array_literal(entry), element_type)
+ ),
+ )
+
+ try:
+ if operator in {utils.FilterOperator.IN, utils.FilterOperator.NOT_IN}:
+ candidates = (
+ list(value) if isinstance(value, (list, tuple)) else [value]
+ )
+ return tuple(literal(candidate) for candidate in candidates)
+ return literal(value)
+ except NotImplementedError:
Review Comment:
Preview now reaches this for array samples, and a non-scalar element (`[[1, 2]]` on an `Array(Array(Int32))` column, `[1j]`) raises `CompileError` from the literal render, so preview returns 500 instead of declining.
```suggestion
except (NotImplementedError, sa.exc.CompileError):
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "hughhhh (via GitHub)" <gi...@apache.org>.
hughhhh commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4319671452
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,1613 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import re
+from dataclasses import dataclass
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: Every entry point enforces it -- the typed column field, the import schema
+#: and the preview request -- because `is_transform_active` parses the stored
+#: value on each Explore load, and an unbounded string would make that parse
+#: the expensive part of rendering a chart.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: Balanced Jinja blocks. The probe would render these in a different context
+#: at a different time from the chart query, so they are rejected at save time.
+JINJA_BLOCK_RE = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.DOTALL)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate.
+NON_DETERMINISTIC_FUNCTIONS = {
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """Whether the transform contains a balanced Jinja block."""
+ return bool(transform) and JINJA_BLOCK_RE.search(transform or "") is not None
+
+
+def parse_skeleton(transform: str) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+ """
+ return VALUE_PLACEHOLDER_RE.sub(_PARSE_STANDIN, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(transform: str, engine: str) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error(
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ selections = []
+ for index, value in enumerate(values):
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
Review Comment:
Fixed. `probe_sql_is_evaluable` re-reads the finished compiled statement, so the gates and the engine now see the same SQL and a placeholder smuggled inside a quoted literal cannot open a sub-query the validation never saw.
##########
superset/daos/dataset.py:
##########
@@ -476,10 +546,98 @@ def _validate_column_date_formats(
"python_date_format is an invalid date/timestamp format."
)
+ @staticmethod
+ def clear_unmapped_partition_transforms(model: SqlaTable) -> None:
+ """
+ Drop the value transform from every column the mapping does not mirror.
+
+ A mapping has exactly one mirrored column, so at most one column may
+ carry a transform. A transform parked on any other column is invisible
+ -- no row but the mapped one renders one -- yet it is still stored, and
+ it goes live the moment the mapped column resolves back to it. Clearing
+ an override is enough to do that: a null `partition_mapped_column` means
+ "follow `main_dttm_col`", so dropping a mapping would otherwise activate
+ whatever the default datetime column happened to be holding, turning a
+ request to remove a mapping into a request to add a different one.
+
+ Enforced here rather than in the editor alone because the editor is only
+ one writer: a PUT, an `override_columns=true` metadata sync and an
+ import all reach the columns directly. The same argument
+ `clear_dangling_partition_mapping` makes about dangling columns.
+
+ `DatasetDAO.update` calls this twice, before and after it applies the
+ request, and the reason is here rather than only at the call site: this
+ reads the mapping as it stands, so a single call can only enforce the
+ invariant against one of the two resolutions a mapping change has.
+
+ Gated on the feature flag, unlike its sibling, because this discards
+ stored configuration rather than repairing a broken reference. With the
+ flag off nothing mirrors, so there is no armed mapping to disarm and
+ clearing would be pure loss.
+ """
+ if not feature_flag_manager.is_feature_enabled(PARTITION_FILTER_MAPPING_FLAG):
+ return
+
+ mapped_column = (
+ (model.partition_mapped_column or model.main_dttm_col)
+ if model.partition_column
+ else None
+ )
+ # `_upsert_columns` and `_override_columns` insert a new column with
+ # `db.session.add(TableColumn(..., table_id=model.id))` rather than
+ # appending to this relationship, and `BaseDAO.update` does not flush --
+ # so a column created *and* given a transform in the same request was
+ # invisible here and kept it. That is exactly the stray transform this
+ # method exists to clear, waiting for the mapping to resolve back to it.
+ db.session.flush()
+ db.session.expire(model, ["columns"])
+ for column in model.columns:
+ if column.column_name == mapped_column:
+ continue
+ if (
+ column.partition_value_transform
+ or column.partition_transform_is_monotonic
+ ):
+ column.partition_value_transform = None
+ column.partition_transform_is_monotonic = False
+
+ @staticmethod
+ def clear_dangling_partition_mapping(
+ model: SqlaTable, surviving_column_names: set[str]
+ ) -> None:
+ """
+ Drop parts of the partition filter mapping whose columns no longer exist.
+
+ A metadata sync can remove the partition column at the source, which
+ would otherwise leave the dataset pointing at a column that isn't there.
+ The query layer bails out defensively on a dangling mapping, so this is
+ about the dataset's stored state being honest rather than about
+ correctness of the SQL.
+
+ Called from `update_columns` for both write paths: the editor clears the
+ mapping client-side too, but `override_columns=true` (an API-driven
+ metadata sync) bypasses the editor entirely, and the upsert path drops
+ every column the payload omits, so either one can take the mapped
+ column out from under the mapping.
+ """
+ if (
Review Comment:
Fixed. The cleanup is keyed on the final requested references — `requested.get("partition_column", item.partition_column)` and the same for `partition_mapped_column` and `main_dttm_col` — instead of the stored ones, so a rename in the same PUT no longer strikes the surviving mapping.
##########
superset/datasets/api.py:
##########
@@ -323,6 +401,8 @@ class DatasetRestApi(SoftDeleteApiMixin, BaseSupersetModelRestApi):
]
show_columns = show_select_columns + [
"columns.type_generic",
+ # Engine-supplied pre-fill for the editor's value transform input.
+ "partition_value_transform_default",
Review Comment:
Fixed. `partition_filter_mapping` is in the GET's `show_columns` alongside `partition_column` and `partition_mapped_column`, so the save/reload boundary from Explore keeps the pruning indicators.
##########
superset/datasets/schemas.py:
##########
@@ -347,6 +373,12 @@ def fix_extra(self, data: dict[str, Any], **kwargs: Any) -> dict[str, Any]:
datetime_format = fields.String(
allow_none=True, validate=[Length(1, 100), validate_python_date_format]
)
+ partition_value_transform = fields.String(
+ allow_none=True, validate=Length(1, MAX_TRANSFORM_LENGTH)
+ )
+ # Bundles predating the field must not claim their transform preserves
+ # ordering, which would silently enable range mirroring on import.
+ partition_transform_is_monotonic = fields.Boolean(load_default=False)
Review Comment:
Fixed. The import field is `fields.Boolean(allow_none=True)`, matching the model and the PUT schema, so an unchanged export round-trips.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "hughhhh (via GitHub)" <gi...@apache.org>.
hughhhh commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4319662866
##########
superset/commands/dataset/create.py:
##########
@@ -248,5 +253,52 @@ def validate(self) -> None: # noqa: C901
# so a ``viewers`` key would be dropped by the DAO's ``setattr`` loop.
populate_subjects(self._properties, exceptions, include_viewers=False)
+ self._validate_partition_mapping(exceptions)
+
if exceptions:
raise DatasetInvalidError(exceptions=exceptions)
+
+ def _validate_partition_mapping(self, exceptions: list[ValidationError]) -> None:
+ """
+ Reject a partition mapping that cannot work, at create time too.
+
+ `UpdateDatasetCommand` has validated this since the mapping landed, but
+ create did not, so the same mapping accepted on POST and rejected on PUT
+ was reachable -- and once stored it is only reported as broken by the
+ editor, which an API-only caller never opens.
+
+ What create can check is narrower than what update can. The dataset's
+ columns are synced by `fetch_metadata` *after* this runs, so "is that a
+ real column?" has no answer yet; both submitted names are therefore
+ passed as known so the existence checks pass trivially and the checks
+ that do not need a column list still run. There is no column payload on
+ POST either, so no transform can arrive here to validate.
+ """
+ if not is_feature_enabled(PARTITION_FILTER_MAPPING):
+ return
+
+ partition_column = self._properties.get("partition_column")
+ database = self._properties.get("database")
+ if not partition_column or not database:
+ # No database means the caller already has a
+ # `DatabaseNotFoundValidationError`; there is no engine to validate
+ # a mapping against and no value in a second error about it.
+ return
+
+ partition_mapped_column = self._properties.get("partition_mapped_column")
+ for issue in validate_partition_mapping(
+ column_names={
+ name
+ for name in (partition_column, partition_mapped_column)
+ if name is not None
+ },
+ partition_column=partition_column,
+ partition_mapped_column=partition_mapped_column,
+ main_dttm_col=None,
Review Comment:
Fixed. `_validate_partition_mapping_after_sync` runs after `fetch_metadata`, against the real columns and the real `main_dttm_col`, filtered to `issue.blocking`. The implicit self-mapping stays Tier 2 there on purpose — blocking it would recreate the unsaveable dataset the check exists to prevent — and the rejection rolls the partial create back.
##########
superset/commands/dataset/importers/v1/utils.py:
##########
@@ -267,6 +272,72 @@ def _get_template_params(dataset: SqlaTable) -> dict[str, Any]:
return params if isinstance(params, dict) else {}
+def drop_unusable_partition_transforms(config: dict[str, Any]) -> None:
+ """
+ Drop a partition value transform the save path would have rejected.
+
+ Import is the one door into this field that does not go through
+ `UpdateDatasetCommand`, so a bundle can carry a transform holding Jinja or
+ calling a non-deterministic function -- one that will never mirror a filter,
+ and that the editor can only report as broken after the fact. Dropping it on
+ the way in leaves the column with no transform, a state an owner can see and
+ fix, rather than a stored expression that looks configured and is not.
+
+ Deliberately sanitizes rather than raises. A bundle is imported as a whole,
+ and failing someone's entire dataset over one unusable expression is a worse
+ trade than importing the dataset without it. This is the same bargain
+ `DatasetDAO.clear_dangling_partition_mapping` already strikes for a mapping
+ whose column went away.
+
+ Two kinds of check, and only one of them answers to the feature flag. The
+ usability checks ask whether a transform will ever mirror a filter, which
+ is a question about a live feature; with the flag off nothing mirrors, so
+ rewriting the bundle would discard configuration for no gain. The
+ structural check asks whether the expression is one this product stores at
+ all, and that answer does not change with a flag -- an import written while
+ the flag was off would otherwise sit in the metadata DB fully armed,
+ waiting for an operator to turn the flag on.
+ """
+ columns = config.get("columns")
+ if not columns:
+ return
+ if not any(column.get("partition_value_transform") for column in columns):
+ return
+
+ database = db.session.query(Database).filter_by(id=config["database_id"]).first()
+ if database is None:
+ return
+
+ check_usability = is_feature_enabled(PARTITION_FILTER_MAPPING)
+ catalog = config.get("catalog")
+ schema = config.get("schema")
+
+ for column in columns:
+ transform = column.get("partition_value_transform")
+ if not transform:
+ continue
+
+ reasons: list[str] = []
+ if reason := stored_expression_error(database, catalog, schema, transform):
Review Comment:
Fixed. `stored_expression_error` is now asked only when `is_unfinished(transform, database.backend)` is false — the same condition `UpdateDatasetCommand` puts in front of that gate — so a half-typed transform imports in the inactive state PUT stores it in. The structural check still runs with the flag off, deliberately, so a bundle written flag-off cannot sit armed in the metadata DB.
##########
superset/commands/dataset/importers/v1/utils.py:
##########
@@ -582,6 +668,12 @@ def import_dataset( # noqa: C901
if dataset.id is None:
db.session.flush()
+ # A bundle can name a mapped column and still carry transforms on other
+ # columns; the editor's client-side guard never runs here. Left in place, a
+ # transform on an unmirrored column is invisible and still stored, ready to
+ # go live the moment the mapped column resolves back to it.
+ DatasetDAO.clear_unmapped_partition_transforms(dataset)
Review Comment:
Fixed. The cleanup runs against both the old and the new mapping before the import is applied — resolving `partition_column` / `partition_mapped_column` from the config falling back to the stored values — so a parked transform cannot be activated by an overwrite that clears the override.
##########
superset/commands/dataset/importers/v1/utils.py:
##########
@@ -582,6 +734,27 @@ def import_dataset( # noqa: C901
if dataset.id is None:
db.session.flush()
+ # A bundle can name a mapped column and still carry transforms on other
+ # columns; the editor's client-side guard never runs here. Left in place, a
+ # transform on an unmirrored column is invisible and still stored, ready to
+ # go live the moment the mapped column resolves back to it.
+ DatasetDAO.clear_unmapped_partition_transforms(dataset)
+
+ # And repair a reference the import itself broke: a `sync` deletion can
+ # remove the column `partition_column` names, which otherwise leaves the
+ # dataset failing `UpdateDatasetCommand`'s validation on every later edit --
+ # including a description-only PUT, which carries no columns payload and so
+ # cannot reach the forgiveness branch that tolerates a stored-only dangle.
+ #
+ # Flushed and expired first: the `sync` deletion is still pending here, and
+ # reading the relationship without flushing loads the removed rows back and
+ # un-deletes them.
+ db.session.flush()
+ db.session.expire(dataset, ["columns"])
+ DatasetDAO.clear_dangling_partition_mapping(
Review Comment:
Fixed. An explicit self-mapping — `partition_mapped_column` equal to `partition_column` — is cleared on import, in line with the dangling-reference repair, so a bundle setting both to the same column no longer produces a dataset that fails its next description-only PUT.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "hughhhh (via GitHub)" <gi...@apache.org>.
hughhhh commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4319676081
##########
superset/models/helpers.py:
##########
@@ -5623,6 +6025,33 @@ def get_sqla_query( # pylint: disable=too-many-arguments,too-many-locals,too-ma
)
having_clause_and += [Grouping(self.text(having))]
+ # The mirrors go on last, so the snapshot taken here is everything the
+ # outer query and the series-limit ranking subquery agree about: row
+ # level security, the extras `where`, every filter. The two disagree
+ # about exactly the mirrors, and subtracting them again later is not an
+ # option -- `==` on a SQLAlchemy expression builds a new expression
+ # rather than answering a question, so the list cannot be filtered by
+ # identity.
+ where_clause_and_without_mirrors = list(where_clause_and)
+ inner_partition_mirror_predicates: list[Any] = []
+ if partition_mapping is not None:
+ partition_mirror_predicates = self._build_partition_mirror_predicates(
Review Comment:
Fixed. `get_sqla_query` takes `mirror_partition_filters`, which `get_extra_cache_keys` passes as `False` — it wants the SQL's shape, not the SQL a chart would run, and the mirrors contribute nothing to `extra_cache_keys`. It is not in `SQLA_QUERY_KEYS`, so no request payload can set it.
##########
superset/models/helpers.py:
##########
@@ -5689,7 +6106,20 @@ def get_sqla_query( # pylint: disable=too-many-arguments,too-many-locals,too-ma
)
if _inner_filter is not None:
inner_time_filter = [_inner_filter]
- subq = subq.where(and_(*(where_clause_and + inner_time_filter)))
+ # The mirrors swapped for the inner window's own, since the
+ # time filter just built describes that window: an outer-window
+ # mirror here would demand partition keys from a period this
+ # subquery excludes, and the empty ranking would drop the
+ # comparison series from the join below.
+ subq = subq.where(
+ and_(
+ *(
+ where_clause_and_without_mirrors
+ + inner_partition_mirror_predicates
Review Comment:
Fixed. The inner mirror is added only `if not db_engine_spec.time_groupby_inline`, so on ClickHouse (and Databend, Elasticsearch, Kusto) the ranking subquery is no longer narrowed by a window nothing else in that query mentions. Window-independent mirrors still go to both sinks, since those correspond to `where_clause_and`, which the subquery does receive.
##########
superset/views/datasource/views.py:
##########
@@ -87,6 +88,51 @@ def _load_dataset_for_samples(
return dataset, None
+def _partition_transform_error(
+ orm_datasource: Any,
+ datasource_dict: dict[str, Any],
+) -> str | None:
+ """
+ The first column whose incoming value transform may not be stored, if any.
+
+ Only datasets carry a partition mapping, and only a transform the request
+ actually changes is worth refusing over -- re-sending a value already in
+ storage is what a GET-then-PUT client does, and a transform stored before
+ this check existed is disarmed at probe time instead.
+ """
+ incoming = [
+ column
+ for column in datasource_dict.get("columns") or []
+ if column.get("partition_value_transform")
+ ]
+ database = getattr(orm_datasource, "database", None)
+ if not incoming or database is None:
+ return None
+
+ stored = {
+ column.column_name: column.partition_value_transform
+ for column in orm_datasource.columns
+ }
+ for column in incoming:
Review Comment:
Fixed. The legacy save calls `stored_expression_error`, which checks `len(transform) > MAX_TRANSFORM_LENGTH` ahead of the parse — both because it is the cheaper question and because the parse is the cost the bound exists to contain.
##########
superset/views/datasource/views.py:
##########
@@ -87,6 +95,109 @@ def _load_dataset_for_samples(
return dataset, None
+def _partition_transform_error(
+ orm_datasource: Any,
+ datasource_dict: dict[str, Any],
+) -> str | None:
+ """
+ The first column whose incoming value transform may not be stored, if any.
+
+ Only datasets carry a partition mapping, and only a transform the request
+ actually changes is worth refusing over -- re-sending a value already in
+ storage is what a GET-then-PUT client does, and a transform stored before
+ this check existed is disarmed at probe time instead.
+ """
+ incoming = [
+ column
+ for column in datasource_dict.get("columns") or []
+ if column.get("partition_value_transform")
+ ]
+ database = getattr(orm_datasource, "database", None)
+ if not incoming or database is None:
+ return None
+
+ stored = {
+ column.column_name: column.partition_value_transform
+ for column in orm_datasource.columns
+ }
+ for column in incoming:
+ transform = column["partition_value_transform"]
+ if transform == stored.get(column.get("column_name")):
+ continue
+ if reason := stored_expression_error(
Review Comment:
Fixed. The legacy save reaches `validate_transform`'s blocking tier as well as `stored_expression_error`, so `random() + :value` is refused here instead of saving with a 200 and then failing every later PUT.
##########
superset/views/datasource/views.py:
##########
@@ -157,6 +203,18 @@ def save(self) -> FlaskResponse:
),
status=409,
)
+ # `partition_value_transform` rides in on `update_from_object`, which
+ # writes every field in `update_from_object_fields` straight onto the
+ # column. That bypasses `UpdateDatasetCommand`, and with it the gate
+ # the REST PUT and the mapping preview both apply -- so without this
+ # the deprecated endpoint is a way to store arbitrary SQL that the
+ # partition probe later runs. Refused rather than dropped, unlike the
+ # importer: this is one interactive edit whose author is present to
+ # correct it, not a bundle where failing the whole dataset over one
+ # expression is the worse trade.
+ if error := _partition_transform_error(orm_datasource, datasource_dict):
Review Comment:
Fixed. `_partition_mapping_reference_error` runs the same `validate_partition_mapping` reference check as `UpdateDatasetCommand` before `update_from_object`, so the legacy endpoint can no longer store a `partition_column` naming a column that does not exist.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #43870:
URL: https://github.com/apache/superset/pull/43870#issuecomment-5953290957
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers an incremental AI Review.
- `/review full` - Manually triggers a full AI Review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4185252045
##########
superset/models/helpers.py:
##########
@@ -4290,36 +4297,283 @@ def dttm_sql_literal(self, dttm: datetime, col: "TableColumn") -> str:
return f"""'{dttm.strftime("%Y-%m-%d %H:%M:%S.%f")}'"""
- def get_time_filter( # pylint: disable=too-many-arguments # noqa: C901
+ def _mirror_probe_value(self, dttm: datetime, col: Optional["TableColumn"]) -> Any:
+ """
+ ``dttm`` in the mapped column's own stored representation.
+
+ The predicate this mirror stands in for compares the column against
+ `dttm_sql_literal(dttm, col)`, so the transform has to be probed with
+ the same value. On a column stored as an epoch integer, ``T`` is a
+ function of an integer: probing it with a `datetime` either returns
+ something unrelated to the partition keys or raises, and a raise costs
+ the dataset its pruning silently.
+
+ Only the ``python_date_format`` branches of `dttm_sql_literal` are
+ reproduced, because only those produce a *value*. `convert_dttm` yields
+ engine-specific SQL text, which cannot be bound as a parameter; its own
+ divergence from the probe is handled by widening the bounds instead.
+ """
+ if col is None:
+ return dttm
+
+ tf = col.python_date_format
+ if not tf and self.db_extra:
+ tf = self.db_extra.get("python_date_format_by_column_name", {}).get(
+ col.column_name
+ )
+ if not tf:
+ return dttm
+
+ if tf in EPOCH_FORMATS:
+ dttm_tz_aware = dttm
+ if dttm_tz_aware.tzinfo is None:
+ dttm_tz_aware = dttm_tz_aware.replace(tzinfo=timezone.utc)
+ return int(dttm_tz_aware.timestamp()) * EPOCH_FORMATS[tf]
+ return dttm.strftime(tf)
+
+ def _engine_drops_subseconds(
+ self, dttm: datetime, col: Optional["TableColumn"]
+ ) -> bool:
+ """
+ Whether this engine's literal for ``dttm`` loses the sub-second part.
+
+ SQLite renders a timestamp with ``timespec="seconds"``, so the real
+ predicate compares a floored bound while the probe is handed the full
+ precision -- which makes the mirror *narrower* than the predicate it
+ stands in for, and narrower means dropped rows.
+
+ Detected rather than enumerated per engine: two instants that differ
+ only below the second render as the same text exactly when the engine
+ has thrown the remainder away.
+
+ Both probes carry a non-zero sub-second part on purpose. Comparing
+ against ``dttm`` truncated to the second looks like the obvious test
+ and is wrong, because truncating can cross a formatting boundary as
+ well as a precision one -- SQLite renders a DATE column at exactly
+ midnight as a bare date, so the two texts differ for a reason that has
+ nothing to do with precision and the truncation goes unnoticed.
+
+ Note this only distinguishes second-level precision. An engine that
+ rendered no time part at all would need the bounds widened to the whole
+ day, which this does not do; no supported engine does that for a value
Review Comment:
Presto, Trino, BigQuery and ~20 other specs render a DATE bound with no time, so this happens: a 10:00 start gives `event_date >= DATE '2026-01-01'` but `dt_epoch >= 1767261600`, dropping Jan 1 rows the filter keeps. No suggestion: the fix spans this detector and the rounding.
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/DatasourceEditor.tsx:
##########
@@ -617,100 +674,160 @@ function ColumnCollectionTable({
/>
);
- return (
- <CollectionTable
- tableColumns={tableColumns}
- sortColumns={tableColumns}
- allowDeletes
- allowAddItem={allowAddItem}
- itemGenerator={itemGenerator}
- collection={columns}
- columnLabelTooltips={columnLabelTooltips}
- filterTerm={filterTerm}
- filterFields={filterFields}
- stickyHeader
- expandFieldset={
- <FormContainer>
- <Fieldset compact>
- {showExpression && (
- <Field
- fieldKey="expression"
- label={t('SQL expression')}
- control={
- <TextAreaControl
- language="sql"
- offerEditInModal={false}
- maxLines={25}
- debounceDelay={300}
- />
- }
- />
- )}
- <Field
- fieldKey="verbose_name"
- label={t('Label')}
- control={
- <TextControl
- controlId="verbose_name"
- placeholder={t('Label')}
- />
- }
+ const partitionMappingEnabled =
+ isFeatureEnabled(FeatureFlag.PartitionFilterMapping) && Boolean(datasource);
+ const partitionColumn = partitionMappingEnabled
+ ? datasource?.partition_column
+ : null;
+
+ // The two `itemRenderers` variants below differ only in which widget edits
+ // the name, so the certified badge and the PARTITION tag are shared here
+ // rather than written out four times.
+ const renderColumnName =
+ (EditControl: 'editableTitle' | 'textControl') =>
+ (
+ v: unknown,
+ onItemChange: (value: any) => void,
+ _: unknown,
+ record: Column,
+ ): ReactNode => (
+ <StyledLabelWrapper>
+ {record.is_certified && (
+ <CertifiedBadge
+ certifiedBy={record.certified_by}
+ details={record.certification_details}
+ />
+ )}
+ {editableColumnName ? (
+ EditControl === 'editableTitle' ? (
+ <EditableTitle
+ canEdit
+ title={v as string}
+ onSaveTitle={onItemChange}
/>
- <Field
- fieldKey="description"
- label={t('Description')}
- control={
- <TextControl
- controlId="description"
- placeholder={t('Description')}
+ ) : (
+ <TextControl value={v as string} onChange={onItemChange} />
+ )
+ ) : (
+ (v as ReactNode)
+ )}
+ {partitionColumn === record.column_name && (
+ <Tooltip
+ title={t(
+ 'Filters on the mapped column are mirrored onto this column so the engine can prune partitions.',
+ )}
+ >
+ <Label data-test="partition-tag">
+ <Icons.FilterOutlined iconSize="s" /> {t('PARTITION')}
+ </Label>
+ </Tooltip>
+ )}
+ </StyledLabelWrapper>
+ );
+
+ return (
+ <StyledColumnsTableWrapper>
+ <CollectionTable
+ tableColumns={tableColumns}
+ sortColumns={tableColumns}
+ allowDeletes
+ allowAddItem={allowAddItem}
+ itemGenerator={itemGenerator}
+ collection={columns}
+ columnLabelTooltips={columnLabelTooltips}
+ filterTerm={filterTerm}
+ filterFields={filterFields}
+ rowClassName={record =>
Review Comment:
This `rowClassName` is now ignored: the merge took master's CollectionTable whole, dropping its `rowClassName` prop and `<Table>` passthrough, so the partition row is never muted. No suggestion: the fix is in CollectionTable/index.tsx, outside the diff.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4254790118
##########
superset/mcp_service/common/schema_discovery.py:
##########
@@ -160,6 +160,11 @@ def _get_sqlalchemy_type_name(col_type: Any) -> str:
"filter_select_enabled": "Whether filter select is enabled",
"normalize_columns": "Whether to normalize column names",
"always_filter_main_dttm": "Whether to always filter on the main datetime column",
+ "partition_column": "Physical column the engine partitions on",
Review Comment:
Schema discovery now lists `partition_column` and `partition_mapped_column` as selectable dataset fields, but `DatasetInfo` and `serialize_dataset_object` do not carry them. A client that follows discovery and calls `get_dataset_info` with `select_columns: ["id", "partition_column", "partition_mapped_column"]` gets neither field back and no error. Should these be added to the dataset schema and serializer, or dropped from discovery?
##########
superset/commands/dataset/importers/v0.py:
##########
@@ -291,7 +302,43 @@ def run(self) -> None:
.one()
)
dataset["database_id"] = database.id
- SqlaTable.import_from_dict(dataset, sync=self.sync)
+ table = SqlaTable.import_from_dict(dataset, sync=self.sync)
+ if table is not None:
+ imported.append(table)
+
+ self._repair_partition_mappings(imported)
+
+ @staticmethod
+ def _repair_partition_mappings(datasets: list[SqlaTable]) -> None:
+ """
+ Keep the partition filter mapping honest across a v0 import.
+
+ The mapping's columns ride in `SqlaTable.export_fields`, so this path
+ carries them -- but it calls `SqlaTable.import_from_dict` directly and
+ goes through neither `DatasetDAO.update` nor the v1 importer, so
+ neither of the mapping's repairs ran. An older bundle imported with
+ ``--sync columns`` that omits the partition column deletes it and keeps
+ `partition_column` naming it: pruning silently stops, and every later
+ edit of that dataset fails the partition-column-not-found validation,
+ including a description-only PUT, which carries no columns payload and
+ so cannot reach the branch that forgives a stored-only dangle.
+
+ The same pair, in the same order, as `RefreshDatasetCommand` and the
+ v1 importer. Run after the import rather than around it because
+ ``import_from_dict`` is what discovers which datasets are involved.
+ """
+ if not datasets:
+ return
+ # Deferred import: `daos.dataset` pulls in `views.base`, which
+ # circularly imports back into the commands package at app init.
+ from superset.daos.dataset import DatasetDAO # noqa: PLC0415
+
+ db.session.flush()
+ for dataset in datasets:
+ DatasetDAO.clear_dangling_partition_mapping(
Review Comment:
The v0 repair only handles a dangling reference, while the v1 importer also clears an explicit self-mapping and defaults an omitted monotonicity flag. A legacy bundle that sets `partition_column` and `partition_mapped_column` to the same existing column (e.g. `event_time`) imports cleanly, and then every later save, even a description-only PUT, fails the blocking self-mapping validation. Likewise a legacy bundle that supplies a transform like `abs(:value)` without the monotonic key keeps a stored `True` on overwrite, so range filters can mirror and drop matching rows (e.g. `n >= -1` becomes `p >= 1` and misses `n=0, p=0`). Could v0 run the same self-mapping and omitted-monotonic normalization as v1?
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/utils.ts:
##########
@@ -0,0 +1,607 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { t } from '@apache-superset/core/translation';
+import type {
+ PartitionMappingColumn,
+ PartitionMappingDatasource,
+ PartitionMappingIssue,
+ PartitionRowState,
+} from './types';
+
+/**
+ * Jinja delimiters.
+ *
+ * A transform is evaluated in a different context and at a different time from
+ * the chart query, so a template would not render the same way -- the backend
+ * rejects one outright. Shared so the check that declines to preview a Jinja
+ * transform and the check that blocks saving it cannot drift apart.
+ */
+const JINJA_PATTERN = /\{\{|\{%|\{#/;
+
+/**
+ * The column whose filters are mirrored.
+ *
+ * `partition_mapped_column` is an explicit override; `null` means "follow the
+ * default datetime column", so re-pointing that column moves the mapping with
+ * it. Mirrors `SqlaTable.partition_filter_mapping_summary` on the backend.
+ */
+export function resolveMappedColumn(
+ datasource: PartitionMappingDatasource,
+): string | null {
+ if (!datasource.partition_column) {
+ return null;
+ }
+ return datasource.partition_mapped_column || datasource.main_dttm_col || null;
+}
+
+/** Whether the mapped column came from `main_dttm_col` rather than an override. */
+export function mappedColumnIsImplicit(
+ datasource: PartitionMappingDatasource,
+): boolean {
+ return Boolean(
+ datasource.partition_column &&
+ !datasource.partition_mapped_column &&
+ datasource.main_dttm_col,
+ );
+}
+
+/**
+ * Whether a transform is worth spending a preview request on.
+ *
+ * A necessary condition, never a sufficient one: the server stays the authority
+ * on whether a transform is usable, and anything this cannot see -- an
+ * unparseable expression, a non-deterministic function -- still comes back from
+ * it. What this catches is the cases that are knowably hopeless while the owner
+ * is still typing, which would otherwise spend the per-user preview budget and
+ * leave none for the transform they eventually finish writing.
+ */
+export function transformCanPreview(
+ transform: string | null | undefined,
+ mappedColumn?: string | null,
+ partitionColumn?: string | null,
+): boolean {
+ const trimmed = transform?.trim();
+ if (!trimmed) {
+ return false;
+ }
+ // Without the placeholder there is no value to substitute, so the transform
+ // is inert however well-formed it is.
+ if (!/:value\b/.test(trimmed)) {
+ return false;
+ }
+ // Jinja is rejected on save, so previewing it is pointless.
+ if (JINJA_PATTERN.test(trimmed)) {
+ return false;
+ }
+ // A column cannot stand in for itself; the backend rejects this outright.
+ if (mappedColumn && partitionColumn && mappedColumn === partitionColumn) {
+ return false;
+ }
+ return true;
+}
+
+/**
+ * Whether the mapping will actually mirror anything.
+ *
+ * Drives the choice between the green "filters will automatically apply"
+ * message and the warning that nothing is mirrored yet, so "non-blank text in
+ * the box" is not a good enough test: a transform with no `:value` to
+ * substitute, or one carrying Jinja, is as inert as an empty one and the
+ * backend's own summary reports it inactive. Claiming otherwise tells an owner
+ * their queries are pruning when they are not.
+ *
+ * Shares `transformCanPreview`'s conditions rather than restating them, and is
+ * necessary rather than sufficient for the same reason: an unparseable
+ * expression or a non-deterministic function needs a SQL parser to spot, so the
+ * server stays the authority -- `valueTransformIssues` surfaces what it says at
+ * the transform field itself.
+ */
+export function mappingIsActive(
+ datasource: PartitionMappingDatasource,
+ columns: PartitionMappingColumn[],
+): boolean {
+ const mappedColumnName = resolveMappedColumn(datasource);
+ if (!mappedColumnName || mappedColumnName === datasource.partition_column) {
+ return false;
+ }
+ const mappedColumn = columns.find(
+ column => column.column_name === mappedColumnName,
+ );
+ return transformCanPreview(
+ mappedColumn?.partition_value_transform,
+ mappedColumnName,
+ datasource.partition_column,
+ );
+}
+
+/**
+ * What is wrong with one column's value transform, if anything.
+ *
+ * Split out of `partitionMappingErrors` because the two callers disagree about
+ * which text to judge. The save gate reads the committed column record; the
+ * field's own message has to describe the text on screen, which lags the commit
+ * by a debounce. Passing the transform separately lets both ask the same
+ * question about different values instead of reimplementing the checks.
+ */
+export function valueTransformIssues(
+ column: PartitionMappingColumn | undefined,
+ transform: string | null | undefined,
+): PartitionMappingIssue[] {
+ if (!column) {
+ return [];
+ }
+
+ if (JINJA_PATTERN.test(transform ?? '')) {
+ return [
+ {
+ field: 'partition_value_transform',
+ message: t(
+ 'Jinja templating is not supported in a partition value transform. The transform is evaluated in a different context and at a different time from the chart query, so a template would not render the same way.',
+ ),
+ },
+ ];
+ }
+
+ // A temporal column falls back on the engine's own default, so leaving the box
+ // empty there only makes the mapping inactive -- which the dataset-level
+ // warning already says. A non-temporal column has nothing to fall back on.
+ if (!column.is_dttm && !transform?.trim()) {
+ return [
+ {
+ field: 'partition_value_transform',
+ message: t(
+ 'A value transform is required on %(name)s, which is not a temporal column. Use :value for each value.',
+ { name: column.column_name },
+ ),
+ },
+ ];
+ }
+
+ return [];
+}
+
+/**
+ * Everything wrong with the mapping that should stop the save.
+ *
+ * The client half of `validate_partition_mapping` in
+ * `superset/connectors/sqla/partition_mapping.py`, restricted to its blocking
+ * (Tier 1) issues. Those are the ones the PUT would reject anyway, so catching
+ * them here turns a 400 toast arriving after the modal closed into a disabled
+ * Save button that says why. Tier 2 is deliberately absent: an unparseable
+ * transform, or one missing `:value`, is "saved but stays inactive until it
+ * parses" per the PRD, and must not cost the owner the rest of their edits.
+ *
+ * One check is stricter than the backend's: an empty transform on a
+ * non-temporal mapped column blocks. The backend files that as Tier 2 for every
+ * column, but a non-temporal column has no default transform to fall back on --
+ * the field carries a required marker saying exactly this -- so the marker
+ * should mean something.
+ *
+ * Callers gate on the feature flag themselves, the way the two mount sites in
+ * `DatasourceEditor` already do; a dataset carrying a stale `partition_column`
+ * on an engine that cannot use one must not block a save the backend accepts.
+ */
+export function partitionMappingErrors(
+ datasource: PartitionMappingDatasource,
+ columns: PartitionMappingColumn[],
+): PartitionMappingIssue[] {
+ const partitionColumn = datasource.partition_column;
+ if (!partitionColumn) {
+ return [];
+ }
+
+ const issues: PartitionMappingIssue[] = [];
+ const columnNames = new Set(columns.map(column => column.column_name));
+
+ if (!columnNames.has(partitionColumn)) {
+ issues.push({
+ field: 'partition_column',
+ message: t('Partition column %(name)s is not a column on this dataset.', {
+ name: partitionColumn,
+ }),
+ });
+ }
+
+ const override = datasource.partition_mapped_column;
+ if (override && !columnNames.has(override)) {
+ issues.push({
+ field: 'partition_mapped_column',
+ message: t('Mapped column %(name)s is not a column on this dataset.', {
+ name: override,
+ }),
+ });
+ }
+
+ const mappedColumnName = resolveMappedColumn(datasource);
+ if (mappedColumnName === partitionColumn) {
+ // Only the *explicit* self-mapping blocks the save, matching
+ // `validate_partition_mapping`: an override naming the partition column is
+ // something the owner asked for and can take back, so it is Tier 1 there.
+ //
+ // The implicit one -- no override, and `main_dttm_col` happens to equal the
+ // partition column -- is Tier 2 on purpose. Blocking it here disabled Save
+ // on a dataset already in that state (metadata sync used to be able to
+ // produce one) even for a description-only edit, which is exactly the
+ // unsaveable dataset the backend comment says it avoids. The owner gets the
+ // same message, as a warning they can save through.
+ //
+ // No transform check can follow either way: the transform is a property of
+ // the mapped column, and there is no coherent mapped column to read it from.
+ issues.push({
+ field: 'partition_column',
+ blocking: Boolean(datasource.partition_mapped_column),
+ message: t(
+ 'The partition column cannot be mapped onto itself. %(name)s is both the partition column and the mapped column.',
+ { name: partitionColumn },
+ ),
+ });
+ return issues;
+ }
+
+ const mappedColumn = columns.find(
+ column => column.column_name === mappedColumnName,
+ );
+ issues.push(
+ ...valueTransformIssues(
+ mappedColumn,
+ mappedColumn?.partition_value_transform,
+ ),
+ );
+
+ return issues;
+}
+
+/** Which of the three row-expand treatments a column gets. */
+export function partitionRowState(
+ datasource: PartitionMappingDatasource,
+ columnName: string,
+): PartitionRowState {
+ if (!datasource.partition_column) {
+ return 'none';
+ }
+ if (columnName === datasource.partition_column) {
+ return 'partition';
+ }
+ return resolveMappedColumn(datasource) === columnName ? 'mapped' : 'unmapped';
+}
+
+/**
+ * The transform to pre-fill when a column becomes the mapped one.
+ *
+ * Only temporal columns get one, and only when the engine supplies it:
+ * `unix_timestamp(:value)` is Hive-family syntax and would not parse on
+ * Postgres or BigQuery, so a wrong default is worse than none.
+ */
+export function defaultTransformFor(
+ datasource: PartitionMappingDatasource,
+ column: PartitionMappingColumn | undefined,
+): string {
+ if (!column?.is_dttm) {
+ return '';
+ }
+ return datasource.partition_value_transform_default || '';
+}
+
+/** Declared types whose values are numbers rather than strings. */
+const NUMERIC_TYPE_RE =
+ /INT|NUMERIC|DECIMAL|DOUBLE|FLOAT|REAL|NUMBER|BIGNUMERIC/i;
+
+/** The sample instant, 2026-01-15 00:00:00 UTC, in each epoch representation. */
+const EPOCH_SAMPLES: Record<string, string> = {
+ epoch_s: '1768435200',
+ epoch_ms: '1768435200000',
+};
+
+/**
+ * Samples the preview evaluates the transform at.
+ *
+ * Temporal columns get one timestamp, because a time-range bound is what they
+ * are mapped for. Everything else gets two values, so the preview demonstrates
+ * the element-wise `IN` an ordinary categorical filter actually produces.
+ *
+ * The samples follow the column's declared type, not just whether it is
+ * temporal. A mapped integer column with `CAST(:value AS INTEGER)` is a real
+ * configuration, and evaluating it at `'US'` makes the engine reject a transform
+ * that an actual `IN (2025, 2026)` filter would mirror perfectly well -- the
+ * preview was reporting a fault in its own sample data.
+ *
+ * That includes a temporal column stored as a number. A `BIGINT` epoch column
+ * marked temporal compares epoch integers, and a chart's time range reaches it
+ * as one; a timestamp string coerces to nothing on that column, so the preview
+ * would report a broken mapping that the chart path mirrors correctly. Such a
+ * column gets the sample instant in its epoch representation, or the plain
+ * numeric samples when its format is not an epoch.
+ */
+export function sampleValuesFor(
+ column: PartitionMappingColumn | undefined,
+): string[] {
+ const isNumeric = Boolean(column?.type && NUMERIC_TYPE_RE.test(column.type));
+ if (column?.is_dttm) {
+ if (!isNumeric) {
+ return ['2026-01-15 00:00:00'];
Review Comment:
Every non-numeric temporal column gets `'2026-01-15 00:00:00'` regardless of `python_date_format`. For a `STRING` column stored as `%Y%m%d` mapped to a `DATE` partition key with `PARSE_DATE('%Y%m%d', :value)`, chart bounds arrive as `'20260115'`, so the preview parses a differently formatted sample and reports a working mapping as broken. Could the sample be rendered through the column's `python_date_format` when one is set?
##########
superset/daos/dataset.py:
##########
@@ -434,35 +452,147 @@ def update(
delete_metric_ids removes only explicitly selected metrics, without
replacing or replaying the remaining metrics.
"""
+ # Snapshot the keys: the column and metric branches below `pop` theirs
+ # out of `attributes`, so by the time the partition-mapping cleanup runs
+ # the dict no longer says what the request contained.
+ attribute_names = set(attributes or {})
+ touches_mapping = not PARTITION_MAPPING_ATTRIBUTES.isdisjoint(attribute_names)
+
+ # Once before the update and once after, because one pass can only ever
+ # see one of the two resolutions and the bug lives between them.
+ #
+ # The cleanup skips whichever column the mapping currently mirrors. Run
+ # only afterwards, it therefore skips the column this very request has
+ # just *made* the mapped one -- and a transform parked there, invisible
+ # because no row but the mapped one renders one, goes live. That turns
+ # removing a mapping into adding a different one, exactly what
+ # `clear_unmapped_partition_transforms` exists to prevent.
+ #
+ # This pass clears what is unmapped under the *old* resolution, which
+ # includes the column about to become mapped. The pass after clears
+ # what the *new* resolution strands. A transform the request itself
+ # supplies lands between the two, via `update_columns`, and survives --
+ # correctly, since the owner typed it.
+ if item is not None and touches_mapping:
+ cls.clear_unmapped_partition_transforms(item)
+ # The same invariant against what the request *carries*, which the
+ # pair of model-level passes cannot answer for: they are gated on
+ # the feature flag, correctly -- they discard stored configuration
+ # -- so with the flag off a payload could put a transform on a
+ # non-mapped column and have `update_columns` write it. Nothing
+ # reads it while the flag is off, and then the flag goes on and the
+ # mapping resolves onto it. See `drop_unmapped_value_transforms`.
+ #
+ # Harmless with the flag on, where the pass above has already
+ # cleared the same columns on the model and the pass below answers
+ # for the resolution this request leaves behind.
+ #
+ # Each name falls back to the model, because the mapping is
+ # `partition_mapped_column or main_dttm_col` and a request may
+ # change one of the three without mentioning the others.
+ requested = attributes or {}
+ if cleared := drop_unmapped_value_transforms(
Review Comment:
With the flag off, this runs against the incoming columns and nulls the transform on any column that is not the currently mapped one. If the editor changes the default datetime column from `event_time` to `event_time2` and saves, its columns payload still echoes `event_time`'s stored transform and monotonic flag, so they are written back as NULL/False. Switching the default column back and enabling the flag cannot recover the configuration, which is the same permanent loss the editor-side guard is meant to prevent. Should this skip clearing when the incoming value equals what is already stored, and only drop a transform the request is newly introducing?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4265949326
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,3128 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: The opening and closing delimiters of each kind of Jinja block. The probe
+#: would render these in a different context at a different time from the chart
+#: query, so a transform holding one is rejected at save time.
+JINJA_BLOCK_DELIMITERS = (("{{", "}}"), ("{%", "%}"), ("{#", "#}"))
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: A PostgreSQL Unicode-escaped identifier, ``U&"..."``.
+#:
+#: The second construct that breaks the premise above, and in the same way:
+#: ``U&"\\0071uery_to_xml"(...)`` parses as an anonymous function whose name is
+#: the *literal* ``\\0071uery_to_xml``, so the function denylist is matching a
+#: name the engine never sees -- PostgreSQL decodes the escape and runs
+#: ``query_to_xml``, handing a dataset owner rows from outside their RLS scope
+#: through the preview's ``emitted_predicate``.
+#:
+#: Normalizing the escapes and re-checking would be the other repair, and is
+#: worse: it means reimplementing one engine's identifier decoding well enough
+#: to be a security boundary. Refusing the construct is exact, and costs
+#: nothing real -- a transform is a scalar function of ``:value``, and there is
+#: no reason to name a function or column through an escape sequence.
+#:
+#: Refused on every engine, like the executable comment, so a transform stored
+#: on SQLite cannot detonate when the dataset is re-pointed at PostgreSQL. The
+#: ``&`` may be separated from the ``U`` by nothing at all, but whitespace or a
+#: comment between the prefix and the string is not accepted by PostgreSQL
+#: either, so the strict form is the whole surface.
+#:
+#: Matched in raw text, so the prefix is refused inside a string literal too.
+#: That is the same trade the executable comment makes and has the same
+#: justification: a gate whose contract is to fire *before* the parse cannot
+#: ask the parse whether the text was quoted. ``concat(:value, 'u&"x"')`` is
+#: refused, which costs an owner nothing anyone writes.
+UNICODE_ESCAPED_IDENTIFIER_RE = re.compile(r'\bU&"', re.IGNORECASE)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate: a transform such as
+#: ``datediff(day, :value, LOCALTIMESTAMP)`` for a relative partition key is
+#: evaluated once and then keeps emitting yesterday's answer, so the chart
+#: silently drops rows after midnight.
+#:
+#: Matched by SQL function name, so every engine's spelling of "now" has to be
+#: named -- the ANSI four were not enough. Listed rather than delegated to the
+#: engine specs because the risk is the same everywhere and a spec that had not
+#: got round to declaring its own would fail open; a name no engine has is
+#: inert, so over-listing costs nothing.
+NON_DETERMINISTIC_FUNCTIONS = {
+ # ANSI, and the engines that spell it this way.
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "LOCALTIME",
+ "LOCALTIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+ # PostgreSQL. `now()` is statement-stable; these two are not even that.
+ "CLOCK_TIMESTAMP",
+ "STATEMENT_TIMESTAMP",
+ "TIMEOFDAY",
+ # MySQL and MariaDB.
+ "CURDATE",
+ "CURTIME",
+ "SYSDATE",
+ "UTC_DATE",
+ "UTC_TIME",
+ "UTC_TIMESTAMP",
+ "UUID_SHORT",
+ # Oracle.
+ "SYSTIMESTAMP",
+ "SYS_GUID",
+ # SQL Server.
+ "GETDATE",
+ "GETUTCDATE",
+ "SYSDATETIME",
+ "SYSUTCDATETIME",
+ "SYSDATETIMEOFFSET",
+ "NEWID",
+ # BigQuery.
+ "CURRENT_DATETIME",
+ "GENERATE_UUID",
+ # Snowflake.
+ "RANDSTR",
+ "UUID_STRING",
+ # ClickHouse.
+ "NOW64",
+ "RANDCANONICAL",
+ "GENERATEUUIDV4",
+ # H2 and Derby, which the test fixtures use.
+ "RANDOM_UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+class Unmirrorable:
+ """
+ A filter no mirror can stand in for, and why.
+
+ Returned by `ExploreMixin.mirror_probe_request` for a value the engine
+ compares more coarsely than the filter carries, one it cannot render as a
+ literal, one in a time frame the transform would discard, or an ``IN`` list
+ with a member of any of those kinds. An object rather than `None`, because
+ `None` is a filter value in its own right.
+
+ The reason rides along because the preview has to explain the decline to
+ the owner, and the two declines want different advice: "the engine compares
+ less of this value than you typed, so map a column it compares in full" is
+ sound guidance for a `DATE` column and actively misleading for an
+ offset-bearing bound on a `TIMESTAMP` one, which already is such a column.
+ Carried rather than re-derived so the preview's explanation cannot come
+ apart from the chart path's decision.
+
+ Lives here rather than beside that method so the preview can read it too:
+ `superset.models.helpers` imports this module, so these can only cross the
+ boundary in this direction. Both callers recognise the same instances -- a
+ preview that answered "valid" for a request the chart path declines is the
+ drift this is here to prevent.
+ """
+
+ __slots__ = ("reason",)
+
+ def __init__(self, reason: str) -> None:
+ self.reason = reason
+
+ def __repr__(self) -> str:
+ return f"<Unmirrorable {self.reason}>"
+
+
+#: The ordinary decline: whatever the mirror cannot be built from, with the
+#: engine's own comparison resolution as the reason an owner can act on.
+UNMIRRORABLE = Unmirrorable("resolution")
+
+#: A value carrying a UTC offset, declined whatever the column's resolution.
+#: A transform such as ``CAST(:value AS TIMESTAMP)`` drops the offset, so even
+#: an engine that compares the whole instant would be probed in the wrong
+#: frame -- which is not something mapping a different column fixes.
+UNMIRRORABLE_OFFSET = Unmirrorable("offset")
+
+
+def is_unmirrorable(value: Any) -> bool:
+ """Whether `mirror_probe_request` declined this request."""
+ return isinstance(value, Unmirrorable)
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+#: Declared types whose comparison ignores trailing blanks.
+#:
+#: The fixed-width character types, which the SQL standard has compare as
+#: though both sides were padded to the same length -- so ``'US'`` and
+#: ``'US '`` are equal in a ``CHARACTER(3)``, while ``lower()`` of the two is
+#: not. Spelled out rather than matched by prefix because the variable-width
+#: names start with the same letters: ``VARCHAR`` and ``CHARACTER VARYING``
+#: compare the blanks and must not land here.
+PADDED_CHARACTER_TYPES = frozenset(
+ {
+ "CHAR",
+ "NCHAR",
+ # PostgreSQL's own name for ``CHARACTER``, which is what reflection
+ # reports for a ``CHAR(n)`` column there.
+ "BPCHAR",
+ "CHARACTER",
+ "NATIONAL CHAR",
+ "NATIONAL CHARACTER",
+ }
+)
+
+
+def _is_padded_character_type(column: TableColumn) -> bool:
+ """
+ Whether ``column``'s declared type compares without its trailing blanks.
+
+ Read off the declared type rather than the engine spec's resolved one: the
+ specs map ``CHAR`` and ``VARCHAR`` onto the same `sqlalchemy.String`, so
+ the distinction this needs is gone by then. The length suffix is dropped
+ and the name matched against `PADDED_CHARACTER_TYPES`, so an unfamiliar
+ spelling answers ``False`` and the engine-level flag decides as before --
+ this gate adds a decline rather than lifting one. A column with no
+ declared type has nothing to read, and answers the same way.
+ """
+ if not isinstance(column.type, str):
+ return False
+ native = re.sub(r"\s+", " ", column.type.strip().upper())
+ return native.split("(")[0].strip() in PADDED_CHARACTER_TYPES
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ Padding is asked about per column, because it is a property of the *type*
+ rather than of the engine. ``binary_string_comparison`` speaks for an
+ engine's default text comparison, and on PostgreSQL -- which declares it
+ -- a ``CHAR(2)`` still matches a filter for ``'US '`` against a stored
+ ``'US'``, because the standard says a padded character type compares
+ without its trailing blanks. The mirror ``region_key = lower('US ')`` then
+ excludes the row. So a fixed-width character type declines whatever the
+ engine says, and an engine that ignores trailing blanks on its *variable*
+ types says so by not declaring the flag at all (see `RedshiftEngineSpec`).
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ # Ahead of the generic-type question, which a padded type can lose: the
+ # specs map ``CHARACTER`` onto no generic type at all on some engines, and
+ # a fixed-width character type is a string whether or not Superset can say
+ # so from the name.
+ if _is_padded_character_type(column):
+ return False
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
Review Comment:
The string-comparison gate can be bypassed without any custom collation, in two ways. `type_generic` answers `TEMPORAL` for every `is_dttm` column, so a VARCHAR `event_time` flagged temporal skips the string check: on MySQL with `HEX(:value)` as the transform, a filter for `'2026-01-01T00:00:00'` matches a stored `'2026-01-01t00:00:00'`, but the mirror `p = hex('2026-01-01T00:00:00')` excludes the row. And a column whose type the engine spec cannot classify (PostgreSQL `citext` matches none of the type patterns) gets `type_generic is None`, which is not `STRING` either, so this returns `True` before it reads `binary_string_comparison` -- the comment above says an unresolvable type fails closed, but only the exception branch does. Could this use `_native_generic_type(column)` and treat a `None` result as a string?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,3128 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: The opening and closing delimiters of each kind of Jinja block. The probe
+#: would render these in a different context at a different time from the chart
+#: query, so a transform holding one is rejected at save time.
+JINJA_BLOCK_DELIMITERS = (("{{", "}}"), ("{%", "%}"), ("{#", "#}"))
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: A PostgreSQL Unicode-escaped identifier, ``U&"..."``.
+#:
+#: The second construct that breaks the premise above, and in the same way:
+#: ``U&"\\0071uery_to_xml"(...)`` parses as an anonymous function whose name is
+#: the *literal* ``\\0071uery_to_xml``, so the function denylist is matching a
+#: name the engine never sees -- PostgreSQL decodes the escape and runs
+#: ``query_to_xml``, handing a dataset owner rows from outside their RLS scope
+#: through the preview's ``emitted_predicate``.
+#:
+#: Normalizing the escapes and re-checking would be the other repair, and is
+#: worse: it means reimplementing one engine's identifier decoding well enough
+#: to be a security boundary. Refusing the construct is exact, and costs
+#: nothing real -- a transform is a scalar function of ``:value``, and there is
+#: no reason to name a function or column through an escape sequence.
+#:
+#: Refused on every engine, like the executable comment, so a transform stored
+#: on SQLite cannot detonate when the dataset is re-pointed at PostgreSQL. The
+#: ``&`` may be separated from the ``U`` by nothing at all, but whitespace or a
+#: comment between the prefix and the string is not accepted by PostgreSQL
+#: either, so the strict form is the whole surface.
+#:
+#: Matched in raw text, so the prefix is refused inside a string literal too.
+#: That is the same trade the executable comment makes and has the same
+#: justification: a gate whose contract is to fire *before* the parse cannot
+#: ask the parse whether the text was quoted. ``concat(:value, 'u&"x"')`` is
+#: refused, which costs an owner nothing anyone writes.
+UNICODE_ESCAPED_IDENTIFIER_RE = re.compile(r'\bU&"', re.IGNORECASE)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate: a transform such as
+#: ``datediff(day, :value, LOCALTIMESTAMP)`` for a relative partition key is
+#: evaluated once and then keeps emitting yesterday's answer, so the chart
+#: silently drops rows after midnight.
+#:
+#: Matched by SQL function name, so every engine's spelling of "now" has to be
+#: named -- the ANSI four were not enough. Listed rather than delegated to the
+#: engine specs because the risk is the same everywhere and a spec that had not
+#: got round to declaring its own would fail open; a name no engine has is
+#: inert, so over-listing costs nothing.
+NON_DETERMINISTIC_FUNCTIONS = {
+ # ANSI, and the engines that spell it this way.
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "LOCALTIME",
+ "LOCALTIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+ # PostgreSQL. `now()` is statement-stable; these two are not even that.
+ "CLOCK_TIMESTAMP",
+ "STATEMENT_TIMESTAMP",
+ "TIMEOFDAY",
+ # MySQL and MariaDB.
+ "CURDATE",
+ "CURTIME",
+ "SYSDATE",
+ "UTC_DATE",
+ "UTC_TIME",
+ "UTC_TIMESTAMP",
+ "UUID_SHORT",
+ # Oracle.
+ "SYSTIMESTAMP",
+ "SYS_GUID",
+ # SQL Server.
+ "GETDATE",
+ "GETUTCDATE",
+ "SYSDATETIME",
+ "SYSUTCDATETIME",
+ "SYSDATETIMEOFFSET",
+ "NEWID",
+ # BigQuery.
+ "CURRENT_DATETIME",
+ "GENERATE_UUID",
+ # Snowflake.
+ "RANDSTR",
+ "UUID_STRING",
+ # ClickHouse.
+ "NOW64",
+ "RANDCANONICAL",
+ "GENERATEUUIDV4",
+ # H2 and Derby, which the test fixtures use.
+ "RANDOM_UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+class Unmirrorable:
+ """
+ A filter no mirror can stand in for, and why.
+
+ Returned by `ExploreMixin.mirror_probe_request` for a value the engine
+ compares more coarsely than the filter carries, one it cannot render as a
+ literal, one in a time frame the transform would discard, or an ``IN`` list
+ with a member of any of those kinds. An object rather than `None`, because
+ `None` is a filter value in its own right.
+
+ The reason rides along because the preview has to explain the decline to
+ the owner, and the two declines want different advice: "the engine compares
+ less of this value than you typed, so map a column it compares in full" is
+ sound guidance for a `DATE` column and actively misleading for an
+ offset-bearing bound on a `TIMESTAMP` one, which already is such a column.
+ Carried rather than re-derived so the preview's explanation cannot come
+ apart from the chart path's decision.
+
+ Lives here rather than beside that method so the preview can read it too:
+ `superset.models.helpers` imports this module, so these can only cross the
+ boundary in this direction. Both callers recognise the same instances -- a
+ preview that answered "valid" for a request the chart path declines is the
+ drift this is here to prevent.
+ """
+
+ __slots__ = ("reason",)
+
+ def __init__(self, reason: str) -> None:
+ self.reason = reason
+
+ def __repr__(self) -> str:
+ return f"<Unmirrorable {self.reason}>"
+
+
+#: The ordinary decline: whatever the mirror cannot be built from, with the
+#: engine's own comparison resolution as the reason an owner can act on.
+UNMIRRORABLE = Unmirrorable("resolution")
+
+#: A value carrying a UTC offset, declined whatever the column's resolution.
+#: A transform such as ``CAST(:value AS TIMESTAMP)`` drops the offset, so even
+#: an engine that compares the whole instant would be probed in the wrong
+#: frame -- which is not something mapping a different column fixes.
+UNMIRRORABLE_OFFSET = Unmirrorable("offset")
+
+
+def is_unmirrorable(value: Any) -> bool:
+ """Whether `mirror_probe_request` declined this request."""
+ return isinstance(value, Unmirrorable)
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+#: Declared types whose comparison ignores trailing blanks.
+#:
+#: The fixed-width character types, which the SQL standard has compare as
+#: though both sides were padded to the same length -- so ``'US'`` and
+#: ``'US '`` are equal in a ``CHARACTER(3)``, while ``lower()`` of the two is
+#: not. Spelled out rather than matched by prefix because the variable-width
+#: names start with the same letters: ``VARCHAR`` and ``CHARACTER VARYING``
+#: compare the blanks and must not land here.
+PADDED_CHARACTER_TYPES = frozenset(
+ {
+ "CHAR",
+ "NCHAR",
+ # PostgreSQL's own name for ``CHARACTER``, which is what reflection
+ # reports for a ``CHAR(n)`` column there.
+ "BPCHAR",
+ "CHARACTER",
+ "NATIONAL CHAR",
+ "NATIONAL CHARACTER",
+ }
+)
+
+
+def _is_padded_character_type(column: TableColumn) -> bool:
+ """
+ Whether ``column``'s declared type compares without its trailing blanks.
+
+ Read off the declared type rather than the engine spec's resolved one: the
+ specs map ``CHAR`` and ``VARCHAR`` onto the same `sqlalchemy.String`, so
+ the distinction this needs is gone by then. The length suffix is dropped
+ and the name matched against `PADDED_CHARACTER_TYPES`, so an unfamiliar
+ spelling answers ``False`` and the engine-level flag decides as before --
+ this gate adds a decline rather than lifting one. A column with no
+ declared type has nothing to read, and answers the same way.
+ """
+ if not isinstance(column.type, str):
+ return False
+ native = re.sub(r"\s+", " ", column.type.strip().upper())
+ return native.split("(")[0].strip() in PADDED_CHARACTER_TYPES
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ Padding is asked about per column, because it is a property of the *type*
+ rather than of the engine. ``binary_string_comparison`` speaks for an
+ engine's default text comparison, and on PostgreSQL -- which declares it
+ -- a ``CHAR(2)`` still matches a filter for ``'US '`` against a stored
+ ``'US'``, because the standard says a padded character type compares
+ without its trailing blanks. The mirror ``region_key = lower('US ')`` then
+ excludes the row. So a fixed-width character type declines whatever the
+ engine says, and an engine that ignores trailing blanks on its *variable*
+ types says so by not declaring the flag at all (see `RedshiftEngineSpec`).
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ # Ahead of the generic-type question, which a padded type can lose: the
+ # specs map ``CHARACTER`` onto no generic type at all on some engines, and
+ # a fixed-width character type is a string whether or not Superset can say
+ # so from the name.
+ if _is_padded_character_type(column):
+ return False
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_unicode_escaped_identifier(transform: str | None) -> bool:
+ """Whether the transform names something through a ``U&"..."`` escape.
+
+ See `UNICODE_ESCAPED_IDENTIFIER_RE`. Answered on raw text for the same
+ reason as the comment above: the parse reports a name the engine does not
+ use, which is exactly what makes the denylist blind to it.
+ """
+ return (
+ bool(transform)
+ and UNICODE_ESCAPED_IDENTIFIER_RE.search(transform or "") is not None
+ )
+
+
+#: Sequence pseudo-columns, which advance a sequence when they are *read*.
+#:
+#: ``orders_seq.NEXTVAL`` parses as a qualified column reference, not a
+#: function call, so neither `SQLStatement.is_mutating` -- which walks function
+#: names -- nor the function denylist can see it. The probe would then run
+#: ``SELECT orders_seq.NEXTVAL + 1 FROM DUAL`` and advance the sequence, again
+#: on every cache expiry, for a dataset editor holding neither SQL Lab nor a
+#: DML grant. Reading one is a write however the parser classifies it.
+#:
+#: The function spelling (``nextval('s')`` on PostgreSQL) is a different shape
+#: and is caught as a function; this is only about the suffix form.
+SEQUENCE_PSEUDO_COLUMNS = frozenset({"nextval", "currval"})
+
+#: The same thing written as a call.
+#:
+#: Only the suffix form parses as a column; `nextval('s')` on PostgreSQL and
+#: DuckDB, `NEXTVAL(s)`/`SETVAL(s, 1)` on MySQL and MariaDB, and SQL Server's
+#: `NEXT VALUE FOR s` all parse as functions. `SQLStatement.is_mutating` walks
+#: function names on PostgreSQL alone -- deliberately, since the same names are
+#: read-only elsewhere -- so every other engine let these through.
+#:
+#: Matched on the name whatever the engine, because advancing a sequence is a
+#: write wherever it happens and a transform has no reason to call one.
+SEQUENCE_FUNCTIONS = frozenset(
+ {"nextval", "setval", "next_value_for", "nextvalfor", "prevval", "lastval"}
+)
+
+
+def references_sequence(statement: SQLStatement) -> bool:
+ """Whether the statement reads or advances a sequence.
+
+ Both spellings: the pseudo-column suffix, which parses as a column (see
+ `SEQUENCE_PSEUDO_COLUMNS`), and the call, which parses as a function (see
+ `SEQUENCE_FUNCTIONS`).
+
+ Answered on the parse rather than on raw text, because position is what
+ makes it the construct: a column or alias merely *called* ``nextval`` is
+ an ordinary column, and a string literal holding the word is text.
+ """
+ return bool(
+ statement.get_column_names() & SEQUENCE_PSEUDO_COLUMNS
+ or statement.get_disallowed_functions(set(SEQUENCE_FUNCTIONS))
+ )
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """
+ Whether the transform contains a balanced Jinja block.
+
+ A block is an opening delimiter followed, anywhere later, by its closing
+ one -- the same thing ``{{.*?}}`` and its two siblings match under
+ ``re.DOTALL``. Scanned with `str.find` rather than that pattern, because a
+ lazy match retried from every opening delimiter is quadratic in a run of
+ them, and this runs on stored transforms with no length bound of its own:
+ `is_transform_active` reads whatever the column holds. The earliest opening
+ delimiter is the only one worth trying, since any closing delimiter after a
+ later one is also after it.
+ """
+ if not transform:
+ return False
+ for opening, closing in JINJA_BLOCK_DELIMITERS:
+ start = transform.find(opening)
+ if start != -1 and transform.find(closing, start + len(opening)) != -1:
+ return True
+ return False
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error( # noqa: C901
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ And it must be a *read*. Shape is a separate question from effect: a bare
+ scalar expression can still write, so `SQLStatement.is_mutating` is asked
+ too -- the same question SQL Lab and the chart executor ask before letting
+ SQL run. See the gate itself for what that reaches and what it does not.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ # Also ahead of the parse, and for a stronger reason than cost: every gate
+ # below reasons about the parse tree, and this is the one construct that
+ # makes the parse tree describe a different statement from the one the
+ # engine runs. Checked here as well as in `validate_transform` because this
+ # is the door a row written by an earlier release still comes through.
+ if contains_executable_comment(transform):
+ return str(
+ _(
+ "A partition value transform cannot contain a MySQL "
+ "executable comment, which the database executes and every "
+ "validator reads as a comment."
+ )
+ )
+
+ if contains_unicode_escaped_identifier(transform):
+ return str(
+ _(
+ "A partition value transform cannot name anything through a "
+ 'U&"..." escape sequence, which the database decodes and '
+ "every validator reads literally."
+ )
+ )
+
+ # Same door, same reason: the name the denylist below would match is not
+ # the name the engine resolves. See `UNICODE_ESCAPED_IDENTIFIER_RE`.
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The read-only gate, which nothing above implies. The shape gates ask what
+ # the transform *selects*; this asks what evaluating it *does*, and a bare
+ # scalar expression can still write. `nextval(:value)` on PostgreSQL
+ # advances a sequence: one function call, no clause, no sub-query, and not
+ # in the default `DISALLOWED_SQL_FUNCTIONS` either -- so every gate above
+ # passes it and the probe then runs it. `setval` is the same shape, and
+ # `exp.Execute` and the opaque-`exp.Command` forms arrive the same way.
+ #
+ # The large-object writers (`lo_export`, `lowrite`, `lo_from_bytea`, ...)
+ # are caught here too, and the shipped denylist happens to name them as
+ # well -- but that is config an operator can replace, while this is not.
+ #
+ # `is_mutating` is the same question SQL Lab, `get_virtual_table_metadata`
+ # and the chart executor ask before letting SQL run, so a transform is held
+ # to the bar the rest of Superset already sets rather than to one invented
+ # here. Unconditional rather than gated on `Database.allow_dml`: a transform
+ # is a scalar function of `:value` by definition, so there is no legitimate
+ # mutating one, and the probe runs on a cache schedule nobody chose -- a
+ # write would repeat every time the entry expired.
+ #
+ # It bears saying what this does not reach. A user-defined function whose
+ # body writes is a plain call no parser can tell from `lower(:value)`, and
+ # `is_mutating`'s function-name walk is PostgreSQL-only by design, since the
+ # same names are read-only elsewhere. Neither residual is specific to this
+ # feature -- a dataset editor can already have the engine evaluate an
+ # arbitrary expression through a calculated column or a virtual dataset's
+ # SQL -- and closing them means authorizing the preview against the
+ # database, not parsing harder.
+ if statement.is_mutating():
+ return str(
+ _(
+ "A partition value transform cannot change data. It is "
+ "evaluated against the database to check that it mirrors, so "
+ "it has to be a read."
+ )
+ )
+
+ # Not reached by the walk above, which is why it is its own gate: a
+ # sequence pseudo-column is a *column* to the parser and a write to the
+ # engine. See `SEQUENCE_PSEUDO_COLUMNS`.
+ if references_sequence(statement):
+ return str(
+ _(
+ "A partition value transform cannot read a sequence. "
+ "NEXTVAL advances the sequence every time it is evaluated, "
+ "and the transform is evaluated on a cache schedule."
+ )
+ )
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the probe
+ uninspected -- string elements are escaped by the dialect's own literal
+ processor. `probe_sql_is_evaluable` then re-reads the finished query, which
+ is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def _placeholder_is_bindable(transform: str) -> bool:
+ """
+ Whether SQLAlchemy's ``text()`` can see ``:value`` as a bound parameter.
+
+ `VALUE_PLACEHOLDER_RE` is ``:value\b``, which matches the placeholder in a
+ Postgres cast such as ``:value::bigint``. SQLAlchemy's own bind scan is
+ ``(?<![:\\w$]):([\\w$]+)(?![:\\w$])`` -- note the trailing exclusion -- so a
+ following colon stops it: ``text(":value::bigint")`` reports a parameter
+ named ``valu``, and ``.bindparams(bindparam("value"))`` then raises
+ ``ArgumentError``.
+
+ `_probe` swallows that, so the only symptom was a perfectly valid transform
+ whose mapping silently never pruned, and a preview reporting an engine
+ failure for SQL that was never sent. Every write-side gate passes the
+ transform: it parses, it is a bare expression, and the placeholder *is* in
+ an executable position.
+
+ Answered by attempting the bind itself rather than by pattern-matching
+ ``::`` or reading ``text()``'s private parameter map, so this cannot
+ disagree with what `build_probe_sql` is about to do -- on any dialect, or on
+ a SQLAlchemy whose scan changes.
+ """
+ try:
+ sa.text(transform).bindparams(sa.bindparam("value", value=None))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return False
+ return True
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ bindable = _placeholder_is_bindable(transform)
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ elif bindable:
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
+ rendered = _compile_literal(clause, dialect)
+ else:
+ # `text()` cannot see the placeholder (see
+ # `_placeholder_is_bindable`), so the value is rendered by the
+ # dialect's own literal processor first and substituted as SQL
+ # text. The same two steps in the other order: binding exists to
+ # get the value through that processor, and `_compile_literal`
+ # inlines the result either way, so this is the same string by a
+ # different route -- not a loosening of the "never interpolate a
+ # raw value" rule. `parse_skeleton` substitutes literally, so a
+ # rendered literal containing a backslash is safe here.
+ rendered = parse_skeleton(
+ transform, _compile_literal(sa.literal(value), dialect)
+ )
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Four things have to hold, and all four are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ # Before the parse, because this gate's whole contract is that what the
+ # parse describes is what the engine will run, and an executable comment is
+ # precisely the text where that stops being true. The transform is already
+ # refused for carrying one; this covers the compiled statement, so no later
+ # change to how values are rendered can reintroduce it behind the gates
+ # below.
+ if contains_executable_comment(sql) or contains_unicode_escaped_identifier(sql):
+ return False
+
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if not isinstance(statement, SQLStatement):
+ # A dialect whose statements this gate cannot take apart -- KQL -- gets
+ # no probe rather than an unchecked one. It never had one: the clause
+ # inspection below is implemented for SQL statements only, and the
+ # alternative to declining here is an `AttributeError` that `_probe`
+ # swallows into the same outcome, less legibly.
+ return False
+ if statement.has_subquery():
+ return False
+ if statement.get_clause_names() - {"from"}:
+ return False
+ if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+ """
+ The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+ Parsed rather than string-compared so that the comparison in
+ `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+ not parse answers ``None``, which no statement carrying a FROM can match --
+ the probe then declines, which is the right way for an unreadable engine
+ constant to fail.
+ """
+ if not from_suffix.strip():
+ return None
+ try:
+ return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+ except SupersetParseError:
+ return None
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ """
+ if not values:
+ return None
+
+ # Dedupe so a 200-value `IN` list costs one column, not 200.
+ distinct: list[Any] = []
+ seen: set[Any] = set()
+ for value in values:
+ key = _hashable(value)
+ if key not in seen:
+ seen.add(key)
+ distinct.append(value)
+
+ cache_key = _probe_cache_key(database, catalog, schema, transform, distinct)
+ cached = _cache_get(cache_key)
+ if cached is None:
+ cached = _run_probe(
+ database, catalog, schema, transform, distinct, errors=errors
+ )
+ if cached is None:
+ # Deliberately not cached: a transient engine blip would otherwise
+ # keep the dataset pruning-free for the whole cache timeout.
+ return None
+ _cache_set(cache_key, cached)
+
+ evaluated = dict(
+ zip((_hashable(value) for value in distinct), cached, strict=False)
+ )
+ return [evaluated[_hashable(value)] for value in values]
+
+
+def _run_probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ """
+ `_probe` plus the advisory record of how it went.
+
+ One place rather than one per `return`, because every way out of `_probe`
+ is a verdict and the next reader of `known_mirror_verdict` cannot tell the
+ difference between "declined" and "never asked".
+ """
+ values = _probe(database, catalog, schema, transform, distinct, errors=errors)
+ record_mirror_verdict(
+ database,
+ catalog,
+ schema,
+ transform,
+ mirrors=values is not None and not any(value is None for value in values),
+ )
+ return values
+
+
+def _probe(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ distinct: list[Any],
+ *,
+ errors: list[str] | None = None,
+) -> list[Any] | None:
+ # The last gate before the transform becomes SQL the engine runs, and the
+ # only one that covers a transform already in storage. The write-side
+ # checks can only speak for rows written after they existed; this speaks
+ # for every row, including ones a pre-fix release stored and ones a door
+ # that forgets to ask still lets in.
+ #
+ # Declining costs pruning, never correctness -- see `evaluate_transform`.
+ if reason := stored_expression_error(database, catalog, schema, transform):
+ logger.warning(
+ "Refusing to probe a partition transform that is not a storable "
+ "expression; queries will not prune: %s",
+ reason,
+ )
+ return None
+
+ try:
+ from_suffix = database.db_engine_spec.select_without_from_suffix
+ sql = build_probe_sql(
+ transform,
+ distinct,
+ _dialect_for(database),
+ from_suffix,
+ )
+ if not probe_sql_is_evaluable(
+ sql, database.backend, len(distinct), from_suffix
+ ):
+ # Declining rather than raising, for the same reason every other
+ # failure here declines: the chart query is already correct without
+ # the mirror, and it is the only thing the caller is waiting on.
+ logger.warning(
+ "Refusing to run a partition transform probe whose compiled SQL "
+ "is not a plain projection per input value; queries will not "
+ "prune"
+ )
+ return None
+ frame = database.get_df(sql=sql, catalog=catalog, schema=schema)
+ if frame is None or frame.empty:
+ logger.warning(
+ "Partition transform probe returned no rows; skipping mirroring"
+ )
+ return None
+ column_count = frame.shape[1]
+ if column_count != len(distinct):
+ # The results cannot be aligned back to their inputs; skipping
+ # beats guessing which value produced which column. Too *many*
+ # columns is the dangerous direction and the reason this is `!=`
+ # rather than `<`: a transform whose select list holds two
+ # expressions returns 2N columns for N inputs, and reading the
+ # first N of them interleaves the expressions instead of selecting
+ # one per value -- a predicate built from the wrong values rather
+ # than one that is merely short. `is_parseable` rejects that
+ # transform before it is ever stored; this is the backstop for one
+ # that predates the check.
+ logger.warning(
+ "Partition transform probe returned %d values for %d inputs",
+ column_count,
+ len(distinct),
+ )
+ return None
+ # Cell-wise rather than through `frame.iloc[0]`. A row is a Series, so
+ # it carries one dtype for every probe column: a row mixing an exact
+ # int64 with a float unifies to float64, and an integer partition key
+ # above 2^53 comes back rounded. `_to_python_scalar` converts
+ # faithfully but runs after the loss, so the mirror asks for a key the
+ # warehouse does not hold and drops the row the filter matched.
+ return [
+ _to_python_scalar(frame.iat[0, index]) for index in range(len(distinct))
+ ]
+ except Exception as ex: # pylint: disable=broad-except
+ logger.warning(
+ "Partition transform probe failed; queries will not prune",
+ exc_info=True,
+ )
+ if errors is not None:
+ errors.append(str(ex))
+ return None
+
+
+def _to_python_scalar(value: Any) -> Any:
+ """
+ A probed value as a type SQLAlchemy can render and bind.
+
+ The probe reads its results out of a pandas frame, so a numeric column
+ arrives as a `numpy.int64` and a temporal one as a `pandas.Timestamp`.
+ SQLAlchemy has no literal renderer for either: `sa.literal(np.int64(...))`
+ infers `NullType` and raises `CompileError`, which is a 500 from the preview
+ endpoint for the canonical epoch transform -- the most ordinary mapping
+ there is.
+
+ Pandas' missing-value sentinels are folded into `None` on the way through.
+ `NaT` is not a `Timestamp` and has no renderer either, and a transform that
+ returns nothing for an input it cannot convert is exactly the NULL case the
+ mirror already admits.
+ """
+ if value is None:
+ return None
+ try:
+ if pd.isna(value):
+ return None
+ except (TypeError, ValueError):
+ # Not something `isna` can judge (a list, a dict); pass it through and
+ # let the dialect decide.
+ pass
+ if isinstance(value, pd.Timestamp):
+ return value.to_pydatetime()
+ if isinstance(value, np.generic):
+ return value.item()
+ return value
+
+
+def _execution_identity(database: Database) -> str | None:
+ """
+ Who the warehouse will run the probe as, when that can vary by caller.
+
+ `_probe_cache_key` keys on the `Database` record, which is the *connection*
+ -- not the identity it is opened under. Two hooks make that identity a
+ function of the Superset user instead:
+
+ * ``impersonate_user`` on the database, which hands the effective username
+ to `db_engine_spec.impersonate_user`;
+ * ``DB_CONNECTION_MUTATOR``, which receives the effective username and may
+ return an entirely different account's URL.
+
+ Under either one, a cached probe result computed under user A's grants was
+ served to user B, and the preview echoed it back in ``emitted_predicate``.
+ A transform wrapping a read-capable function the denylist does not name --
+ Oracle's ``DBMS_XMLGEN.GETXML`` is the worked example -- then leaks across
+ users who were never allowed the same rows.
+
+ Returns ``None`` when neither hook is configured, which is the common case
+ and deliberately leaves the key as it was: the cache exists to keep a
+ synchronous warehouse round trip off the chart-query path, and keying every
+ deployment on the username would cost every deployment the hit rate to fix
+ the two that need it.
+
+ The *Superset* username rather than the resolved warehouse account, because
+ it is the input both hooks branch on, and reading it needs no URL parse and
+ puts no credential in the key.
+ """
+ if not (database.impersonate_user or app.config["DB_CONNECTION_MUTATOR"]):
+ return None
+ return get_username()
+
+
+def _probe_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+) -> str:
+ """
+ Key on everything that can change the answer.
+
+ Note this cache is independent of the chart-data cache: it is keyed on the
+ transform and its inputs, so it is correct to share across every chart on
+ every dataset that happens to use the same transform.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ # The probe asks this connection to evaluate the transform, so the
+ # answer belongs to it. `id` outlives an edit to the URI or to
+ # `extra` (a session timezone, say), which would otherwise serve
+ # values computed against the old environment until the entry
+ # expires. `changed_on` covers the edits that do not show up here,
+ # such as a rotated password, without putting a secret in the key.
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ [repr(value) for value in values],
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_probe:{digest}"
+
+
+def _cache_get(key: str) -> list[Any] | None:
+ try:
+ return cache_manager.cache.get(key)
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+def _cache_set(key: str, value: list[Any]) -> None:
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(key, value, timeout=timeout)
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform probe", exc_info=True)
+
+
+def _mirror_verdict_cache_key(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str:
+ """
+ `_probe_cache_key` without the values.
+
+ Whether a transform can be evaluated at all is a property of the transform
+ and the connection, not of the filter that happened to be probing it, so
+ one chart's answer settles the question for the next one.
+ """
+ payload = json.dumps(
+ [
+ database.id,
+ database.backend,
+ database.sqlalchemy_uri,
+ database.extra,
+ str(database.changed_on),
+ catalog,
+ schema,
+ transform,
+ # Whether a transform *can* be evaluated is a property of the
+ # transform and the connection -- but under impersonation the
+ # connection is per-user, and a function one account may call can
+ # be refused to another. See `_execution_identity`.
+ _execution_identity(database),
+ ],
+ default=repr,
+ )
+ digest = hashlib.md5(payload.encode("utf-8")).hexdigest() # noqa: S324
+ return f"partition_transform_verdict:{digest}"
+
+
+def record_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ *,
+ mirrors: bool,
+) -> None:
+ """
+ Remember whether this transform produced a mirror, for the UI to read.
+
+ Advisory only. Nothing in the query path consults it: a probe that failed
+ once is retried on the next chart exactly as it is today, because declining
+ to prune for a whole cache timeout over one transient engine blip is the
+ trade `evaluate_transform` deliberately refuses -- see the comment where it
+ declines to cache a failure.
+
+ What this is for is the *claim*. `is_transform_active` parses the transform
+ and no more, so a transform the database rejects -- a misspelled function
+ is the common case -- is "active", and the editor's banner and Explore's
+ pruning glyph promise a speed-up that never happens. A promise is exactly
+ the thing that may be withheld on one bad answer and restored on a good
+ one, which is why this is a separate entry from the probe's own results
+ rather than a relaxation of that rule.
+
+ Written by `_run_probe`, so the preview endpoint -- which shares the
+ evaluator -- settles the question before the owner has even saved.
+ """
+ timeout = app.config.get("PARTITION_TRANSFORM_PROBE_CACHE_TIMEOUT", 24 * 60 * 60)
+ try:
+ cache_manager.cache.set(
+ _mirror_verdict_cache_key(database, catalog, schema, transform),
+ mirrors,
+ timeout=timeout,
+ )
+ except Exception: # pylint: disable=broad-except
+ logger.warning("Could not cache partition transform verdict", exc_info=True)
+
+
+def known_mirror_verdict(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> bool | None:
+ """
+ The last verdict `record_mirror_verdict` stored, or `None` if there is none.
+
+ `None` is the honest answer on a cold cache and is deliberately not `False`:
+ reporting a working mapping as broken until something probes it would
+ trade one wrong claim for another. The alternative -- probing from the
+ read side -- would put a warehouse round trip on every Explore and
+ dashboard load, and a failing transform is not cached at all, so it would
+ be a round trip every single time.
+ """
+ try:
+ verdict = cache_manager.cache.get(
+ _mirror_verdict_cache_key(database, catalog, schema, transform)
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return verdict if isinstance(verdict, bool) else None
+
+
+def _compile_literal(element: Any, dialect: Dialect | None) -> str:
+ """
+ Compile with inline literals, undoing the paramstyle's percent doubling.
+
+ Both ``TextClause`` and literal compilation run the dialect's
+ ``post_process_text``, which doubles every ``%`` whenever the identifier
+ preparer asks it to -- true for MySQL and Postgres and for every spec
+ inheriting their paramstyle. That doubling exists so a later DBAPI
+ parameter-interpolation pass can undo it, and the probe has no such pass:
+ it executes with no bound parameters at all. So a transform of
+ ``date_format(:value, '%Y%m%d')`` reaches the warehouse asking for the
+ literal string ``%%Y%%m%%d``, the probe returns that instead of a date, and
+ the mirrored predicate drops every row the filter keeps.
+
+ The same normalization ``Database.compile_sqla_query`` applies for the same
+ reason. ``_double_percents`` is private and not guaranteed on a third-party
+ dialect, hence the ``getattr`` default.
+ """
+ compiled = str(
+ element.compile(dialect=dialect, compile_kwargs={"literal_binds": True})
+ )
+ if dialect is not None and getattr(
+ dialect.identifier_preparer, "_double_percents", False
+ ):
+ compiled = compiled.replace("%%", "%")
+ return compiled
+
+
+def _dialect_for(database: Database) -> Dialect | None:
+ """
+ The dialect used to render literals in the probe SQL.
+
+ Falls back to SQLAlchemy's default dialect if the database cannot produce
+ one -- the probe is best-effort and a rendering mismatch surfaces as a
+ failed probe, which fails open to no pruning.
+ """
+ try:
+ dialect = database.get_dialect()
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+ return dialect if isinstance(dialect, Dialect) else None
+
+
+def _hashable(value: Any) -> Any:
+ """Values arrive from user filters and are not guaranteed hashable."""
+ try:
+ hash(value)
+ except TypeError:
+ return repr(value)
+ return value
+
+
+@dataclass(frozen=True)
+class MappingValidationIssue:
+ """
+ One problem found with a mapping at save time.
+
+ ``blocking`` issues reject the save (400). The rest save fine and leave the
+ mapping inactive -- the PRD is explicit that a mapping "stays inactive until
+ it parses", so a half-written transform must not cost the owner the rest of
+ their edits.
+ """
+
+ field: str
+ message: str
+ blocking: bool
+
+
+def validate_partition_mapping( # pylint: disable=too-many-arguments
+ *,
+ column_names: set[str],
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ transform: str | None,
+ engine: str,
+) -> list[MappingValidationIssue]:
+ """
+ Validate a dataset's partition mapping, in two tiers.
+
+ Tier 1 (``blocking=True``) is structural and safety: the columns have to
+ exist, a column cannot be *asked* to stand in for itself, and the transform
+ cannot carry Jinja or call a non-deterministic function. Tier 2
+ (``blocking=False``) is everything that merely leaves the mapping inactive
+ -- including a self-mapping nobody asked for, where the partition column
+ merely happens to be the default datetime column.
+
+ The Tier-1 transform checks need a successful parse to inspect anything, so
+ an unparseable transform falls through to Tier 2. That leaves them
+ unreachable in exactly the case where it doesn't matter: an unparseable
+ transform is never executed.
+ """
+ if not partition_column:
+ return []
+
+ issues: list[MappingValidationIssue] = []
+
+ if partition_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "Partition column %(name)s is not a column on this dataset.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column not in column_names:
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "Mapped column %(name)s is not a column on this dataset.",
+ name=partition_mapped_column,
+ ),
+ blocking=True,
+ )
+ )
+
+ if partition_mapped_column and partition_mapped_column == partition_column:
+ # Asked for explicitly, so report it as the mistake it is.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_column",
+ message=_(
+ "The partition column cannot be mapped onto itself. "
+ "%(name)s is both the partition column and the mapped "
+ "column.",
+ name=partition_column,
+ ),
+ blocking=True,
+ )
+ )
+ elif not partition_mapped_column and main_dttm_col == partition_column:
+ # Resolved onto itself only because the default datetime column happens
+ # to be the partition column -- a state metadata sync could produce
+ # without anyone asking for it. The mapping is inert either way, since
+ # `resolve_partition_mapping` bails out on it, so this reports and lets
+ # the write through: blocking here means a dataset already in the state
+ # can never be saved again, not even to change its description, and
+ # there is no field whose edit would clear the error first.
+ issues.append(
+ MappingValidationIssue(
+ field="partition_mapped_column",
+ message=_(
+ "%(name)s is both the partition column and the default "
+ "datetime column, so the mapping points at itself and "
+ "stays inactive. Set a mapped column override, or change "
+ "the default datetime column.",
+ name=partition_column,
+ ),
+ blocking=False,
+ )
+ )
+
+ issues.extend(validate_transform(transform, engine))
+ return issues
+
+
+def drop_unmapped_value_transforms(
+ columns: list[dict[str, Any]] | None,
+ *,
+ partition_column: str | None,
+ partition_mapped_column: str | None,
+ main_dttm_col: str | None,
+ names_by_id: dict[int, str] | None = None,
+ stored_by_name: dict[str, tuple[str | None, bool]] | None = None,
+) -> list[str]:
+ """
+ Null the value transform on every *incoming* column the mapping cannot mirror.
+
+ The write-side twin of `DatasetDAO.clear_unmapped_partition_transforms`,
+ which answers for the model. A mapping has exactly one mirrored column, so
+ at most one column may carry a transform. One parked on any other column is
+ invisible -- no row but the mapped one renders a transform -- and yet it is
+ stored, and it goes live the moment the mapped column resolves back to it.
+ Clearing an override is enough to do that: a null
+ ``partition_mapped_column`` means "follow ``main_dttm_col``".
+
+ Ungated on the feature flag, unlike its model-level twin, and the difference
+ is what each one discards. That one drops stored configuration, so with the
+ flag off it would be pure loss. This one drops only a value the request in
+ hand is asking to write where the invariant says none may live -- and the
+ flag-off window is precisely when such a value gets parked for later, since
+ the editor hides these fields and the model-level pass declines to run.
+
+ Three writers reach the columns with no effective model-level pass between
+ them, which is why this exists at all: the deprecated
+ ``POST /datasource/save/``, which writes straight through
+ `update_from_object` and so never had one; and a
+ ``PUT /api/v1/dataset/<pk>`` or a dataset import made while the flag is
+ off, where the pass runs on both sides of the write and declines on both.
+
+ Mutates the payload in place, because every caller hands its own request
+ dict straight on to the code that writes it. Returns the names it cleared,
+ so the caller can say so in a log: this is a silent correction to a payload
+ whose author may have meant it.
+
+ A column whose payload mentions neither field is left alone. "Incoming" is
+ the whole scope -- a transform already in storage on a column this request
+ says nothing about is the model-level pass's business, under its own flag.
+
+ The mapped column resolves the way every other reader resolves it,
+ ``partition_mapped_column or main_dttm_col``, and resolves to nothing
+ without a partition column -- in which case no column may hold a transform
+ either.
+
+ :param names_by_id: how to read the name off a payload entry that gives
+ only an ``id``. `DatasetDAO._upsert_columns` identifies an existing
+ column by its primary key and lets ``column_name`` be omitted -- the
+ column keeps the name it has -- so without this an ordinary PUT looked
+ like a payload of nameless columns, none of which matched the mapped
+ one, and every transform in it was dropped. Callers whose writer keys
+ on the name instead (`update_from_object`, the importer) pass nothing.
+ An entry this cannot name is left alone rather than guessed at.
+ :param stored_by_name: ``(transform, is_monotonic)`` as currently stored,
+ per column name, so an *echo* can be told from an introduction. A
+ GET-then-PUT client sends back every column exactly as it received it,
+ so changing the default datetime column away from the mapped one made
+ the payload's unchanged copy of its transform look like a value being
+ parked -- and nulling it destroyed configuration the owner never
+ touched, unrecoverably, with the flag off and the editor's own fields
+ hidden. An unchanged value is the model-level pass's business under its
+ own flag, which is the same line this function's docstring already
+ draws for a column the payload omits. Callers that cannot see storage
+ pass nothing and keep the stricter behaviour.
+ """
+ mapped_column = (
+ (partition_mapped_column or main_dttm_col) if partition_column else None
+ )
+ cleared: list[str] = []
+ for column in columns or []:
+ name = column.get("column_name")
+ if name is None and names_by_id is not None:
+ column_id = column.get("id")
+ if column_id is not None:
+ name = names_by_id.get(column_id)
+ if name is None or name == mapped_column:
+ continue
+ transform = column.get("partition_value_transform")
+ is_monotonic = column.get("partition_transform_is_monotonic")
+ if not transform and not is_monotonic:
+ continue
+ if stored_by_name is not None and name in stored_by_name:
+ stored_transform, stored_monotonic = stored_by_name[name]
+ if transform == stored_transform and bool(is_monotonic) == bool(
Review Comment:
This echo check compares `bool(is_monotonic)` against storage, but `_upsert_columns` only writes the keys a column entry carries, so an entry with the unchanged `partition_value_transform` and no `partition_transform_is_monotonic` key is a valid partial update. Here the missing key reads as `None`, so with the flag off and a stored monotonic flag of `true`, a PUT that changes `main_dttm_col` and echoes only the transform fails the exemption and both fields are written back as `NULL`/`False`, the same unrecoverable loss the exemption exists to prevent. Could an absent key count as unchanged, e.g. `"partition_transform_is_monotonic" not in column or bool(is_monotonic) == bool(stored_monotonic)`?
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,3128 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Sequence
+from dataclasses import dataclass
+from datetime import date, datetime
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: The opening and closing delimiters of each kind of Jinja block. The probe
+#: would render these in a different context at a different time from the chart
+#: query, so a transform holding one is rejected at save time.
+JINJA_BLOCK_DELIMITERS = (("{{", "}}"), ("{%", "%}"), ("{#", "#}"))
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: A PostgreSQL Unicode-escaped identifier, ``U&"..."``.
+#:
+#: The second construct that breaks the premise above, and in the same way:
+#: ``U&"\\0071uery_to_xml"(...)`` parses as an anonymous function whose name is
+#: the *literal* ``\\0071uery_to_xml``, so the function denylist is matching a
+#: name the engine never sees -- PostgreSQL decodes the escape and runs
+#: ``query_to_xml``, handing a dataset owner rows from outside their RLS scope
+#: through the preview's ``emitted_predicate``.
+#:
+#: Normalizing the escapes and re-checking would be the other repair, and is
+#: worse: it means reimplementing one engine's identifier decoding well enough
+#: to be a security boundary. Refusing the construct is exact, and costs
+#: nothing real -- a transform is a scalar function of ``:value``, and there is
+#: no reason to name a function or column through an escape sequence.
+#:
+#: Refused on every engine, like the executable comment, so a transform stored
+#: on SQLite cannot detonate when the dataset is re-pointed at PostgreSQL. The
+#: ``&`` may be separated from the ``U`` by nothing at all, but whitespace or a
+#: comment between the prefix and the string is not accepted by PostgreSQL
+#: either, so the strict form is the whole surface.
+#:
+#: Matched in raw text, so the prefix is refused inside a string literal too.
+#: That is the same trade the executable comment makes and has the same
+#: justification: a gate whose contract is to fire *before* the parse cannot
+#: ask the parse whether the text was quoted. ``concat(:value, 'u&"x"')`` is
+#: refused, which costs an owner nothing anyone writes.
+UNICODE_ESCAPED_IDENTIFIER_RE = re.compile(r'\bU&"', re.IGNORECASE)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate: a transform such as
+#: ``datediff(day, :value, LOCALTIMESTAMP)`` for a relative partition key is
+#: evaluated once and then keeps emitting yesterday's answer, so the chart
+#: silently drops rows after midnight.
+#:
+#: Matched by SQL function name, so every engine's spelling of "now" has to be
+#: named -- the ANSI four were not enough. Listed rather than delegated to the
+#: engine specs because the risk is the same everywhere and a spec that had not
+#: got round to declaring its own would fail open; a name no engine has is
+#: inert, so over-listing costs nothing.
+NON_DETERMINISTIC_FUNCTIONS = {
+ # ANSI, and the engines that spell it this way.
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "LOCALTIME",
+ "LOCALTIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+ # PostgreSQL. `now()` is statement-stable; these two are not even that.
+ "CLOCK_TIMESTAMP",
+ "STATEMENT_TIMESTAMP",
+ "TIMEOFDAY",
+ # MySQL and MariaDB.
+ "CURDATE",
+ "CURTIME",
+ "SYSDATE",
+ "UTC_DATE",
+ "UTC_TIME",
+ "UTC_TIMESTAMP",
+ "UUID_SHORT",
+ # Oracle.
+ "SYSTIMESTAMP",
+ "SYS_GUID",
+ # SQL Server.
+ "GETDATE",
+ "GETUTCDATE",
+ "SYSDATETIME",
+ "SYSUTCDATETIME",
+ "SYSDATETIMEOFFSET",
+ "NEWID",
+ # BigQuery.
+ "CURRENT_DATETIME",
+ "GENERATE_UUID",
+ # Snowflake.
+ "RANDSTR",
+ "UUID_STRING",
+ # ClickHouse.
+ "NOW64",
+ "RANDCANONICAL",
+ "GENERATEUUIDV4",
+ # H2 and Derby, which the test fixtures use.
+ "RANDOM_UUID",
+}
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+class Unmirrorable:
+ """
+ A filter no mirror can stand in for, and why.
+
+ Returned by `ExploreMixin.mirror_probe_request` for a value the engine
+ compares more coarsely than the filter carries, one it cannot render as a
+ literal, one in a time frame the transform would discard, or an ``IN`` list
+ with a member of any of those kinds. An object rather than `None`, because
+ `None` is a filter value in its own right.
+
+ The reason rides along because the preview has to explain the decline to
+ the owner, and the two declines want different advice: "the engine compares
+ less of this value than you typed, so map a column it compares in full" is
+ sound guidance for a `DATE` column and actively misleading for an
+ offset-bearing bound on a `TIMESTAMP` one, which already is such a column.
+ Carried rather than re-derived so the preview's explanation cannot come
+ apart from the chart path's decision.
+
+ Lives here rather than beside that method so the preview can read it too:
+ `superset.models.helpers` imports this module, so these can only cross the
+ boundary in this direction. Both callers recognise the same instances -- a
+ preview that answered "valid" for a request the chart path declines is the
+ drift this is here to prevent.
+ """
+
+ __slots__ = ("reason",)
+
+ def __init__(self, reason: str) -> None:
+ self.reason = reason
+
+ def __repr__(self) -> str:
+ return f"<Unmirrorable {self.reason}>"
+
+
+#: The ordinary decline: whatever the mirror cannot be built from, with the
+#: engine's own comparison resolution as the reason an owner can act on.
+UNMIRRORABLE = Unmirrorable("resolution")
+
+#: A value carrying a UTC offset, declined whatever the column's resolution.
+#: A transform such as ``CAST(:value AS TIMESTAMP)`` drops the offset, so even
+#: an engine that compares the whole instant would be probed in the wrong
+#: frame -- which is not something mapping a different column fixes.
+UNMIRRORABLE_OFFSET = Unmirrorable("offset")
+
+
+def is_unmirrorable(value: Any) -> bool:
+ """Whether `mirror_probe_request` declined this request."""
+ return isinstance(value, Unmirrorable)
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+#: Declared types whose comparison ignores trailing blanks.
+#:
+#: The fixed-width character types, which the SQL standard has compare as
+#: though both sides were padded to the same length -- so ``'US'`` and
+#: ``'US '`` are equal in a ``CHARACTER(3)``, while ``lower()`` of the two is
+#: not. Spelled out rather than matched by prefix because the variable-width
+#: names start with the same letters: ``VARCHAR`` and ``CHARACTER VARYING``
+#: compare the blanks and must not land here.
+PADDED_CHARACTER_TYPES = frozenset(
+ {
+ "CHAR",
+ "NCHAR",
+ # PostgreSQL's own name for ``CHARACTER``, which is what reflection
+ # reports for a ``CHAR(n)`` column there.
+ "BPCHAR",
+ "CHARACTER",
+ "NATIONAL CHAR",
+ "NATIONAL CHARACTER",
+ }
+)
+
+
+def _is_padded_character_type(column: TableColumn) -> bool:
+ """
+ Whether ``column``'s declared type compares without its trailing blanks.
+
+ Read off the declared type rather than the engine spec's resolved one: the
+ specs map ``CHAR`` and ``VARCHAR`` onto the same `sqlalchemy.String`, so
+ the distinction this needs is gone by then. The length suffix is dropped
+ and the name matched against `PADDED_CHARACTER_TYPES`, so an unfamiliar
+ spelling answers ``False`` and the engine-level flag decides as before --
+ this gate adds a decline rather than lifting one. A column with no
+ declared type has nothing to read, and answers the same way.
+ """
+ if not isinstance(column.type, str):
+ return False
+ native = re.sub(r"\s+", " ", column.type.strip().upper())
+ return native.split("(")[0].strip() in PADDED_CHARACTER_TYPES
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ Padding is asked about per column, because it is a property of the *type*
+ rather than of the engine. ``binary_string_comparison`` speaks for an
+ engine's default text comparison, and on PostgreSQL -- which declares it
+ -- a ``CHAR(2)`` still matches a filter for ``'US '`` against a stored
+ ``'US'``, because the standard says a padded character type compares
+ without its trailing blanks. The mirror ``region_key = lower('US ')`` then
+ excludes the row. So a fixed-width character type declines whatever the
+ engine says, and an engine that ignores trailing blanks on its *variable*
+ types says so by not declaring the flag at all (see `RedshiftEngineSpec`).
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ # Ahead of the generic-type question, which a padded type can lose: the
+ # specs map ``CHARACTER`` onto no generic type at all on some engines, and
+ # a fixed-width character type is a string whether or not Superset can say
+ # so from the name.
+ if _is_padded_character_type(column):
+ return False
+ try:
+ is_string = column.type_generic == utils.GenericDataType.STRING
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ # An unresolvable type is treated as a string: the gate exists to stop
+ # a silent wrong answer, so it fails closed.
+ return False
+ if not is_string:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_unicode_escaped_identifier(transform: str | None) -> bool:
+ """Whether the transform names something through a ``U&"..."`` escape.
+
+ See `UNICODE_ESCAPED_IDENTIFIER_RE`. Answered on raw text for the same
+ reason as the comment above: the parse reports a name the engine does not
+ use, which is exactly what makes the denylist blind to it.
+ """
+ return (
+ bool(transform)
+ and UNICODE_ESCAPED_IDENTIFIER_RE.search(transform or "") is not None
+ )
+
+
+#: Sequence pseudo-columns, which advance a sequence when they are *read*.
+#:
+#: ``orders_seq.NEXTVAL`` parses as a qualified column reference, not a
+#: function call, so neither `SQLStatement.is_mutating` -- which walks function
+#: names -- nor the function denylist can see it. The probe would then run
+#: ``SELECT orders_seq.NEXTVAL + 1 FROM DUAL`` and advance the sequence, again
+#: on every cache expiry, for a dataset editor holding neither SQL Lab nor a
+#: DML grant. Reading one is a write however the parser classifies it.
+#:
+#: The function spelling (``nextval('s')`` on PostgreSQL) is a different shape
+#: and is caught as a function; this is only about the suffix form.
+SEQUENCE_PSEUDO_COLUMNS = frozenset({"nextval", "currval"})
+
+#: The same thing written as a call.
+#:
+#: Only the suffix form parses as a column; `nextval('s')` on PostgreSQL and
+#: DuckDB, `NEXTVAL(s)`/`SETVAL(s, 1)` on MySQL and MariaDB, and SQL Server's
+#: `NEXT VALUE FOR s` all parse as functions. `SQLStatement.is_mutating` walks
+#: function names on PostgreSQL alone -- deliberately, since the same names are
+#: read-only elsewhere -- so every other engine let these through.
+#:
+#: Matched on the name whatever the engine, because advancing a sequence is a
+#: write wherever it happens and a transform has no reason to call one.
+SEQUENCE_FUNCTIONS = frozenset(
+ {"nextval", "setval", "next_value_for", "nextvalfor", "prevval", "lastval"}
+)
+
+
+def references_sequence(statement: SQLStatement) -> bool:
+ """Whether the statement reads or advances a sequence.
+
+ Both spellings: the pseudo-column suffix, which parses as a column (see
+ `SEQUENCE_PSEUDO_COLUMNS`), and the call, which parses as a function (see
+ `SEQUENCE_FUNCTIONS`).
+
+ Answered on the parse rather than on raw text, because position is what
+ makes it the construct: a column or alias merely *called* ``nextval`` is
+ an ordinary column, and a string literal holding the word is text.
+ """
+ return bool(
+ statement.get_column_names() & SEQUENCE_PSEUDO_COLUMNS
+ or statement.get_disallowed_functions(set(SEQUENCE_FUNCTIONS))
+ )
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """
+ Whether the transform contains a balanced Jinja block.
+
+ A block is an opening delimiter followed, anywhere later, by its closing
+ one -- the same thing ``{{.*?}}`` and its two siblings match under
+ ``re.DOTALL``. Scanned with `str.find` rather than that pattern, because a
+ lazy match retried from every opening delimiter is quadratic in a run of
+ them, and this runs on stored transforms with no length bound of its own:
+ `is_transform_active` reads whatever the column holds. The earliest opening
+ delimiter is the only one worth trying, since any closing delimiter after a
+ later one is also after it.
+ """
+ if not transform:
+ return False
+ for opening, closing in JINJA_BLOCK_DELIMITERS:
+ start = transform.find(opening)
+ if start != -1 and transform.find(closing, start + len(opening)) != -1:
+ return True
+ return False
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error( # noqa: C901
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ And it must be a *read*. Shape is a separate question from effect: a bare
+ scalar expression can still write, so `SQLStatement.is_mutating` is asked
+ too -- the same question SQL Lab and the chart executor ask before letting
+ SQL run. See the gate itself for what that reaches and what it does not.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ # Also ahead of the parse, and for a stronger reason than cost: every gate
+ # below reasons about the parse tree, and this is the one construct that
+ # makes the parse tree describe a different statement from the one the
+ # engine runs. Checked here as well as in `validate_transform` because this
+ # is the door a row written by an earlier release still comes through.
+ if contains_executable_comment(transform):
+ return str(
+ _(
+ "A partition value transform cannot contain a MySQL "
+ "executable comment, which the database executes and every "
+ "validator reads as a comment."
+ )
+ )
+
+ if contains_unicode_escaped_identifier(transform):
+ return str(
+ _(
+ "A partition value transform cannot name anything through a "
+ 'U&"..." escape sequence, which the database decodes and '
+ "every validator reads literally."
+ )
+ )
+
+ # Same door, same reason: the name the denylist below would match is not
+ # the name the engine resolves. See `UNICODE_ESCAPED_IDENTIFIER_RE`.
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The read-only gate, which nothing above implies. The shape gates ask what
+ # the transform *selects*; this asks what evaluating it *does*, and a bare
+ # scalar expression can still write. `nextval(:value)` on PostgreSQL
+ # advances a sequence: one function call, no clause, no sub-query, and not
+ # in the default `DISALLOWED_SQL_FUNCTIONS` either -- so every gate above
+ # passes it and the probe then runs it. `setval` is the same shape, and
+ # `exp.Execute` and the opaque-`exp.Command` forms arrive the same way.
+ #
+ # The large-object writers (`lo_export`, `lowrite`, `lo_from_bytea`, ...)
+ # are caught here too, and the shipped denylist happens to name them as
+ # well -- but that is config an operator can replace, while this is not.
+ #
+ # `is_mutating` is the same question SQL Lab, `get_virtual_table_metadata`
+ # and the chart executor ask before letting SQL run, so a transform is held
+ # to the bar the rest of Superset already sets rather than to one invented
+ # here. Unconditional rather than gated on `Database.allow_dml`: a transform
+ # is a scalar function of `:value` by definition, so there is no legitimate
+ # mutating one, and the probe runs on a cache schedule nobody chose -- a
+ # write would repeat every time the entry expired.
+ #
+ # It bears saying what this does not reach. A user-defined function whose
+ # body writes is a plain call no parser can tell from `lower(:value)`, and
+ # `is_mutating`'s function-name walk is PostgreSQL-only by design, since the
+ # same names are read-only elsewhere. Neither residual is specific to this
+ # feature -- a dataset editor can already have the engine evaluate an
+ # arbitrary expression through a calculated column or a virtual dataset's
+ # SQL -- and closing them means authorizing the preview against the
+ # database, not parsing harder.
+ if statement.is_mutating():
+ return str(
+ _(
+ "A partition value transform cannot change data. It is "
+ "evaluated against the database to check that it mirrors, so "
+ "it has to be a read."
+ )
+ )
+
+ # Not reached by the walk above, which is why it is its own gate: a
+ # sequence pseudo-column is a *column* to the parser and a write to the
+ # engine. See `SEQUENCE_PSEUDO_COLUMNS`.
+ if references_sequence(statement):
+ return str(
+ _(
+ "A partition value transform cannot read a sequence. "
+ "NEXTVAL advances the sequence every time it is evaluated, "
+ "and the transform is evaluated on a cache schedule."
+ )
+ )
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the probe
+ uninspected -- string elements are escaped by the dialect's own literal
+ processor. `probe_sql_is_evaluable` then re-reads the finished query, which
+ is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def _placeholder_is_bindable(transform: str) -> bool:
+ """
+ Whether SQLAlchemy's ``text()`` can see ``:value`` as a bound parameter.
+
+ `VALUE_PLACEHOLDER_RE` is ``:value\b``, which matches the placeholder in a
+ Postgres cast such as ``:value::bigint``. SQLAlchemy's own bind scan is
+ ``(?<![:\\w$]):([\\w$]+)(?![:\\w$])`` -- note the trailing exclusion -- so a
+ following colon stops it: ``text(":value::bigint")`` reports a parameter
+ named ``valu``, and ``.bindparams(bindparam("value"))`` then raises
+ ``ArgumentError``.
+
+ `_probe` swallows that, so the only symptom was a perfectly valid transform
+ whose mapping silently never pruned, and a preview reporting an engine
+ failure for SQL that was never sent. Every write-side gate passes the
+ transform: it parses, it is a bare expression, and the placeholder *is* in
+ an executable position.
+
+ Answered by attempting the bind itself rather than by pattern-matching
+ ``::`` or reading ``text()``'s private parameter map, so this cannot
+ disagree with what `build_probe_sql` is about to do -- on any dialect, or on
+ a SQLAlchemy whose scan changes.
+ """
+ try:
+ sa.text(transform).bindparams(sa.bindparam("value", value=None))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return False
+ return True
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ bindable = _placeholder_is_bindable(transform)
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ elif bindable:
+ clause = sa.text(transform).bindparams(sa.bindparam("value", value=value))
Review Comment:
A colon-word inside a string literal in the transform is read by `text()` as a second bind parameter, and with literal binds an unbound one renders as `NULL` rather than failing. On SQLite, `:value || ':suffix'` compiles for `'us'` to `'us' || 'NULL'`, so for a row with business value `'us'` and partition key `'us:suffix'` the mirror is `p = 'usNULL'` and the chart drops the row, with no error to swallow. The `:value::bigint` fix covers the placeholder only. Should the probe escape every colon that is not the `:value` placeholder before handing the text to `text()`, or should the write-side gate reject a transform that contains one?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "hughhhh (via GitHub)" <gi...@apache.org>.
hughhhh commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4364060599
##########
superset/db_engine_specs/oracle.py:
##########
@@ -36,6 +36,7 @@
class OracleEngineSpec(BaseEngineSpec):
engine = "oracle"
engine_name = "Oracle"
+ select_without_from_suffix = " FROM DUAL"
Review Comment:
Good catch. Fixed in [6f37942f48](https://github.com/apache/superset/pull/43870/commits/6f37942f48): whether a key holds only days is now read from the database's own dialect, which makes Oracle's `DATE` a `DateTime`, so the precision check runs and a time-of-day bound is declined (an exact midnight still mirrors).
##########
superset/datasets/api.py:
##########
@@ -2064,6 +2165,134 @@ def get(self, id_or_uuid: str, **kwargs: Any) -> Response:
entity_concurrency_token(SqlaTable, table.id, table.uuid),
)
+ @expose("/<int:pk>/partition_mapping/preview/", methods=("POST",))
+ @protect()
+ @safe
+ @statsd_metrics
+ @event_logger.log_this_with_context(
+ action=lambda self, *args, **kwargs: (
+ f"{self.__class__.__name__}.partition_mapping_preview"
+ ),
+ log_to_statsd=False,
+ )
+ def partition_mapping_preview(self, pk: int) -> Response:
Review Comment:
Fixed in [6f37942f48](https://github.com/apache/superset/pull/43870/commits/6f37942f48): a temporal sample is now previewed as a time range sends it (the typed literal), the text shape is probed too, and the preview refuses a transform whose two answers differ, showing both predicates.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "hughhhh (via GitHub)" <gi...@apache.org>.
hughhhh commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4391503271
##########
superset/connectors/sqla/partition_mapping.py:
##########
@@ -0,0 +1,3889 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+"""
+Partition filter mapping.
+
+Datasets on Hadoop-family engines are commonly partitioned on a *technical*
+column -- an epoch integer, a lowercased region key -- that no analyst would
+filter on. Unless a query carries a predicate on that column the engine scans
+every partition.
+
+A dataset owner names one partition column ``p``, one business column that
+filters are mirrored from, and a value transform ``T`` (a SQL expression
+containing a ``:value`` placeholder). Superset then appends an equivalent
+predicate on ``p`` to every query, so chart authors change nothing and queries
+prune.
+
+The load-bearing assumption
+---------------------------
+Everything here reasons about ``T(col) op T(v)``, but what is emitted is
+``p op T(v)`` -- a predicate on a *physically different column*. The step from
+one to the other is::
+
+ p = T(mapped_col) for every row in the table
+
+Superset cannot verify that; it is a property of whatever ETL populates the
+partition column. If that job lags, backfills with different logic, or writes
+the partition key in a different timezone, mirrored predicates silently drop
+real rows. The mapping is only as trustworthy as the pipeline behind it.
+
+Operator safety
+---------------
+A mirrored predicate ``P2`` may only be ``AND``-ed onto a query when the
+original predicate ``P1`` *implies* it:
+
+=========================================== =============================
+Original Safe when
+=========================================== =============================
+``col = v``, ``col IN (...)`` ``T`` is a function *and* the
+ engine compares ``col``
+ byte-exactly
+``col >=|>|<|<= v``, ``TEMPORAL_RANGE`` only if ``T`` is monotonic
+``col != v``, ``NOT IN``, ``LIKE``, ... never
+=========================================== =============================
+
+Monotonic here means non-decreasing, not strictly increasing: a bucketing
+transform such as a day key is monotonic and maps a whole day of timestamps
+onto one value. ``col < v`` then only implies ``T(col) <= T(v)``, so a strict
+bound is mirrored non-strictly -- see `mirror_operator`.
+
+Equality under the engine's own rules
+-------------------------------------
+"``T`` is a function" gives ``col = v`` implies ``T(col) = T(v)`` for *value*
+equality. The engine compares with *SQL* equality, and the two part company
+wherever that comparison is not byte-exact: under a case-insensitive collation
+a stored ``country`` of ``'us'`` satisfies a filter for ``'US'``, while the
+mirror ``region_key = hex('US')`` excludes the row and the chart loses it with
+nothing to indicate why. Trailing-space-insensitive ``CHAR`` comparison says
+the same thing about padding.
+
+So equality and ``IN`` are withdrawn for a *string* mapped column unless the
+engine spec declares ``binary_string_comparison`` -- `equality_mirrors_safely`.
+Numeric and temporal comparison is exact everywhere and is untouched, and range
+mirroring is untouched too: it already rests on the owner declaring ``T``
+order-preserving *with respect to the column's own order*, which is an
+assertion about the very semantics this is checking for.
+
+What the gate cannot see is a column declaring its own collation
+(``country COLLATE NOCASE``) on an otherwise byte-exact engine. Nothing in
+SQLAlchemy's reflection or the engine specs exposes that, so there it remains
+the owner's assumption, like ``p = T(mapped_col)`` itself.
+
+Resolution of the value the engine compares
+-------------------------------------------
+Every row of the table above assumes the engine compares the value the mirror
+was built from. It does not always. A ``DATE`` column compared against
+``'2026-07-06 10:08:11'`` is compared on the date part alone -- whether the
+engine writes the literal itself (``TO_DATE('2026-07-06', 'YYYY-MM-DD')`` on
+Postgres, ``DATE '2026-07-06'`` on Presto, Trino, BigQuery and some two dozen
+others) or applies an implicit cast to a bound string. The filter therefore
+keeps the whole of that day while ``p = T(2026-07-06 10:08:11)`` keeps one
+instant of it: narrower than the predicate it stands in for, which is the one
+thing a mirror may never be.
+
+What an engine throws away is detected from the column's type rather than
+enumerated per engine -- `ExploreMixin._engine_literal_resolution` -- and what
+to do about it is a property of the *operator*, not of the value:
+
+* a bound rounds outward, backward for a lower one and forward for an upper one,
+ through `ExploreMixin._round_bounds_outward`. The mirror then reads one extra
+ bucket at the edge, and the original predicate is still in the query to
+ exclude the rows that bucket adds.
+* an equality, or one member of an ``IN`` list, has nowhere to widen to: these
+ predicates are ``AND``-ed onto the query, so "or the day either side" is not
+ something the mirror can express. They decline, which costs the query its
+ pruning and nothing else.
+
+So a ``DATE``-typed mapped column mirrors a range at day granularity, and does
+not mirror an equality whose value carries a time of day at all. Map a
+``TIMESTAMP`` column instead and every operator is available again.
+
+Writing the value into the probe
+--------------------------------
+The probe evaluates the transform at a *literal*, because it runs with no bound
+parameters at all -- so every value is written into SQL text by the driver's
+literal renderer and read back by the engine's lexer, and the two do not always
+agree. SQLAlchemy's default renderer doubles apostrophes and leaves backslashes
+alone; Hive honours backslash escapes and not doubling, so ``'O''Brien'`` is
+read there as two adjacent literals and ``'x\\''`` ends four characters into a
+value the filter carries whole. A disagreement is either a mirror built from a
+value nobody filtered on -- dropping rows the filter keeps -- or, where the
+value closes its own quote, an expression of the filterer's choosing running in
+the probe.
+
+Which side is right is not knowable from the driver: it is a per-session server
+setting (``standard_conforming_strings``, ``NO_BACKSLASH_ESCAPES``,
+``spark.sql.parser.escapedStringLiterals``), and SQLAlchemy's own view of it is
+only correct on a dialect that has connected. So escaping is not what makes
+this safe. `literal_round_trips` renders the literal and reads it back in the
+engine's own dialect instead, and a value that does not survive the trip is not
+mirrored -- the usual trade, pruning for correctness. `probe_sql_is_evaluable`
+re-reads the finished statement behind it.
+
+The probe's *answers* make the same trip, in the other direction. The chart
+query is compiled with ``literal_binds``, so a probed partition key is rendered
+into its SQL by the same renderer and read by the same lexer -- and
+``concat(:value, chr(92), 'b')`` turns the unremarkable input ``a`` into the key
+``a\\b``, which Hive reads back as ``a`` followed by a backspace. So
+`_predicates_from_probe` asks `literal_round_trips` about each result too, and
+declines the request rather than emitting a predicate no row can satisfy: the
+mirror is ``AND``-ed onto the query, so a mirror that matches nothing costs the
+chart its rows rather than its pruning.
+
+Negations are never safe because ``T`` need not be injective:
+``lower(:value)`` with ``country != 'US'`` mirrors to ``region_key != 'us'``,
+which wrongly excludes rows whose ``country`` is already lowercase ``'us'`` --
+rows the original filter *keeps*.
+
+Monotonicity is a property of the transform, not of the column's data type:
+``hour(:value)``, ``date_format(:value, 'dd')`` and ``dayofweek(:value)`` are
+all reasonable transforms on a ``TIMESTAMP`` column and none of them preserve
+ordering. It is therefore declared by the owner, not inferred.
+
+Time grains
+-----------
+A grained filter -- drill-to-detail, mostly -- compares the *truncated* column,
+``trunc(col) op v``, so the raw bounds it carries do not describe the rows it
+keeps. A row in the final partial bucket satisfies ``trunc(col) < until`` while
+``col < until`` excludes it.
+
+Which direction a grain rounds is not knowable from the duration alone, and the
+obvious guess is wrong: ``WEEK_ENDING_SATURDAY`` rounds *forward* on Hive and
+Presto, and Ocient's grains are ``ROUND``, i.e. to nearest. What every grain
+does satisfy is a bound on the displacement::
+
+ |trunc(ts) - ts| < width(grain)
+
+so widening *both* bounds by one bucket width is no narrower than the real
+predicate whichever way the grain rounds -- and it needs no monotonicity of
+``trunc`` itself, which is what rescues Hive's oddly-anchored ``P1W``. Width is
+a property of the grain, not of the engine, which is what makes this
+maintainable; see `grain_bucket_width`. A grain whose SQL an operator supplied
+has no known width, and does not mirror at all.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import logging
+import numbers
+import re
+from collections.abc import Mapping, Sequence
+from dataclasses import dataclass
+from datetime import date, datetime, time, timedelta
+from functools import lru_cache
+from typing import Any, cast, TYPE_CHECKING
+
+import numpy as np
+import pandas as pd
+import sqlalchemy as sa
+from dateutil.relativedelta import relativedelta
+from flask import current_app as app
+from flask_babel import lazy_gettext as _
+from sqlalchemy.engine.interfaces import Dialect
+from sqlalchemy.sql.elements import ColumnElement
+
+from superset.constants import LRU_CACHE_MAX_SIZE, TimeGrain
+from superset.exceptions import (
+ QueryClauseValidationException,
+ SupersetParseError,
+ SupersetSecurityException,
+)
+from superset.extensions import cache_manager, feature_flag_manager
+from superset.sql.parse import SQLScript, SQLStatement
+from superset.superset_typing import FilterValues
+from superset.utils import core as utils, json
+from superset.utils.core import FilterOperator, get_username
+
+if TYPE_CHECKING:
+ from superset.connectors.sqla.models import SqlaTable, TableColumn
+ from superset.db_engine_specs.base import BaseEngineSpec
+ from superset.models.core import Database
+
+logger = logging.getLogger(__name__)
+
+FEATURE_FLAG = "PARTITION_FILTER_MAPPING"
+
+#: Longest transform accepted anywhere. A transform is one SQL expression an
+#: owner types by hand, so this is generous; the point is that it is bounded.
+#: The bound matters because `is_transform_active` parses the stored value on
+#: each Explore load, and an unbounded string would make that parse the
+#: expensive part of rendering a chart.
+#:
+#: The typed column field, the import schema and the preview request each
+#: enforce it through a marshmallow `Length` validator, which is what produces
+#: the per-field message those three callers want. `stored_expression_error`
+#: enforces it too, for the paths that load no schema -- the deprecated
+#: `POST /datasource/save/` is one, and it writes straight through
+#: `update_from_object`.
+MAX_TRANSFORM_LENGTH = 1024
+
+#: Placeholder the owner writes in the transform, e.g. ``unix_timestamp(:value)``.
+#: Matched with word boundaries so ``:values`` is not mistaken for it.
+VALUE_PLACEHOLDER_RE = re.compile(r":value\b")
+
+#: The opening and closing delimiters of each kind of Jinja block. The probe
+#: would render these in a different context at a different time from the chart
+#: query, so a transform holding one is rejected at save time.
+JINJA_BLOCK_DELIMITERS = (("{{", "}}"), ("{%", "%}"), ("{#", "#}"))
+
+#: MySQL and MariaDB "executable comments": ``/*!50000 ... */`` and
+#: ``/*M!50000 ... */`` are comments to every other reader and *statement text*
+#: to those two engines.
+#:
+#: This is the one construct that breaks the premise the probe's shape gates
+#: rest on -- that the parse this module inspects and the statement the engine
+#: runs are the same statement. ``1 /*!50000 + (SELECT secret FROM vault) */``
+#: parses with no sub-query and no FROM, clears `stored_expression_error` and
+#: `probe_sql_is_evaluable` alike, and then reads a table on MySQL. The result
+#: comes back to a dataset owner through the preview's ``emitted_predicate``,
+#: with no RLS applied and no SQL Lab access needed.
+#:
+#: Refused on every engine rather than only the two that honour it. A transform
+#: is a scalar function of ``:value``; there is no legitimate reason for one to
+#: carry a comment of any kind, let alone this one, and a per-engine gate would
+#: store a transform on Postgres that detonates when the dataset is re-pointed
+#: at MySQL.
+EXECUTABLE_COMMENT_RE = re.compile(r"/\*M?!")
+
+#: A PostgreSQL Unicode-escaped identifier, ``U&"..."``.
+#:
+#: The second construct that breaks the premise above, and in the same way:
+#: ``U&"\\0071uery_to_xml"(...)`` parses as an anonymous function whose name is
+#: the *literal* ``\\0071uery_to_xml``, so the function denylist is matching a
+#: name the engine never sees -- PostgreSQL decodes the escape and runs
+#: ``query_to_xml``, handing a dataset owner rows from outside their RLS scope
+#: through the preview's ``emitted_predicate``.
+#:
+#: Normalizing the escapes and re-checking would be the other repair, and is
+#: worse: it means reimplementing one engine's identifier decoding well enough
+#: to be a security boundary. Refusing the construct is exact, and costs
+#: nothing real -- a transform is a scalar function of ``:value``, and there is
+#: no reason to name a function or column through an escape sequence.
+#:
+#: Refused on every engine, like the executable comment, so a transform stored
+#: on SQLite cannot detonate when the dataset is re-pointed at PostgreSQL. The
+#: ``&`` may be separated from the ``U`` by nothing at all, but whitespace or a
+#: comment between the prefix and the string is not accepted by PostgreSQL
+#: either, so the strict form is the whole surface.
+#:
+#: Matched in raw text, so the prefix is refused inside a string literal too.
+#: That is the same trade the executable comment makes and has the same
+#: justification: a gate whose contract is to fire *before* the parse cannot
+#: ask the parse whether the text was quoted. ``concat(:value, 'u&"x"')`` is
+#: refused, which costs an owner nothing anyone writes.
+UNICODE_ESCAPED_IDENTIFIER_RE = re.compile(r'\bU&"', re.IGNORECASE)
+
+#: Substituted for ``:value`` before parsing -- sqlglot rejects a bare ``:value``
+#: on most dialects. Mirrors the ``_JINJA_BLOCK_RE`` -> ``NULL`` trick used by
+#: ``validate_stored_expression``.
+_PARSE_STANDIN = "NULL"
+
+#: Substituted for ``:value`` to find out *where* the placeholder landed, which
+#: `_PARSE_STANDIN` cannot answer: ``NULL`` is a keyword, so after substitution
+#: the parse tree no longer records that a placeholder was ever there. An
+#: identifier does leave a trace -- a column reference -- and one that is
+#: missing is a placeholder the engine will never evaluate.
+#:
+#: Named so it cannot plausibly collide with a real column, but a transform that
+#: writes it anyway is refused rather than counted. A hand-written occurrence
+#: does not merely make the count disagree: it *supplies* the column reference a
+#: non-executable placeholder failed to produce, and the two cancel exactly. See
+#: `placeholder_is_executable`.
+_PLACEHOLDER_STANDIN = "superset_pfm_value_standin"
+
+#: Functions whose value depends on wall-clock time or randomness. The probe
+#: runs in a different session at a different moment from the chart query and
+#: its result is then cached, so any of these freezes a snapshot of probe time
+#: into the emitted predicate: a transform such as
+#: ``datediff(day, :value, LOCALTIMESTAMP)`` for a relative partition key is
+#: evaluated once and then keeps emitting yesterday's answer, so the chart
+#: silently drops rows after midnight.
+#:
+#: Matched by SQL function name, so every engine's spelling of "now" has to be
+#: named -- the ANSI four were not enough. Listed rather than delegated to the
+#: engine specs because the risk is the same everywhere and a spec that had not
+#: got round to declaring its own would fail open; a name no engine has is
+#: inert, so over-listing costs nothing.
+NON_DETERMINISTIC_FUNCTIONS = {
+ # ANSI, and the engines that spell it this way.
+ "CURRENT_DATE",
+ "CURRENT_TIME",
+ "CURRENT_TIMESTAMP",
+ "LOCALTIME",
+ "LOCALTIMESTAMP",
+ "NOW",
+ "RAND",
+ "RANDOM",
+ "UUID",
+ # PostgreSQL. `now()` is statement-stable; these two are not even that.
+ "CLOCK_TIMESTAMP",
+ "STATEMENT_TIMESTAMP",
+ "TIMEOFDAY",
+ # MySQL and MariaDB.
+ "CURDATE",
+ "CURTIME",
+ "SYSDATE",
+ "UTC_DATE",
+ "UTC_TIME",
+ "UTC_TIMESTAMP",
+ "UUID_SHORT",
+ # Oracle.
+ "SYSTIMESTAMP",
+ "SYS_GUID",
+ # SQL Server.
+ "GETDATE",
+ "GETUTCDATE",
+ "SYSDATETIME",
+ "SYSUTCDATETIME",
+ "SYSDATETIMEOFFSET",
+ "NEWID",
+ # BigQuery.
+ "CURRENT_DATETIME",
+ "GENERATE_UUID",
+ # Snowflake.
+ "RANDSTR",
+ "UUID_STRING",
+ # ClickHouse.
+ "NOW64",
+ "RANDCANONICAL",
+ "GENERATEUUIDV4",
+ # H2 and Derby, which the test fixtures use.
+ "RANDOM_UUID",
+}
+
+#: The wall-clock names an engine evaluates with no parentheses at all.
+#:
+#: These parse as *column references*, not functions, so the name-based walk
+#: below cannot see them: `datediff(UTC_DATE, :value)` on MySQL and
+#: `:value - SYSDATE` on Oracle both cleared the gate and froze probe time into
+#: a cached mirror.
+#:
+#: A subset of `NON_DETERMINISTIC_FUNCTIONS` rather than the whole of it,
+#: because refusing a bare name costs an owner a column genuinely called that.
+#: Only the names SQL lets you write without ``()`` are listed -- the datetime
+#: keywords -- so `rand`, `uuid` and `newid`, which always need parentheses and
+#: are plausible column names, stay out.
+BARE_WALL_CLOCK_KEYWORDS = frozenset(
+ {
+ "current_date",
+ "current_time",
+ "current_timestamp",
+ "localtime",
+ "localtimestamp",
+ "utc_date",
+ "utc_time",
+ "utc_timestamp",
+ "sysdate",
+ "systimestamp",
+ }
+)
+
+#: Functions that mean "now" only in their zero-argument form. On Hive and
+#: Impala ``unix_timestamp()`` is the current time while ``unix_timestamp(x)``
+#: -- the canonical transform for this feature -- is pure.
+NON_DETERMINISTIC_WHEN_NILADIC = {"UNIX_TIMESTAMP"}
+
+#: Safe for any function ``T``.
+MIRRORABLE_ALWAYS = {FilterOperator.EQUALS, FilterOperator.IN}
+
+#: Safe only when ``T`` preserves ordering.
+MIRRORABLE_IF_MONOTONIC = {
+ FilterOperator.GREATER_THAN,
+ FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN,
+ FilterOperator.LESS_THAN_OR_EQUALS,
+ FilterOperator.TEMPORAL_RANGE,
+}
+
+
+#: Every operator that can be mirrored under *some* transform. The preview
+#: endpoint accepts these; whether a given one actually mirrors still depends on
+#: the monotonicity declaration.
+MIRRORABLE_OPERATORS = MIRRORABLE_ALWAYS | MIRRORABLE_IF_MONOTONIC
+
+#: Operators the preview endpoint can construct. `TEMPORAL_RANGE` is mirrored by
+#: the query path, but as *two* bounds that `_collect_partition_mirror_range`
+#: decomposes a time range into -- the preview request carries sample values, not
+#: a since/until pair, so there is no range for it to build. The editor never
+#: asks for one either: `previewOperatorFor` sends `>=`, `=` or `IN`.
+PREVIEWABLE_OPERATORS = MIRRORABLE_OPERATORS - {FilterOperator.TEMPORAL_RANGE}
+
+
+class Unmirrorable:
+ """
+ A filter no mirror can stand in for, and why.
+
+ Returned by `ExploreMixin.mirror_probe_request` for a value the engine
+ compares more coarsely than the filter carries, one it cannot render as a
+ literal, one whose rendered literal the engine would not read back as the
+ same value, one in a time frame the transform would discard, or an ``IN``
+ list with a member of any of those kinds. An object rather than `None`,
+ because `None` is a filter value in its own right.
+
+ The reason rides along because the preview has to explain the decline to
+ the owner, and the two declines want different advice: "the engine compares
+ less of this value than you typed, so map a column it compares in full" is
+ sound guidance for a `DATE` column and actively misleading for an
+ offset-bearing bound on a `TIMESTAMP` one, which already is such a column.
+ Carried rather than re-derived so the preview's explanation cannot come
+ apart from the chart path's decision.
+
+ Lives here rather than beside that method so the preview can read it too:
+ `superset.models.helpers` imports this module, so these can only cross the
+ boundary in this direction. Both callers recognise the same instances -- a
+ preview that answered "valid" for a request the chart path declines is the
+ drift this is here to prevent.
+ """
+
+ __slots__ = ("reason",)
+
+ def __init__(self, reason: str) -> None:
+ self.reason = reason
+
+ def __repr__(self) -> str:
+ return f"<Unmirrorable {self.reason}>"
+
+
+#: The ordinary decline: whatever the mirror cannot be built from, with the
+#: engine's own comparison resolution as the reason an owner can act on.
+UNMIRRORABLE = Unmirrorable("resolution")
+
+#: A value carrying a UTC offset, declined whatever the column's resolution.
+#: A transform such as ``CAST(:value AS TIMESTAMP)`` drops the offset, so even
+#: an engine that compares the whole instant would be probed in the wrong
+#: frame -- which is not something mapping a different column fixes.
+UNMIRRORABLE_OFFSET = Unmirrorable("offset")
+
+#: A value the driver and the engine would not spell the same way, declined
+#: whatever the column's resolution and whatever the operator. Nothing about
+#: the column or the transform fixes it -- see `literal_round_trips` -- so the
+#: advice the resolution reason carries would send an owner after the wrong
+#: thing entirely.
+UNMIRRORABLE_ESCAPING = Unmirrorable("escaping")
+
+
+def is_unmirrorable(value: Any) -> bool:
+ """Whether `mirror_probe_request` declined this request."""
+ return isinstance(value, Unmirrorable)
+
+
+#: A transform that preserves ordering need not be *strictly* increasing: a day
+#: key such as ``to_char(ts, 'YYYYMMDD')`` maps a whole day of timestamps onto
+#: one value. For such a ``T``, ``col < v`` only implies ``T(col) <= T(v)`` and
+#: ``col > v`` only implies ``T(col) >= T(v)`` -- the rows in the bucket at the
+#: boundary satisfy the non-strict form and not the strict one. A strict mirror
+#: therefore drops rows the filter keeps, which is the one thing a mirror may
+#: never do, so a strict bound is mirrored non-strictly.
+_NON_STRICT_EQUIVALENT = {
+ FilterOperator.GREATER_THAN: FilterOperator.GREATER_THAN_OR_EQUALS,
+ FilterOperator.LESS_THAN: FilterOperator.LESS_THAN_OR_EQUALS,
+}
+
+
+def mirror_operator(operator: FilterOperator) -> FilterOperator:
+ """
+ The operator a mirrored predicate uses to stand in for ``operator``.
+
+ Strict bounds widen; everything else passes through. Idempotent, so it is
+ safe wherever a request may already have been widened.
+
+ The widened bound reads one extra partition at the edge, and the original
+ predicate is still in the query to exclude the rows that partition adds --
+ the same trade as the grain widening and the ``NULL``-partition escape.
+ Declaring the transform strictly increasing would buy that partition back,
+ which is not worth a second property only the owner can vouch for.
+ """
+ return _NON_STRICT_EQUIVALENT.get(operator, operator)
+
+
+def mirrorable_operators(
+ is_monotonic: bool, *, equality_is_safe: bool = True
+) -> set[FilterOperator]:
+ """
+ The operators whose predicates may be mirrored onto the partition column.
+
+ :param is_monotonic: whether the owner declared the transform
+ order-preserving
+ :param equality_is_safe: whether the engine's ``=`` on the mapped column
+ compares the way ``T`` was written against -- see
+ `equality_mirrors_safely`
+
+ Both call sites -- the query path through `PartitionMapping.mirrors` and the
+ Explore indicator through `partition_filter_mapping_summary` -- come through
+ here, which is what keeps the glyph from promising pruning the SQL will not
+ do.
+ """
+ operators = MIRRORABLE_ALWAYS if equality_is_safe else set()
+ if is_monotonic:
+ operators = operators | MIRRORABLE_IF_MONOTONIC
+ return set(operators)
+
+
+def _native_generic_type(
+ column: "TableColumn",
+) -> utils.GenericDataType | None:
+ """
+ What the engine spec makes of ``column``'s declared type.
+
+ `TableColumn.type_generic` answers ``TEMPORAL`` for every column carrying
+ ``is_dttm``, which is the right answer for a chart's time axis and the
+ wrong one for a comparison: an epoch ``BIGINT`` is a number to the engine
+ however it is labelled here. Falls back to the flag where the spec has no
+ answer, so a type Superset cannot resolve is no worse off than before.
+ """
+ try:
+ column_spec = column.db_engine_spec.get_column_spec(
+ column.type, db_extra=column.db_extra
+ )
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ column_spec = None
+ if column_spec is not None and column_spec.generic_type is not None:
+ return column_spec.generic_type
+ try:
+ return column.type_generic
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return None
+
+
+#: A declared type naming an array: PostgreSQL's ``TEXT[]`` / ``INTEGER[][]``
+#: / ``int[3]``, and the ``ARRAY<...>`` / ``ARRAY(...)`` / ``Array(...)``
+#: spellings of Hive, Spark, Trino, BigQuery and ClickHouse.
+#: The bracket body is written so no two runs can match the same blanks:
+#: ``\s*\d*\s*`` backtracks polynomially on a long run of spaces.
+_ARRAY_TYPE_RE = re.compile(r"(?:\[\s*(?:\d+\s*)?\])+\s*$|^\s*ARRAY\b", re.IGNORECASE)
+
+
+def declares_array_type(column_type: str | None) -> bool:
+ """
+ Whether a declared column type is an array, whatever the engine spec says.
+
+ The engine spec only reports ``MULTI_VALUE`` where it has opted into
+ ``supports_multivalue_columns``; PostgreSQL has not, and resolves ``TEXT[]``
+ to ``STRING`` and ``INTEGER[]`` to ``NUMERIC``. So an array partition column
+ there cleared the array refusal, previewed valid, and every equality chart
+ on the mapping failed with ``malformed array literal``. The declared type
+ is what the engine will compare, so it is read directly as well.
+ """
+ return bool(column_type and _ARRAY_TYPE_RE.search(column_type))
+
+
+#: Declared types whose comparison ignores trailing blanks.
+#:
+#: The fixed-width character types, which the SQL standard has compare as
+#: though both sides were padded to the same length -- so ``'US'`` and
+#: ``'US '`` are equal in a ``CHARACTER(3)``, while ``lower()`` of the two is
+#: not. Spelled out rather than matched by prefix because the variable-width
+#: names start with the same letters: ``VARCHAR`` and ``CHARACTER VARYING``
+#: compare the blanks and must not land here.
+PADDED_CHARACTER_TYPES = frozenset(
+ {
+ "CHAR",
+ "NCHAR",
+ # PostgreSQL's own name for ``CHARACTER``, which is what reflection
+ # reports for a ``CHAR(n)`` column there.
+ "BPCHAR",
+ "CHARACTER",
+ "NATIONAL CHAR",
+ "NATIONAL CHARACTER",
+ }
+)
+
+
+def _is_padded_character_type(column: TableColumn) -> bool:
+ """
+ Whether ``column``'s declared type compares without its trailing blanks.
+
+ Read off the declared type rather than the engine spec's resolved one: the
+ specs map ``CHAR`` and ``VARCHAR`` onto the same `sqlalchemy.String`, so
+ the distinction this needs is gone by then. The length suffix is dropped
+ and the name matched against `PADDED_CHARACTER_TYPES`, so an unfamiliar
+ spelling answers ``False`` and the engine-level flag decides as before --
+ this gate adds a decline rather than lifting one. A column with no
+ declared type has nothing to read, and answers the same way.
+ """
+ if not isinstance(column.type, str):
+ return False
+ native = re.sub(r"\s+", " ", column.type.strip().upper())
+ return native.split("(")[0].strip() in PADDED_CHARACTER_TYPES
+
+
+def equality_mirrors_safely(
+ column: TableColumn | None,
+ db_engine_spec: type[BaseEngineSpec],
+) -> bool:
+ """
+ Whether ``col = v`` on this column implies ``T(col) = T(v)`` in the engine.
+
+ The operator matrix calls equality safe "for any function ``T``" because
+ ``T`` is a function, so ``col = v`` gives ``T(col) = T(v)``. That reasons
+ about *value* equality while the engine reasons about *SQL* equality, and
+ the two part company under any comparison that is not byte-exact: with a
+ case-insensitive collation a stored ``country`` of ``'us'`` satisfies a
+ filter for ``'US'``, but the mirror ``region_key = hex('US')`` excludes the
+ row and the chart loses it with no indication why. Trailing-space-insensitive
+ ``CHAR`` comparison says the same thing about padding.
+
+ Only string columns are at risk; numeric and temporal comparison is exact
+ everywhere. And only equality: range mirroring already requires the owner
+ to declare ``T`` order-preserving *with respect to the column's own order*,
+ which is an assertion about the same comparison semantics this is checking
+ for -- so the declaration covers it where equality has nothing to cover it.
+
+ Padding is asked about per column, because it is a property of the *type*
+ rather than of the engine. ``binary_string_comparison`` speaks for an
+ engine's default text comparison, and on PostgreSQL -- which declares it
+ -- a ``CHAR(2)`` still matches a filter for ``'US '`` against a stored
+ ``'US'``, because the standard says a padded character type compares
+ without its trailing blanks. The mirror ``region_key = lower('US ')`` then
+ excludes the row. So a fixed-width character type declines whatever the
+ engine says, and an engine that ignores trailing blanks on its *variable*
+ types says so by not declaring the flag at all (see `RedshiftEngineSpec`).
+
+ The type asked for is the engine spec's reading of the column's declared
+ type, not `TableColumn.type_generic`, which answers ``TEMPORAL`` for
+ anything carrying ``is_dttm``. A ``VARCHAR`` flagged temporal is still text
+ to the engine: on MySQL a filter for ``'2026-01-01T00:00:00'`` matches a
+ stored ``'...t00:00:00'``, while the mirror ``p = hex('...T...')`` excludes
+ it -- and asking the semantic flag skipped the check entirely.
+
+ A type the spec cannot classify declines, which is what the paragraph above
+ promises and what only the exception branch used to do. PostgreSQL's
+ ``citext`` matches no type pattern, so it answered ``None`` -- neither
+ string nor not-string -- and was waved through, which is precisely wrong
+ for a type whose whole purpose is case-insensitive comparison. Declining
+ costs the pruning; admitting it costs rows.
+
+ What this cannot see is a column that declares its own collation
+ (``country COLLATE NOCASE``) on an otherwise byte-exact engine. Neither
+ SQLAlchemy's reflection nor the engine specs expose it, so on such a column
+ the assumption stays where ``p = T(mapped_col)`` already is: with the owner.
+ """
+ if column is None:
+ return True
+ # Ahead of the generic-type question, which a padded type can lose: the
+ # specs map ``CHARACTER`` onto no generic type at all on some engines, and
+ # a fixed-width character type is a string whether or not Superset can say
+ # so from the name.
+ if _is_padded_character_type(column):
+ return False
+ generic_type = _native_generic_type(column)
+ if generic_type is None:
+ return False
+ if generic_type != utils.GenericDataType.STRING:
+ return True
+ return bool(db_engine_spec.binary_string_comparison)
+
+
+#: How wide one bucket of each built-in time grain is.
+#:
+#: Keyed on the ISO duration a filter carries in its ``grain``. Written out
+#: rather than parsed: four of the week grains are ISO *intervals* with an
+#: anchor (``P1W/1970-01-03T00:00:00Z``) that ``isodate.parse_duration``
+#: rejects outright, and ``PT0.5H`` / ``P0.25Y`` are fractional. A literal
+#: table is also the thing a reviewer can check a line at a time.
+#:
+#: ``relativedelta`` rather than ``timedelta`` so the calendar grains stay
+#: calendar arithmetic: a month is not 30 days.
+GRAIN_BUCKET_WIDTHS: dict[str, relativedelta] = {
+ TimeGrain.SECOND: relativedelta(seconds=1),
+ TimeGrain.FIVE_SECONDS: relativedelta(seconds=5),
+ TimeGrain.THIRTY_SECONDS: relativedelta(seconds=30),
+ TimeGrain.MINUTE: relativedelta(minutes=1),
+ TimeGrain.FIVE_MINUTES: relativedelta(minutes=5),
+ TimeGrain.TEN_MINUTES: relativedelta(minutes=10),
+ TimeGrain.FIFTEEN_MINUTES: relativedelta(minutes=15),
+ TimeGrain.THIRTY_MINUTES: relativedelta(minutes=30),
+ TimeGrain.HALF_HOUR: relativedelta(minutes=30),
+ TimeGrain.HOUR: relativedelta(hours=1),
+ TimeGrain.SIX_HOURS: relativedelta(hours=6),
+ TimeGrain.DAY: relativedelta(days=1),
+ TimeGrain.WEEK: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_SUNDAY: relativedelta(days=7),
+ TimeGrain.WEEK_STARTING_MONDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SATURDAY: relativedelta(days=7),
+ TimeGrain.WEEK_ENDING_SUNDAY: relativedelta(days=7),
+ TimeGrain.MONTH: relativedelta(months=1),
+ TimeGrain.QUARTER: relativedelta(months=3),
+ TimeGrain.QUARTER_YEAR: relativedelta(months=3),
+ TimeGrain.YEAR: relativedelta(years=1),
+}
+
+
+def grain_bucket_width(grain: str | None, engine: str) -> relativedelta | None:
+ """
+ How far a grain's truncation can move a timestamp, or ``None`` if unknown.
+
+ A grained filter compares the *truncated* column, so the raw bounds it
+ carries do not describe the rows it keeps. Widening both bounds by one
+ bucket recovers a predicate that is no narrower than the real one -- see
+ `_collect_partition_mirror_range` for the argument. That only works for a
+ grain whose bucket width Superset knows, which excludes anything an
+ operator supplied.
+
+ :param grain: the ISO duration from the filter's ``grain``
+ :param engine: the engine spec's ``engine``, to check per-engine overrides
+ """
+ if not grain:
+ return None
+
+ # An operator-declared grain carries whatever duration string they typed,
+ # and `TIME_GRAIN_ADDON_EXPRESSIONS` can redefine a *built-in* grain's SQL
+ # per engine -- `P1D` could be anything at all. Neither has a width we can
+ # claim to know, so both fall back to not mirroring.
+ if grain in app.config["TIME_GRAIN_ADDONS"]:
+ return None
+ if grain in app.config["TIME_GRAIN_ADDON_EXPRESSIONS"].get(engine, {}):
+ return None
+
+ return GRAIN_BUCKET_WIDTHS.get(grain)
+
+
+@dataclass(frozen=True)
+class PartitionMapping:
+ """A resolved, usable partition filter mapping."""
+
+ partition_column: str
+ mapped_column: str
+ value_transform: str
+ is_monotonic: bool
+ #: Whether the engine compares the mapped column the way ``T`` was written
+ #: against. Resolved once where the column and the engine are both in hand,
+ #: rather than re-derived at each `mirrors` call.
+ equality_is_safe: bool = True
+
+ def mirrors(self, operator: FilterOperator) -> bool:
+ return operator in mirrorable_operators(
+ self.is_monotonic, equality_is_safe=self.equality_is_safe
+ )
+
+
+def contains_value_placeholder(transform: str | None) -> bool:
+ """Whether the transform contains the ``:value`` placeholder."""
+ return bool(transform) and VALUE_PLACEHOLDER_RE.search(transform or "") is not None
+
+
+def contains_executable_comment(transform: str | None) -> bool:
+ """Whether the transform carries a MySQL/MariaDB executable comment.
+
+ See `EXECUTABLE_COMMENT_RE`. Answered on raw text, like
+ `contains_jinja` and for the same reason: the whole point is that no
+ parser this module can reach reports the construct at all.
+ """
+ return bool(transform) and EXECUTABLE_COMMENT_RE.search(transform or "") is not None
+
+
+def contains_unicode_escaped_identifier(transform: str | None) -> bool:
+ """Whether the transform names something through a ``U&"..."`` escape.
+
+ See `UNICODE_ESCAPED_IDENTIFIER_RE`. Answered on raw text for the same
+ reason as the comment above: the parse reports a name the engine does not
+ use, which is exactly what makes the denylist blind to it.
+ """
+ return (
+ bool(transform)
+ and UNICODE_ESCAPED_IDENTIFIER_RE.search(transform or "") is not None
+ )
+
+
+#: Sequence pseudo-columns, which advance a sequence when they are *read*.
+#:
+#: ``orders_seq.NEXTVAL`` parses as a qualified column reference, not a
+#: function call, so neither `SQLStatement.is_mutating` -- which walks function
+#: names -- nor the function denylist can see it. The probe would then run
+#: ``SELECT orders_seq.NEXTVAL + 1 FROM DUAL`` and advance the sequence, again
+#: on every cache expiry, for a dataset editor holding neither SQL Lab nor a
+#: DML grant. Reading one is a write however the parser classifies it.
+#:
+#: The function spelling (``nextval('s')`` on PostgreSQL) is a different shape
+#: and is caught as a function; this is only about the suffix form.
+SEQUENCE_PSEUDO_COLUMNS = frozenset({"nextval", "currval"})
+
+#: The same thing written as a call.
+#:
+#: Only the suffix form parses as a column; `nextval('s')` on PostgreSQL and
+#: DuckDB, `NEXTVAL(s)`/`SETVAL(s, 1)` on MySQL and MariaDB, and SQL Server's
+#: `NEXT VALUE FOR s` all parse as functions. `SQLStatement.is_mutating` walks
+#: function names on PostgreSQL alone -- deliberately, since the same names are
+#: read-only elsewhere -- so every other engine let these through.
+#:
+#: Matched on the name whatever the engine, because advancing a sequence is a
+#: write wherever it happens and a transform has no reason to call one.
+SEQUENCE_FUNCTIONS = frozenset(
+ {"nextval", "setval", "next_value_for", "nextvalfor", "prevval", "lastval"}
+)
+
+
+def references_sequence(statement: SQLStatement) -> bool:
+ """Whether the statement reads or advances a sequence.
+
+ Both spellings: the pseudo-column suffix, which parses as a column (see
+ `SEQUENCE_PSEUDO_COLUMNS`), and the call, which parses as a function (see
+ `SEQUENCE_FUNCTIONS`).
+
+ Answered on the parse rather than on raw text, because position is what
+ makes it the construct: a column or alias merely *called* ``nextval`` is
+ an ordinary column, and a string literal holding the word is text.
+ """
+ return bool(
+ statement.get_column_names() & SEQUENCE_PSEUDO_COLUMNS
+ or statement.get_disallowed_functions(set(SEQUENCE_FUNCTIONS))
+ )
+
+
+def contains_jinja(transform: str | None) -> bool:
+ """
+ Whether the transform contains a balanced Jinja block.
+
+ A block is an opening delimiter followed, anywhere later, by its closing
+ one -- the same thing ``{{.*?}}`` and its two siblings match under
+ ``re.DOTALL``. Scanned with `str.find` rather than that pattern, because a
+ lazy match retried from every opening delimiter is quadratic in a run of
+ them, and this runs on stored transforms with no length bound of its own:
+ `is_transform_active` reads whatever the column holds. The earliest opening
+ delimiter is the only one worth trying, since any closing delimiter after a
+ later one is also after it.
+ """
+ if not transform:
+ return False
+ for opening, closing in JINJA_BLOCK_DELIMITERS:
+ start = transform.find(opening)
+ if start != -1 and transform.find(closing, start + len(opening)) != -1:
+ return True
+ return False
+
+
+def parse_skeleton(transform: str, standin: str = _PARSE_STANDIN) -> str:
+ """
+ The transform with ``:value`` substituted out, ready for a SQL parser.
+
+ ``sanitize_clause`` / sqlglot choke on a bare ``:value`` on most dialects,
+ so the placeholder is swapped for a benign literal first -- the same trick
+ ``validate_stored_expression`` uses for Jinja blocks.
+
+ :param standin: what to substitute. `placeholder_is_executable` passes
+ `_PLACEHOLDER_STANDIN` to find out where the placeholder landed.
+ """
+ # Substituted through a function so `standin` is taken literally. As a
+ # replacement *string* `re.sub` would read backslashes in it as escapes,
+ # and `build_probe_sql` passes rendered SQL here: a filter value containing
+ # `\n` would probe a newline instead of the two characters the predicate
+ # compares, and one containing `\1` would raise outright.
+ return VALUE_PLACEHOLDER_RE.sub(lambda _: standin, transform)
+
+
+#: Prefix the transform is wrapped in before parsing. Its length is subtracted
+#: from any reported column so positions refer to what the owner actually typed.
+_SELECT_PREFIX = "SELECT "
+
+
+def _parse_skeleton(
+ transform: str, engine: str, standin: str = _PARSE_STANDIN
+) -> SQLStatement | None:
+ """
+ Parse ``SELECT <transform>`` with the placeholder substituted out.
+
+ Returns ``None`` when the transform does not parse.
+ """
+ try:
+ return SQLStatement(
+ f"{_SELECT_PREFIX}{parse_skeleton(transform, standin)}", engine
+ )
+ except SupersetParseError:
+ return None
+
+
+def parse_error_detail(transform: str, engine: str) -> str | None:
+ """
+ Where the parser gave up on the transform.
+
+ Returns ``None`` when it parses, or when the parser offered no position.
+ Note that sqlglot parses unknown functions happily -- a misspelled function
+ name is not a parse error, it is an engine error, and surfaces only when the
+ transform is evaluated.
+
+ The parser's own ``highlight`` is deliberately dropped: it would name the
+ ``NULL`` we substituted for ``:value``, which is not a token the owner typed.
+ """
+ try:
+ SQLStatement(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError as ex:
+ column = (ex.error.extra or {}).get("column")
+ if not isinstance(column, int):
+ return None
+ return str(
+ _(
+ "syntax error at position %(position)d.",
+ position=_position_in_transform(transform, column),
+ )
+ )
+ return None
+
+
+def _position_in_transform(transform: str, parsed_column: int) -> int:
+ """
+ Map a column in the parsed skeleton back to the transform as typed.
+
+ Two substitutions stand between them: the ``SELECT`` prefix, and every
+ ``:value`` that became a shorter ``NULL``. Without unwinding both, a
+ reported position drifts left by two characters per placeholder ahead of it
+ -- which is worst exactly where transforms usually break, at the end.
+ """
+ position = max(parsed_column - len(_SELECT_PREFIX), 0)
+ shift = len(":value") - len(_PARSE_STANDIN)
+ preceding = sum(
+ 1
+ for index, match in enumerate(VALUE_PLACEHOLDER_RE.finditer(transform))
+ if match.start() - index * shift < position
+ )
+ return position + preceding * shift
+
+
+def placeholder_is_executable(transform: str | None, engine: str) -> bool:
+ """
+ Whether every ``:value`` sits where the engine will evaluate it.
+
+ `contains_value_placeholder` is a regex over raw text, and `parse_skeleton`
+ substitutes before parsing, so neither notices a placeholder that is not in
+ an executable position. Two shapes reach the probe that way, and both are
+ worse than the inactive mapping a malformed transform earns:
+
+ ``':value'`` -- the placeholder inside a string literal. `build_probe_sql`
+ binds it anyway, because SQLAlchemy's own ``text()`` scan is no more
+ literal-aware than the regex, and the dialect then renders the bind
+ *including its own quotes* in the middle of the owner's quotes. A value of
+ ``" || (SELECT secret FROM vault LIMIT 1) || "`` closes the literal and
+ compiles to a working sub-query -- the very read primitive
+ `stored_expression_error` refuses when it is written openly.
+
+ ``1 -- :value`` -- the placeholder inside a comment. The probe's selections
+ are joined on one line, so the comment swallows its own ``AS v0`` alias and
+ everything after it; a single-value probe still returns one column, the
+ constant is accepted as the transform's result, and the mirror then emits
+ ``partition_col = <constant>`` for every filter value. That is wrong rows,
+ not lost pruning.
+
+ Answered structurally: substitute an identifier rather than a keyword and
+ count the column references it produced. A literal holds no column
+ reference and a comment is not parsed at all, so either case comes back
+ short of the number of placeholders the owner wrote.
+
+ Which is why a transform naming the stand-in itself is refused outright. The
+ count is the whole gate, and a hand-written occurrence pays the difference:
+ ``concat(superset_pfm_value_standin, ':value')`` has one placeholder, inside
+ a literal that contributes nothing, and one bare reference the owner wrote --
+ so the counts match and the gate passes a placeholder the engine will never
+ evaluate. The probe then renders the bound value inside the owner's quotes,
+ where a value closing the literal can alias a column of any table the
+ connection can read into the stand-in's name and have the probe hand it back
+ through the preview. There is no legitimate transform naming this identifier,
+ so refusing it costs nothing and makes the count mean what it claims.
+ """
+ if not transform:
+ return False
+ if _PLACEHOLDER_STANDIN in transform.lower():
+ # Lowercased on both sides because `count_bare_column_references` is
+ # case-insensitive too: a dialect may normalize an unquoted identifier,
+ # so `SUPERSET_PFM_VALUE_STANDIN` would otherwise balance the count
+ # while slipping past a case-sensitive check here.
+ return False
+ expected = len(VALUE_PLACEHOLDER_RE.findall(transform))
+ if not expected:
+ return False
+ statement = _parse_skeleton(transform, engine, _PLACEHOLDER_STANDIN)
+ if statement is None:
+ return False
+ return statement.count_bare_column_references(_PLACEHOLDER_STANDIN) == expected
+
+
+def is_parseable(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform parses as a single select expression.
+
+ "Single" is the load-bearing word. `SELECT lower(:value), 'x'` parses just
+ as happily as `SELECT lower(:value)`, but it returns two columns per input
+ value, and the probe reads one column per input -- so an `IN` filter would
+ get a predicate built from the wrong halves of the wrong rows. Rejecting the
+ list here is what lets the probe trust its own column count.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return statement is not None and statement.count_select_expressions() == 1
+
+
+def is_bare_expression(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is a scalar expression and nothing more.
+
+ `is_parseable` is not enough, because it counts only the projection.
+ ``secret || :value FROM vault`` holds exactly one select expression, so it
+ parses as "a single expression" -- and `build_probe_sql` then emits
+ ``SELECT secret || 'us' AS v0``, where its own alias is read as a table
+ alias on the FROM clause the transform smuggled in. The probe reads a
+ column the owner was never granted and hands it back through the predicate
+ the preview panel renders.
+
+ A transform is a scalar function of ``:value`` by definition -- the whole
+ feature rests on ``partition_col = T(mapped_col)``, which only type-checks
+ for scalar ``T`` -- so there is no legitimate transform with a clause of
+ its own, and none with a sub-query either.
+ """
+ if not transform or not transform.strip():
+ return False
+ statement = _parse_skeleton(transform, engine)
+ return (
+ statement is not None
+ and statement.is_bare_select_expression()
+ and not statement.has_subquery()
+ )
+
+
+def is_unfinished(transform: str | None, engine: str) -> bool:
+ """
+ Whether the transform is not SQL yet, as opposed to the wrong SQL.
+
+ The distinction matters because the two deserve opposite treatment. A
+ half-typed ``unix_timestamp(:value`` is what a text input produces on the
+ way to something valid: a PUT stores it and reports the mapping inactive,
+ so discarding it would mean an export could not round-trip the dataset it
+ came from. ``unix_timestamp(:value); DROP TABLE t`` is not on the way to
+ anything, and has to be refused wherever it is offered.
+
+ Both fail `is_parseable`, and both fail to parse as a single *statement* --
+ so neither of those tells them apart. Parsing as a *script* does: the
+ multi-statement form is two valid statements, while unfinished text is no
+ statement at all.
+ """
+ if not transform or not transform.strip():
+ return False
+ try:
+ SQLScript(f"{_SELECT_PREFIX}{parse_skeleton(transform)}", engine)
+ except SupersetParseError:
+ return True
+ return False
+
+
+def find_non_deterministic_functions(transform: str, engine: str) -> set[str]:
+ """
+ Names of non-deterministic functions the transform calls.
+
+ ``UNIX_TIMESTAMP`` is only reported in its zero-argument form, which means
+ "now" on Hive and Impala; the one-argument form is the canonical temporal
+ transform and stays allowed.
+
+ Three spellings have to be looked for, because one name reaches the parse
+ three ways: as a function call, as a zero-argument call a dialect resolves
+ itself, and -- for the datetime keywords -- as a bare word that parses as a
+ column reference.
+ """
+ statement = _parse_skeleton(transform, engine)
+ if statement is None:
+ return set()
+
+ found = {
+ name
+ for name in NON_DETERMINISTIC_FUNCTIONS
+ if statement.check_functions_present({name})
+ }
+ # The parenthesis-free spellings, which parse as columns rather than
+ # functions and so are invisible to the walk above. See
+ # `BARE_WALL_CLOCK_KEYWORDS`.
+ found |= {
+ name.upper() for name in BARE_WALL_CLOCK_KEYWORDS & statement.get_column_names()
+ }
+ return found | _find_niladic_calls(statement)
+
+
+def _find_niladic_calls(statement: SQLStatement) -> set[str]:
+ """
+ Names from ``NON_DETERMINISTIC_WHEN_NILADIC`` called with no arguments.
+
+ Note some dialects resolve the zero-argument form themselves -- Hive parses
+ ``unix_timestamp()`` straight to ``CURRENT_TIMESTAMP`` -- in which case the
+ name-based check above has already caught it. This is the backstop for the
+ dialects that do not.
+ """
+ return NON_DETERMINISTIC_WHEN_NILADIC & statement.get_niladic_functions()
+
+
+def resolve_partition_mapping(datasource: SqlaTable) -> PartitionMapping | None:
+ """
+ Resolve the dataset's mapping, or ``None`` when nothing may be mirrored.
+
+ Every bail-out here is defensive as well as functional: save-time validation
+ rejects most of these, but rows predating the validation can still violate
+ the invariants, and a column sync can invalidate a mapping that was fine
+ when it was written.
+
+ The transform gate is `is_transform_active`, the same function the Explore
+ indicator reads, which is `validate_transform` with the messages discarded.
+ Anything narrower here would be a second, weaker statement of the same rule:
+ a transform calling `now()` that reached storage without passing
+ `UpdateDatasetCommand` -- through import, or through a bundle written by hand
+ -- would be reported inactive by the editor and still mirrored by this
+ function, freezing a snapshot of probe time into the predicate with nothing
+ on screen to say so.
+ """
+ if not feature_flag_manager.is_feature_enabled(FEATURE_FLAG):
+ return None
+
+ partition_column = getattr(datasource, "partition_column", None)
+ if not partition_column:
+ return None
+
+ columns_by_name = {column.column_name: column for column in datasource.columns}
+ if partition_column not in columns_by_name:
+ # The partition column was dropped by a column sync or at the source.
+ return None
+
+ mapped_column_name = (
+ getattr(datasource, "partition_mapped_column", None) or datasource.main_dttm_col
+ )
+ if not mapped_column_name or mapped_column_name not in columns_by_name:
+ return None
+
+ if mapped_column_name == partition_column:
+ # Self-mapping: the mirrored predicate would duplicate the original.
+ return None
+
+ # An array holds no scalar a transform could return, so no mirror onto it
+ # can ever compare. Refused for the mapping rather than only per value, so
+ # the Explore glyph stops promising one: a probe of ``:value`` succeeds and
+ # records a working transform, and only the later type gate declined.
+ if declares_array_type(columns_by_name[partition_column].type):
+ return None
+
+ mapped_column = columns_by_name[mapped_column_name]
+ transform = getattr(mapped_column, "partition_value_transform", None)
+ if not is_transform_active(transform, datasource.database.backend):
+ return None
+
+ if has_active_advanced_data_type(mapped_column):
+ # `translate_filter` builds its own predicate shape from *translated*
+ # values, so the `(operator, value)` pair the operator matrix reasons
+ # about does not exist and mirroring would apply the wrong values.
+ return None
+
+ return PartitionMapping(
+ partition_column=str(partition_column),
+ mapped_column=str(mapped_column_name),
+ value_transform=cast(str, transform),
+ is_monotonic=bool(
+ getattr(mapped_column, "partition_transform_is_monotonic", False)
+ ),
+ equality_is_safe=equality_mirrors_safely(
+ mapped_column, datasource.database.db_engine_spec
+ ),
+ )
+
+
+def has_active_advanced_data_type(column: TableColumn) -> bool:
+ """
+ Whether the column's advanced data type is configured and switched on.
+
+ Such a column is never mirrored: ``translate_filter`` builds its own
+ predicate shape from translated values, so the ``(operator, value)`` pair
+ the operator matrix reasons about does not exist.
+ """
+ advanced_data_type = getattr(column, "advanced_data_type", None)
+ if not advanced_data_type:
+ return False
+ if not feature_flag_manager.is_feature_enabled("ENABLE_ADVANCED_DATA_TYPES"):
+ return False
+ return advanced_data_type in app.config.get("ADVANCED_DATA_TYPES", {})
+
+
+def _denylist_engine_key(database: "Database") -> str:
+ """
+ The name ``DISALLOWED_SQL_*`` is keyed by for this database.
+
+ The engine spec's own ``engine`` first, because that is what every other
+ denylist gate uses (`_raise_for_disallowed_sql`, `sql_lab`) and what an
+ operator writing the config reads in the documentation; a spec covering
+ several SQLAlchemy backends through ``engine_aliases`` reports the one
+ canonical name under which its entry is written.
+
+ Falling back to the URL's backend, because resolving the spec loads the
+ SQLAlchemy dialect entrypoint, which imports the driver package. On a
+ deployment missing an optional driver that raises rather than merely being
+ absent, asking for the spec here would turn a dataset import into a hard
+ failure -- and for every engine without aliases the two names are the same
+ string anyway.
+ """
+ try:
+ return database.db_engine_spec.engine
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return database.backend
+
+
+def stored_expression_error( # noqa: C901
+ database: "Database",
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+) -> str | None:
+ """
+ Why this transform may not be stored or run, if there is a reason.
+
+ Stricter than the policy a general stored expression goes through, because
+ a value transform is a narrower thing: `build_probe_sql` binds only
+ `:value` and splices the rest of the transform in as SQL text, which the
+ engine then executes, so an ungated transform is arbitrary SQL. A dataset
+ editor without SQL Lab could store `(SELECT secret FROM protected_table
+ LIMIT 1) || :value`, or `secret || :value FROM protected_table`, and read
+ the answer back out of the emitted predicate the preview panel renders.
+
+ So the transform must be a bare scalar expression: no clause of its own and
+ no sub-query, whatever `ALLOW_ADHOC_SUBQUERY` says. That is not a
+ restriction the feature pays for -- it rests on
+ ``partition_col = T(mapped_col)``, which only type-checks for scalar ``T``
+ -- and it is what makes the table denylist and the RLS rewrite moot here,
+ since neither has a table reference left to govern.
+
+ And it must be a *read*. Shape is a separate question from effect: a bare
+ scalar expression can still write, so `SQLStatement.is_mutating` is asked
+ too -- the same question SQL Lab and the chart executor ask before letting
+ SQL run. See the gate itself for what that reaches and what it does not.
+
+ Returns the engine-agnostic reason as a string rather than raising,
+ because its four callers disagree about what to do with it: the preview
+ reports it at the field, a PUT and the legacy datasource save refuse the
+ write, the importer drops the transform and keeps the dataset, and the
+ probe simply declines to run. Raising would make three of those four
+ write a `try` around a question.
+
+ Imported inside the function rather than at module scope:
+ `connectors.sqla.models` imports this module, so the dependency only runs
+ one way at import time.
+ """
+ from superset.connectors.sqla.models import ( # pylint: disable=import-outside-toplevel,cyclic-import
+ validate_stored_expression,
+ )
+
+ # Ahead of the parse, both because it is the cheaper question and because
+ # the parse is the cost the bound exists to contain.
+ if len(transform) > MAX_TRANSFORM_LENGTH:
+ return str(
+ _(
+ "A partition value transform cannot be longer than "
+ "%(limit)d characters.",
+ limit=MAX_TRANSFORM_LENGTH,
+ )
+ )
+
+ # Also ahead of the parse, and for a stronger reason than cost: every gate
+ # below reasons about the parse tree, and this is the one construct that
+ # makes the parse tree describe a different statement from the one the
+ # engine runs. Checked here as well as in `validate_transform` because this
+ # is the door a row written by an earlier release still comes through.
+ if contains_executable_comment(transform):
+ return str(
+ _(
+ "A partition value transform cannot contain a MySQL "
+ "executable comment, which the database executes and every "
+ "validator reads as a comment."
+ )
+ )
+
+ if contains_unicode_escaped_identifier(transform):
+ return str(
+ _(
+ "A partition value transform cannot name anything through a "
+ 'U&"..." escape sequence, which the database decodes and '
+ "every validator reads literally."
+ )
+ )
+
+ # Same door, same reason: the name the denylist below would match is not
+ # the name the engine resolves. See `UNICODE_ESCAPED_IDENTIFIER_RE`.
+ statement = _parse_skeleton(transform, database.backend)
+ if statement is None:
+ return str(
+ _("A partition value transform must parse as a single SQL expression.")
+ )
+
+ # The shape gate again, even though `validate_transform` blocks the same
+ # thing at save time. This is the last door before the transform becomes SQL
+ # an engine runs, and the only door a row written by an earlier release --
+ # or by an importer that ran with the feature flag off -- still passes
+ # through.
+ if not statement.is_bare_select_expression():
+ return str(
+ _(
+ "A partition value transform must be a single SQL expression, "
+ "with no FROM, WHERE or other clause."
+ )
+ )
+
+ # Unconditionally, not under `ALLOW_ADHOC_SUBQUERY`. A transform is a scalar
+ # function of `:value`, so a sub-query in one has no legitimate use, and it
+ # is a read primitive whose answer the preview panel renders back to its
+ # caller. Refusing it is also what lets this function skip the table
+ # denylist and the row-level-security rewrite: with no FROM clause and no
+ # sub-query there is no table reference for either to govern.
+ if statement.has_subquery():
+ return str(_("A partition value transform cannot contain a sub-query."))
+
+ # The read-only gate, which nothing above implies. The shape gates ask what
+ # the transform *selects*; this asks what evaluating it *does*, and a bare
+ # scalar expression can still write. `nextval(:value)` on PostgreSQL
+ # advances a sequence: one function call, no clause, no sub-query, and not
+ # in the default `DISALLOWED_SQL_FUNCTIONS` either -- so every gate above
+ # passes it and the probe then runs it. `setval` is the same shape, and
+ # `exp.Execute` and the opaque-`exp.Command` forms arrive the same way.
+ #
+ # The large-object writers (`lo_export`, `lowrite`, `lo_from_bytea`, ...)
+ # are caught here too, and the shipped denylist happens to name them as
+ # well -- but that is config an operator can replace, while this is not.
+ #
+ # `is_mutating` is the same question SQL Lab, `get_virtual_table_metadata`
+ # and the chart executor ask before letting SQL run, so a transform is held
+ # to the bar the rest of Superset already sets rather than to one invented
+ # here. Unconditional rather than gated on `Database.allow_dml`: a transform
+ # is a scalar function of `:value` by definition, so there is no legitimate
+ # mutating one, and the probe runs on a cache schedule nobody chose -- a
+ # write would repeat every time the entry expired.
+ #
+ # It bears saying what this does not reach. A user-defined function whose
+ # body writes is a plain call no parser can tell from `lower(:value)`, and
+ # `is_mutating`'s function-name walk is PostgreSQL-only by design, since the
+ # same names are read-only elsewhere. Neither residual is specific to this
+ # feature -- a dataset editor can already have the engine evaluate an
+ # arbitrary expression through a calculated column or a virtual dataset's
+ # SQL -- and closing them means authorizing the preview against the
+ # database, not parsing harder.
+ if statement.is_mutating():
+ return str(
+ _(
+ "A partition value transform cannot change data. It is "
+ "evaluated against the database to check that it mirrors, so "
+ "it has to be a read."
+ )
+ )
+
+ # Not reached by the walk above, which is why it is its own gate: a
+ # sequence pseudo-column is a *column* to the parser and a write to the
+ # engine. See `SEQUENCE_PSEUDO_COLUMNS`.
+ if references_sequence(statement):
+ return str(
+ _(
+ "A partition value transform cannot read a sequence. "
+ "NEXTVAL advances the sequence every time it is evaluated, "
+ "and the transform is evaluated on a cache schedule."
+ )
+ )
+
+ # The shape gates above read the transform with `:value` replaced by the
+ # `NULL` keyword, which leaves no trace of where the placeholder was -- so
+ # none of them can see a placeholder that is not in an executable position.
+ # Checked here as well as in `validate_transform` because this is the door
+ # a row written by an earlier release still passes through, and because
+ # the escape only completes once a filter value is bound.
+ #
+ # Guarded on the placeholder being present at all: a transform without one
+ # is inert rather than refused (`validate_transform` reports it as Tier 2),
+ # and refusing it here would make this gate stricter than the PUT's.
+ if contains_value_placeholder(transform) and not placeholder_is_executable(
+ transform, database.backend
+ ):
+ return str(
+ _(
+ "A partition value transform must use the :value placeholder "
+ "where the engine will evaluate it, not inside a string "
+ "literal or a comment."
+ )
+ )
+
+ denied = app.config["DISALLOWED_SQL_FUNCTIONS"].get(
+ _denylist_engine_key(database), set()
+ )
+ if denied and (found := statement.get_disallowed_functions(denied)):
+ return str(
+ _(
+ "A partition value transform cannot call %(functions)s.",
+ functions=", ".join(sorted(found)),
+ )
+ )
+
+ # Kept as the tail call rather than replaced: this is where `sanitize_clause`
+ # runs. Its own sub-query branch returns rewritten, RLS-injected SQL that
+ # this function has no way to propagate -- but that branch is unreachable
+ # from here now, because a transform containing a sub-query was refused
+ # above, so discarding the return value is correct rather than a leak.
+ try:
+ validate_stored_expression(database, catalog, schema, parse_skeleton(transform))
+ except SupersetSecurityException as ex:
+ return str(ex.error.message)
+ except QueryClauseValidationException as ex:
+ return str(ex.message)
+ return None
+
+
+@dataclass(frozen=True)
+class RawProbeValue:
+ """
+ A probe value that is already SQL text rather than a bindable scalar.
+
+ Almost every filter value is a Python scalar, which `build_probe_sql` binds
+ and lets the dialect render. An array column's value is not: the predicate
+ it mirrors compares an engine array literal -- ``array('a', 'b')`` on
+ ClickHouse -- which `BaseEngineSpec.array_literal` returns as a SQLAlchemy
+ expression, and an expression cannot be the value of a bind parameter.
+
+ Frozen, and holding text rather than the expression, for two reasons
+ besides immutability: `_probe_cache_key` keys on ``repr`` of each value, and
+ an expression's ``repr`` carries its memory address -- so caching the probe
+ would key every call differently. `_hashable` needs it hashable too.
+
+ Build one with `raw_probe_value`, which renders the expression through the
+ same literal compilation the bound path uses.
+ """
+
+ sql: str
+
+
+def raw_probe_value(database: "Database", element: Any) -> RawProbeValue:
+ """
+ Freeze an engine-built expression into probe-ready SQL text.
+
+ The text is produced entirely by SQLAlchemy and the engine spec from values
+ that have already been coerced, so no caller-supplied text reaches the
+ probe uninspected. Rendering is not what makes that true: a string element
+ is checked by `literal_round_trips` before it is rendered -- the dialect's
+ literal processor and the engine's lexer do not always agree about what a
+ rendered literal says -- and `probe_sql_is_evaluable` re-reads the finished
+ query, which is what bounds the splice.
+
+ :param database: the database whose dialect renders the literal
+ :param element: a SQLAlchemy expression, e.g. from ``array_literal``
+ :return: the rendered expression, ready to stand in for ``:value``
+ """
+ return RawProbeValue(_compile_literal(element, _dialect_for(database)))
+
+
+def normalize_mixed_numbers(values: Sequence[Any]) -> list[Any]:
+ """
+ One numeric type across ``values``, so a bind cannot be inferred wrongly.
+
+ SQLAlchemy infers an ``IN`` bind's type from the first element it is given.
+ A list mixing an int with a float therefore binds as integer and truncates
+ every later float: ``[33, 29.02]`` emits ``IN (33, 29)`` and drops the row
+ matching ``29.02``.
+
+ Applied on both sides of the probe, which is why it lives here rather than
+ inline at either: the filter values collected for mirroring have to match
+ the ones the real predicate binds (see #33206), and the probe *results*
+ bound against the partition column have the same problem one step later.
+
+ Leaves the list alone when nothing in it is a float, so an exact integer
+ key above 2^53 is not rounded for no reason.
+
+ :param values: the values about to be bound
+ :return: the values, with every number widened to ``float`` if any was
+ """
+ if not any(isinstance(value, float) for value in values):
+ return list(values)
+ return [
+ float(value) if isinstance(value, (int, float)) else value for value in values
+ ]
+
+
+def _placeholder_is_bindable(transform: str) -> bool:
+ """
+ Whether SQLAlchemy's ``text()`` can see ``:value`` as a bound parameter.
+
+ `VALUE_PLACEHOLDER_RE` is ``:value\b``, which matches the placeholder in a
+ Postgres cast such as ``:value::bigint``. SQLAlchemy's own bind scan is
+ ``(?<![:\\w$]):([\\w$]+)(?![:\\w$])`` -- note the trailing exclusion -- so a
+ following colon stops it: ``text(":value::bigint")`` reports a parameter
+ named ``valu``, and ``.bindparams(bindparam("value"))`` then raises
+ ``ArgumentError``.
+
+ `_probe` swallows that, so the only symptom was a perfectly valid transform
+ whose mapping silently never pruned, and a preview reporting an engine
+ failure for SQL that was never sent. Every write-side gate passes the
+ transform: it parses, it is a bare expression, and the placeholder *is* in
+ an executable position.
+
+ Answered by attempting the bind itself rather than by pattern-matching
+ ``::`` or reading ``text()``'s private parameter map, so this cannot
+ disagree with what `build_probe_sql` is about to do -- on any dialect, or on
+ a SQLAlchemy whose scan changes.
+ """
+ try:
+ sa.text(transform).bindparams(sa.bindparam("value", value=None))
+ except Exception: # pylint: disable=broad-except # noqa: BLE001
+ return False
+ return True
+
+
+def escape_foreign_colons(transform: str) -> str:
+ """
+ ``transform`` with every colon but the ``:value`` placeholder escaped.
+
+ `sqlalchemy.text` reads any ``:word`` as a bind parameter, including one
+ inside a string literal, and an unbound parameter renders as ``NULL``
+ under literal binds rather than raising. So ``:value || \':suffix\'``
+ compiled to ``'us' || 'NULL'``: the mirror asked for a partition value no
+ row holds and the chart dropped rows, with no error for `_probe` to
+ swallow and nothing on screen to say so.
+
+ Escaped rather than refused, because a colon in a literal is ordinary --
+ ``concat(:value, \':\', region)`` builds a composite key -- and the
+ placeholder is the only colon this module means to interpret. `text()`
+ reads ``\\:`` as a literal colon.
+
+ Only the bound path needs this. A `RawProbeValue` or an unbindable
+ placeholder is substituted as text by `parse_skeleton`, which never hands
+ the transform to `text()` at all.
+ """
+ pieces: list[str] = []
+ cursor = 0
+ for match in VALUE_PLACEHOLDER_RE.finditer(transform):
+ pieces.append(transform[cursor : match.start()].replace(":", r"\:"))
+ pieces.append(match.group(0))
+ cursor = match.end()
+ pieces.append(transform[cursor:].replace(":", r"\:"))
+ return "".join(pieces)
+
+
+def literal_round_trips(value: Any, dialect: Dialect | None, engine: str) -> bool:
+ """
+ Whether the engine reads a rendered ``value`` back as that same value.
+
+ The probe runs with no bound parameters, so every value reaches the engine
+ as literal text the driver wrote (see `build_probe_sql`). Whether that text
+ says what the value says is a question about two independent spellings: the
+ driver's escaping, and the engine's lexer. SQLAlchemy's default renderer
+ doubles apostrophes and passes backslashes through; Hive and Spark honour
+ the backslash and not the doubling, so ``'O''Brien'`` is read there as two
+ adjacent literals -- the transform is evaluated at ``OBrien``, and the
+ mirror asks for a partition key that holds none of the rows the filter
+ keeps. The same gap in the other direction lets a value close its own quote
+ and have the rest of it read as SQL.
+
+ Escaping is not the repair. Whether a backslash introduces an escape is a
+ per-session server setting -- ``standard_conforming_strings`` on Postgres,
+ ``NO_BACKSLASH_ESCAPES`` on MySQL, ``escapedStringLiterals`` on Spark -- and
+ nothing in the engine specs exposes it. SQLAlchemy reads it off the server
+ into ``_backslash_escapes`` during ``initialize(connection)``, which the
+ probe's dialect never reaches: `_dialect_for` asks the ``Database`` for a
+ dialect, not for a connection, so Postgres renders ``a\\b`` as
+ ``'a\\\\b'`` and a server with the standard setting reads four
+ characters. An engine-spec flag would have to be defaulted, and either
+ default is wrong for a dozen engines: one leaves the hole open, the other
+ corrupts the probed value.
+
+ So the premise is verified rather than declared, the way
+ `probe_sql_is_evaluable` verifies the finished statement. A value that does
+ not survive the round trip is not mirrored, which costs the query its
+ pruning and nothing else.
+
+ The short-circuit is a proof, not a guess, and it matters for cost: a
+ 200-member ``IN`` list would otherwise parse 200 times on the chart path.
+ If the renderer emitted the value between two quotes and changed nothing in
+ it, and the value carries neither a quote nor a backslash, then no lexer in
+ play can read it as anything but itself. Both exclusions are load-bearing:
+ on Hive ``a\\b`` renders verbatim and reads as ``a`` followed by a
+ backspace.
+
+ :param value: a filter value about to be rendered into the probe
+ :param dialect: the dialect that will render it, as `_dialect_for` reports
+ :param engine: ``database.backend``, whose lexer reads the result
+ :return: whether the two agree about what the literal says
+ """
+ if isinstance(value, RawProbeValue):
+ # Already SQL, with no single value for a parse to be compared against:
+ # its elements are checked before they are rendered, by
+ # `ExploreMixin._array_mirror_probe_value`. A backslash surviving into
+ # the finished text is refused here all the same, as the backstop for a
+ # renderer this module does not own.
+ return "\\" not in value.sql
+ if not isinstance(value, str):
+ # Numbers and instants are not written between delimiters, so there is
+ # no escaping for the two sides to disagree about.
+ return True
+
+ rendered = _compile_literal(sa.literal(value), dialect)
+ if rendered == f"'{value}'" and "'" not in value and "\\" not in value:
+ return True
+
+ try:
+ return (
+ SQLStatement(f"SELECT {rendered}", engine).get_select_literal_value()
+ == value
+ )
+ except SupersetParseError:
+ # A rendered literal the engine's own dialect will not parse is the
+ # strongest form of disagreement there is.
+ return False
+
+
+def value_round_trips(database: Database, value: Any) -> bool:
+ """
+ `literal_round_trips` for a caller holding a database, not a dialect.
+
+ Which renderer and which lexer apply is this module's business, so the two
+ callers outside it -- the chart path's own gate in
+ `ExploreMixin.mirror_probe_request` and the mapping summary Explore reads
+ -- ask in these terms and stay out of it.
+
+ :param database: the database whose driver renders and whose engine reads
+ :param value: a filter value about to be rendered into the probe
+ :return: whether the two agree about what the literal says
+ """
+ return literal_round_trips(value, _dialect_for(database), database.backend)
+
+
+def build_probe_sql(
+ transform: str,
+ values: list[Any],
+ dialect: Dialect | None = None,
+ from_suffix: str = "",
+) -> str:
+ """
+ Compile a single ``SELECT`` that evaluates the transform at every value.
+
+ Values are attacker-controlled (a Gamma user picks filter values), so they
+ are bound as parameters and rendered by the dialect's own literal processor
+ rather than interpolated into the SQL text. That is not itself a boundary:
+ the processor's escaping is not always the escaping the engine honours, and
+ a value can close its own quote through the gap. The boundary is
+ `literal_round_trips` on the way in -- which callers must have run, like
+ `stored_expression_error` below -- and `probe_sql_is_evaluable` on the way
+ out.
+
+ ``from_suffix`` comes from the engine spec's ``select_without_from_suffix``.
+ A ``SELECT`` with no ``FROM`` is not universal SQL: Oracle and Db2 need a
+ one-row table to select from, and without it every probe on those engines
+ raises -- which `_run_probe` swallows, so the only symptom is a correctly
+ configured mapping that silently never prunes.
+
+ Note this deliberately does *not* go through ``BaseEngineSpec``'s text
+ helper, which escapes ``:`` on every engine but Athena and would destroy the
+ ``:value`` placeholder before it can be bound.
+
+ Callers must have run `stored_expression_error` first. The ``AS v{index}``
+ alias and ``from_suffix`` are only safe on a transform with no clause of its
+ own; on one carrying its own FROM they attach to that instead.
+ """
+ bindable = _placeholder_is_bindable(transform)
+ selections = []
+ for index, value in enumerate(values):
+ if isinstance(value, RawProbeValue):
+ # Already SQL, so substituted rather than bound -- and deliberately
+ # not run through `_compile_literal`, which has nothing to compile
+ # and would undouble percent signs the owner typed on purpose.
+ rendered = parse_skeleton(transform, value.sql)
+ elif bindable:
+ # Every other colon escaped first: `text()` would read one inside a
+ # string literal as a second bind parameter and render it `NULL`.
+ # See `escape_foreign_colons`.
+ clause = sa.text(escape_foreign_colons(transform)).bindparams(
+ sa.bindparam("value", value=value)
+ )
+ rendered = _compile_literal(clause, dialect)
+ else:
+ # `text()` cannot see the placeholder (see
+ # `_placeholder_is_bindable`), so the value is rendered by the
+ # dialect's own literal processor first and substituted as SQL
+ # text. The same two steps in the other order: binding exists to
+ # get the value through that processor, and `_compile_literal`
+ # inlines the result either way, so this is the same string by a
+ # different route -- not a loosening of the "never interpolate a
+ # raw value" rule. `parse_skeleton` substitutes literally, so the
+ # rendered literal arrives here exactly as it was rendered, which
+ # is what makes `literal_round_trips`' verdict on it good for this
+ # branch as much as for the bound one.
+ rendered = parse_skeleton(
+ transform, _compile_literal(sa.literal(value), dialect)
+ )
+ selections.append(f"{rendered} AS v{index}")
+ return "SELECT " + ", ".join(selections) + from_suffix
+
+
+def probe_sql_is_evaluable(
+ sql: str,
+ engine: str,
+ expected: int,
+ from_suffix: str = "",
+) -> bool:
+ """
+ Whether the compiled probe is still the query `build_probe_sql` intended.
+
+ Every write-side gate reads the transform with ``:value`` standing in for a
+ value. The escape this guards against only completes once a *real* value is
+ rendered in its place, so it is invisible until this point -- and the values
+ are supplied by whoever is filtering a chart, not only by the owner who
+ wrote the transform.
+
+ Five things have to hold, and all five are about the probe still being
+ readable rather than about taste:
+
+ * One statement. A value that closes the expression and starts another
+ would otherwise run both.
+ * No sub-query. A placeholder inside a string literal lets a value close
+ the quote and concatenate one; `stored_expression_error` refuses a
+ sub-query written openly, and this refuses the same thing assembled.
+ * Exactly ``expected`` projections, aliased ``v0`` upward. A comment
+ swallows the rest of its line including its own alias, and the engine
+ still answers with a column -- so the count alone does not notice.
+ Checking the aliases is what makes a missing one visible.
+ * No clause this function did not build, and a ``FROM`` only where
+ ``select_without_from_suffix`` asked for one -- the engine's own, not
+ merely some table. A rendered value can close the projection and append a
+ ``FROM`` of its own without disturbing the aliases that follow it, which
+ is a read of a table the mapping has no business reading; the same value
+ could append a ``WHERE`` and nothing would notice either.
+ * No comment, anywhere. A value that closes its own quote has to hide the
+ text `build_probe_sql` appended after it, and a comment is the only way
+ to do that and still balance the quotes -- so this is what makes the
+ alias check above sufficient rather than merely necessary. Read off the
+ parse rather than the text, so a comment *inside* a literal is data and
+ costs no pruning, and so the question is asked in the engine's own
+ dialect. A transform has no legitimate reason to carry one either; see
+ `EXECUTABLE_COMMENT_RE`.
+
+ Both FROM clauses are compared as sqlglot renders them, so the suffix's own
+ spacing does not have to match what the probe emitted. Identifier case does,
+ which costs nothing: `_probe` hands the same engine constant to
+ `build_probe_sql` and to this gate.
+ """
+ # Before the parse, because this gate's whole contract is that what the
+ # parse describes is what the engine will run, and an executable comment is
+ # precisely the text where that stops being true. The transform is already
+ # refused for carrying one; this covers the compiled statement, so no later
+ # change to how values are rendered can reintroduce it behind the gates
+ # below.
+ if contains_executable_comment(sql) or contains_unicode_escaped_identifier(sql):
+ return False
+
+ try:
+ script = SQLScript(sql, engine)
+ except SupersetParseError:
+ return False
+ if len(script.statements) != 1:
+ return False
+ statement = script.statements[0]
+ if not isinstance(statement, SQLStatement):
+ # A dialect whose statements this gate cannot take apart -- KQL -- gets
+ # no probe rather than an unchecked one. It never had one: the clause
+ # inspection below is implemented for SQL statements only, and the
+ # alternative to declining here is an `AttributeError` that `_probe`
+ # swallows into the same outcome, less legibly.
+ return False
+ if statement.has_comment():
+ return False
+ if statement.has_subquery():
+ return False
+ if statement.get_clause_names() - {"from"}:
+ return False
+ if statement.get_from_clause_sql() != _from_suffix_sql(from_suffix, engine):
+ return False
+ return statement.get_select_aliases() == [f"v{index}" for index in range(expected)]
+
+
+def _from_suffix_sql(from_suffix: str, engine: str) -> str | None:
+ """
+ The engine's own ``FROM`` suffix as its parsed clause, or ``None`` for none.
+
+ Parsed rather than string-compared so that the comparison in
+ `probe_sql_is_evaluable` is between two rendered clauses. A suffix that does
+ not parse answers ``None``, which no statement carrying a FROM can match --
+ the probe then declines, which is the right way for an unreadable engine
+ constant to fail.
+ """
+ if not from_suffix.strip():
+ return None
+ try:
+ return SQLStatement(f"SELECT 1{from_suffix}", engine).get_from_clause_sql()
+ except SupersetParseError:
+ return None
+
+
+def evaluate_transform(
+ database: Database,
+ catalog: str | None,
+ schema: str | None,
+ transform: str,
+ values: list[Any],
+ *,
+ errors: list[str] | None = None,
+ text_answers: list[tuple[int, Any]] | None = None,
+) -> list[Any] | None:
+ """
+ Evaluate ``transform`` against the engine once per distinct value.
+
+ Returns one result per input value, positionally aligned with ``values``, or
+ ``None`` if anything at all goes wrong. Failing open costs pruning, never
+ correctness: the chart query still runs, it just scans more partitions.
+
+ The probe is pinned to the dataset's catalog and schema so session settings
+ match the chart query as closely as the connection pool allows. It still
+ runs in a *different* session, which is why transforms calling
+ session-dependent functions are rejected at save time.
+
+ :param errors: optional sink for the engine's own account of a failure. The
+ query path passes nothing and stays silent; the editor's preview passes
+ a list so it can tell the owner *why* the transform did not evaluate --
+ a misspelled function is the common case and sqlglot parses it happily.
+ :param text_answers: optional sink. When given, every date or timestamp in
+ ``values`` is also asked as the text a simple filter would bind, in the
+ same round trip, and ``(index, answer)`` is appended for each -- see
+ `_declined_for_reading_by_type` for why. A transform that refuses text
+ is asked again with ``values`` alone, so a refusal never costs pruning.
+ """
+ if not values:
+ return None
+
+ if text_answers is not None:
+ indexes = [
+ index
+ for index, value in enumerate(values)
+ if isinstance(value, date) and not is_unmirrorable(value)
+ ]
+ if indexes:
+ combined = evaluate_transform(
+ database,
+ catalog,
+ schema,
+ transform,
+ values + [_as_filter_text(values[index]) for index in indexes],
+ )
+ if combined is not None:
Review Comment:
{ai generated comment}
Thanks, agreed. Fixed in [09c728c5c4](https://github.com/apache/superset/pull/43870/commits/09c728c5c4): a temporal value whose text form the transform refuses now gets no mirror (the typed answer can't be checked without it). Charts still do one probe, and the preview re-asks the typed value alone to say the text form was refused. Engines that write timestamps as plain text are unaffected.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "github-advanced-security[bot] (via GitHub)" <gi...@apache.org>.
github-advanced-security[bot] commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4340504016
##########
superset-frontend/src/components/Datasource/components/DatasourceEditor/components/PartitionFilterMapping/utils.ts:
##########
@@ -0,0 +1,738 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { t } from '@apache-superset/core/translation';
+import type {
+ PartitionMappingColumn,
+ PartitionMappingDatasource,
+ PartitionMappingIssue,
+ PartitionRowState,
+} from './types';
+
+/**
+ * Jinja delimiters.
+ *
+ * A transform is evaluated in a different context and at a different time from
+ * the chart query, so a template would not render the same way -- the backend
+ * rejects one outright. Shared so the check that declines to preview a Jinja
+ * transform and the check that blocks saving it cannot drift apart.
+ */
+const JINJA_PATTERN = /\{\{|\{%|\{#/;
+
+/**
+ * The column whose filters are mirrored.
+ *
+ * `partition_mapped_column` is an explicit override; `null` means "follow the
+ * default datetime column", so re-pointing that column moves the mapping with
+ * it. Mirrors `SqlaTable.partition_filter_mapping_summary` on the backend.
+ */
+export function resolveMappedColumn(
+ datasource: PartitionMappingDatasource,
+): string | null {
+ if (!datasource.partition_column) {
+ return null;
+ }
+ return datasource.partition_mapped_column || datasource.main_dttm_col || null;
+}
+
+/** Whether the mapped column came from `main_dttm_col` rather than an override. */
+export function mappedColumnIsImplicit(
+ datasource: PartitionMappingDatasource,
+): boolean {
+ return Boolean(
+ datasource.partition_column &&
+ !datasource.partition_mapped_column &&
+ datasource.main_dttm_col,
+ );
+}
+
+/**
+ * Whether a transform is worth spending a preview request on.
+ *
+ * A necessary condition, never a sufficient one: the server stays the authority
+ * on whether a transform is usable, and anything this cannot see -- an
+ * unparseable expression, a non-deterministic function -- still comes back from
+ * it. What this catches is the cases that are knowably hopeless while the owner
+ * is still typing, which would otherwise spend the per-user preview budget and
+ * leave none for the transform they eventually finish writing.
+ */
+export function transformCanPreview(
+ transform: string | null | undefined,
+ mappedColumn?: string | null,
+ partitionColumn?: string | null,
+): boolean {
+ const trimmed = transform?.trim();
+ if (!trimmed) {
+ return false;
+ }
+ // Without the placeholder there is no value to substitute, so the transform
+ // is inert however well-formed it is.
+ if (!/:value\b/.test(trimmed)) {
+ return false;
+ }
+ // Jinja is rejected on save, so previewing it is pointless.
+ if (JINJA_PATTERN.test(trimmed)) {
+ return false;
+ }
+ // A column cannot stand in for itself; the backend rejects this outright.
+ if (mappedColumn && partitionColumn && mappedColumn === partitionColumn) {
+ return false;
+ }
+ return true;
+}
+
+/**
+ * A declared type naming an array, as the server's `declares_array_type` reads
+ * it: PostgreSQL's `TEXT[]`, and the `ARRAY<...>` / `ARRAY(...)` / `Array(...)`
+ * spellings.
+ */
+const ARRAY_TYPE_RE = /(\[\s*\d*\s*\])+\s*$|^\s*ARRAY\b/i;
Review Comment:
## CodeQL / Inefficient regular expression
This part of the regular expression may cause exponential backtracking on strings starting with '\[' and containing many repetitions of '\t\]\['.
[Show more details](https://github.com/apache/superset/security/code-scanning/3969)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] feat(datasets): partition filter mapping [superset]
Posted by "geido (via GitHub)" <gi...@apache.org>.
geido commented on code in PR #43870:
URL: https://github.com/apache/superset/pull/43870#discussion_r4363300690
##########
superset/datasets/api.py:
##########
@@ -2064,6 +2165,134 @@ def get(self, id_or_uuid: str, **kwargs: Any) -> Response:
entity_concurrency_token(SqlaTable, table.id, table.uuid),
)
+ @expose("/<int:pk>/partition_mapping/preview/", methods=("POST",))
+ @protect()
+ @safe
+ @statsd_metrics
+ @event_logger.log_this_with_context(
+ action=lambda self, *args, **kwargs: (
+ f"{self.__class__.__name__}.partition_mapping_preview"
+ ),
+ log_to_statsd=False,
+ )
+ def partition_mapping_preview(self, pk: int) -> Response:
Review Comment:
Not sure, but on Oracle the preview and the chart pass `:value` as different types: the preview sends a string, a chart's time range sends a typed `TO_DATE(...)`. So `TO_DATE(:value, 'YYYY-MM-DD HH24:MI:SS')` previews Valid, yet with the default `NLS_DATE_FORMAT` the bounds land in year 0012 and the chart returns 0 rows. Could the preview probe with the same typed values the chart path uses?

[mp4](https://gist.githubusercontent.com/geido/2e9a0de274464f8bac4b8ac43e8888e9/raw/bug4b-oracle-preview-drift.mp4)
##########
superset/db_engine_specs/oracle.py:
##########
@@ -36,6 +36,7 @@
class OracleEngineSpec(BaseEngineSpec):
engine = "oracle"
engine_name = "Oracle"
+ select_without_from_suffix = " FROM DUAL"
Review Comment:
I think the new temporal literal path drops the time on Oracle. Its `DATE` keeps the time of day but maps to `sa.Date`, so `holds_days_only` skips the precision check and the bound becomes `TO_DATE('2026-01-12', 'YYYY-MM-DD')`. With `CAST(:value AS DATE)` (preview Valid), a 06:30 to 18:30 range returns 0 rows instead of 48. Could the exemption skip Oracle, whose dialect `DATE` is a `DateTime`?

[mp4](https://gist.githubusercontent.com/geido/2e9a0de274464f8bac4b8ac43e8888e9/raw/bug4a-oracle-date-floor.mp4)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org