The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Index manager (#75848)
Ngoc Khuat32a869b1e6ab
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 51db75d23fb..78f34ceaa2a 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -1064,6 +1064,27 @@:model-exports #{:model/ModelIndex :model/ModelIndexValue}:model-imports #{:model/Card :model/Collection}}+ indexes+ {:team "Gadget"+ :api #{metabase.indexes.models.table-index+ metabase.indexes.reconcile+ metabase.indexes.schema}+ :uses #{driver+ models+ util}+ :model-exports #{:model/TableIndex}}++ indexes-rest+ {:team "Gadget"+ :api #{metabase.indexes-rest.api}+ :uses #{api+ indexes+ transforms-base+ util}+ :model-imports #{:model/Database+ :model/TableIndex+ :model/Transform}}+initialization-status{:team "UX West":api #{metabase.initialization-status.core}@@ -2371,6 +2392,7 @@database-routingdriverevents+ indexesliblib-bemodels@@ -2400,6 +2422,7 @@:model/Database:model/Field:model/Table+ :model/TableIndex:model/User}}transforms-base@@ -2413,11 +2436,13 @@:model-imports #{:model/Database:model/Field:model/Table+ :model/TableIndex:model/Transform:model/TransformRun}:uses #{database-routingdriverevents+ indexesliblib-bepremium-featuresdiff --git a/docs/developers-guide/driver-changelog.md b/docs/developers-guide/driver-changelog.mdindex 263507da45b..3b316f182a0 100644--- a/docs/developers-guide/driver-changelog.md+++ b/docs/developers-guide/driver-changelog.md@@ -6,6 +6,37 @@ title: Driver interface changelog## Metabase 0.63.0+- Index Manager: drivers can now read and create table indexes, in the broad sense (secondary indexes, sort keys,+ distribution keys, clustering, etc.). New driver feature flags:++ - `:index/fetch` -- the driver can read the indexes that physically exist on a table. Implemented by Postgres,+ ClickHouse, and Redshift.++ - `:index/standalone-create` -- the driver can create an index on a transform's target table as a standalone+ statement after the table is created. Implemented by Postgres.++ - `:index/inline-create` -- the driver inlines an index into the table-creation statement itself (e.g. Redshift+ `SORTKEY`) rather than creating it afterwards. Such drivers render the index from the `:indexes` key of the+ transform details when they build the creation statement: in `metabase.driver/compile-transform` (the CTAS for a+ SQL transform) and/or `metabase.driver/create-table!` (the CREATE TABLE for a Python transform). Implemented by+ Redshift.++ New driver methods:++ - `metabase.driver/fetch-table-indexes` `[driver database schema table]` -- reads a table's physical indexes,+ returning them as a vector of normalized index maps. Drivers declaring `:index/fetch` implement it; the default+ implementation throws.++ - `metabase.driver/supported-index-methods` `[driver database]` -- returns the index methods the driver supports as+ a map of `index-kind` to a metadata map carrying at least `:lifecycle` (`:standalone` or `:inline`). Defaults to+ `{}`.++ - `metabase.driver/compile-create-index` `[driver schema table structured]` -- compiles a `:standalone` index into+ the DDL statement(s) that create it.++ - `metabase.driver/refresh-table-stats!` `[driver database schema table transform-type]` -- refreshes table+ statistics (e.g. `ANALYZE`) after a transform run. Defaults to a no-op.+- `metabase.driver/describe-table-fks`, deprecated in 0.49.0, has been removed. Please implement`metabase.driver/describe-fks` instead. This method is now required for drivers that support`:metadata/key-constraints`.diff --git a/e2e/support/helpers/e2e-data-studio-helpers.ts b/e2e/support/helpers/e2e-data-studio-helpers.tsindex 400026682e0..c3ba92e23b4 100644--- a/e2e/support/helpers/e2e-data-studio-helpers.ts+++ b/e2e/support/helpers/e2e-data-studio-helpers.ts@@ -36,6 +36,7 @@ export const DataStudio = {inspectTab: () => DataStudio.Transforms.header().findByText("Inspect"),targetTab: () => DataStudio.Transforms.header().findByText("Target"),settingsTab: () => DataStudio.Transforms.header().findByText("Settings"),+ indexesTab: () => DataStudio.Transforms.header().findByText("Indexes"),dependenciesTab: () =>DataStudio.Transforms.header().findByText("Dependencies"),visit: () => {@@ -50,6 +51,8 @@ export const DataStudio = {},visitSettingsTab: (transformId: TransformId) =>cy.visit(`/data-studio/transforms/${transformId}/settings`),+ visitIndexes: (transformId: TransformId) =>+ cy.visit(`/data-studio/transforms/${transformId}/indexes`),runButton: () => cy.findAllByTestId("run-button").eq(0),pythonResults: () => cy.findByTestId("python-results"),enableTransformPage: () => cy.findByTestId("enable-transform-page"),diff --git a/e2e/support/helpers/e2e-qa-databases-helpers.js b/e2e/support/helpers/e2e-qa-databases-helpers.jsindex 4646c97bd46..38cc5064b3d 100644--- a/e2e/support/helpers/e2e-qa-databases-helpers.js+++ b/e2e/support/helpers/e2e-qa-databases-helpers.js@@ -422,11 +422,19 @@ export function waitForSyncToFinish({});}+/**+ * @param {object} options+ * @param {number} [options.dbId]+ * @param {string} [options.tableName] - wait until this table is synced+ * @param {string} [options.tableAlias]+ * @param {string[]} [options.tables] - wait until all of these tables are synced+ * @param {boolean} [options.retrigger] - occasionally re-trigger the schema sync while waiting+ */export function resyncDatabase({dbId = 2,tableName = "",- tableAlias = undefined, // TS was complaining that this was a required param- tables,+ tableAlias = undefined,+ tables = [],retrigger = false,}) {// must be signed in as admin to syncdiff --git a/e2e/test/scenarios/data-studio/transforms/transforms-indexes.cy.spec.ts b/e2e/test/scenarios/data-studio/transforms/transforms-indexes.cy.spec.tsnew file mode 100644index 00000000000..8f128b895a2--- /dev/null+++ b/e2e/test/scenarios/data-studio/transforms/transforms-indexes.cy.spec.ts@@ -0,0 +1,216 @@+import { WRITABLE_DB_ID } from "e2e/support/cypress_data";+import type { StructuredIndex, TransformId } from "metabase-types/api";++const { H } = cy;++const SOURCE_TABLE = "Animals";+const TARGET_SCHEMA = "Schema A";++const INDEX_TABLE_COLUMNS = [+ "Name",+ "Type",+ "Columns",+ "Source",+ "Status",+ "Last modified by",+ "Last run",+];++describe("data-studio > transforms > indexes", { tags: ["@external"] }, () => {+ beforeEach(() => {+ H.restore("postgres-writable");+ H.resetTestTable({ type: "postgres", table: "many_schemas" });+ cy.signInAsAdmin();+ H.activateToken("pro-self-hosted");+ H.updateSetting("transforms-enabled", true);+ H.resyncDatabase({ dbId: WRITABLE_DB_ID, tableName: SOURCE_TABLE });+ });++ it("lists managed index requests with pending and removing statuses and sorts by column", () => {+ H.createMbqlTransform({+ sourceTable: SOURCE_TABLE,+ targetTable: "indexes_list_table",+ targetSchema: TARGET_SCHEMA,+ name: "Indexes list transform",+ }).then(({ body: transform }) => {+ createIndexRequest(transform.id, btreeIndex("idx_animal_name", ["name"]));+ createIndexRequest(+ transform.id,+ btreeIndex("idx_animal_score", ["score", "name"]),+ ).then(({ body: request }) => {+ cy.request("DELETE", `/api/index/request/${request.id}`);+ });+ H.DataStudio.Transforms.visitIndexes(transform.id);+ });++ cy.log("all column headers render");+ indexesTable().within(() => {+ INDEX_TABLE_COLUMNS.forEach((header) => {+ cy.findByRole("columnheader", { name: matchHeaderName(header) }).should(+ "be.visible",+ );+ });+ });++ cy.log("pending request row shows all cell values");+ indexesTable().findAllByRole("row").should("have.length", 2);+ indexesTable()+ .findAllByRole("row")+ .eq(0)+ .should("contain", "idx_animal_name")+ .and("contain", "B-Tree")+ .and("contain", "name")+ .and("contain", "Managed")+ .and("contain", "Pending")+ .and("contain", "Bobby Tables")+ .and("contain", "Never");++ cy.log("deleted request row shows the Removing status");+ indexesTable()+ .findAllByRole("row")+ .eq(1)+ .should("contain", "idx_animal_score")+ .and("contain", "score, name")+ .and("contain", "Removing");++ cy.log("clicking the Name header toggles the sort direction");+ indexesTable()+ .findByRole("columnheader", { name: matchHeaderName("Name") })+ .click();+ indexesTable()+ .findByRole("columnheader", { name: matchHeaderName("Name") })+ .should("have.attr", "aria-sort", "descending");+ indexesTable()+ .findAllByRole("row")+ .should("have.length", 2)+ .eq(0)+ .should("contain", "idx_animal_score");+ });++ it("shows a pending index becoming succeeded after a transform run and lists unmanaged warehouse indexes", () => {+ const targetTable = "indexes_lifecycle_table";++ cy.log("run the transform once so the target table exists");+ H.createMbqlTransform({+ sourceTable: SOURCE_TABLE,+ targetTable,+ targetSchema: TARGET_SCHEMA,+ name: "Indexes lifecycle transform",+ }).then(({ body: transform }) => {+ H.runTransformAndWaitForSuccess(transform.id);+ H.DataStudio.Transforms.visitIndexes(transform.id);+ });++ cy.log("the empty state renders for a transform with no indexes");+ cy.findByTestId("transforms-indexes-content")+ .should("contain", "Indexes")+ .and(+ "contain",+ "Index the key columns of your transforms to make them faster and more efficient.",+ );++ cy.log("create an index via the form");+ cy.findByTestId("transforms-indexes-content")+ .findByRole("button", { name: "Create index" })+ .click();++ cy.log("form fields render in the backend-defined order, name first");+ H.modal()+ .find("label")+ .should((labels) => {+ const labelTexts = labels.toArray().map((label) => label.textContent);+ expect(labelTexts).to.deep.equal([+ "Give your index a name",+ "Index type",+ "Enforce uniqueness across rows for indexed columns.",+ "Columns",+ ]);+ });++ H.modal().within(() => {+ cy.findByLabelText("Give your index a name").type("idx_lifecycle_name");+ cy.findByPlaceholderText("Select columns").click();+ });+ cy.findByRole("option", { name: "Name" }).click();+ H.modal().within(() => {+ cy.findByRole("button", { name: "Create index" }).click();+ });+ H.undoToast().findByText("Index created").should("be.visible");++ cy.log("the new index request starts out pending and never run");+ indexesTable()+ .findAllByRole("row")+ .should("have.length", 1)+ .eq(0)+ .should("contain", "idx_lifecycle_name")+ .and("contain", "Managed")+ .and("contain", "Pending")+ .and("contain", "Never");++ cy.log("run the transform from the run tab");+ H.DataStudio.Transforms.runTab().click();+ H.DataStudio.Transforms.runButton().click();+ H.DataStudio.Transforms.runButton().should("have.text", "Ran successfully");++ cy.log("simulate a DBA-created index directly in the warehouse");+ H.queryWritableDB(+ `CREATE INDEX dba_made ON "${TARGET_SCHEMA}"."${targetTable}" (score)`,+ );++ cy.log("the applied index request shows Succeeded and a last run date");+ H.DataStudio.Transforms.indexesTab().click();+ indexesTable().findAllByRole("row").should("have.length", 2);+ indexesTable()+ .findAllByRole("row")+ .eq(1)+ .should("contain", "idx_lifecycle_name")+ .and("contain", "Managed")+ .and("contain", "Succeeded")+ .and("not.contain", "Never");++ cy.log("the managed index physically exists in the warehouse");+ H.queryWritableDB(+ `SELECT indexname FROM pg_indexes+ WHERE schemaname = '${TARGET_SCHEMA}'+ AND tablename = '${targetTable}'+ AND indexname = 'idx_lifecycle_name'`,+ ).then(({ rows }) => {+ expect(rows).to.have.length(1);+ });++ cy.log("the DBA-created index is listed as unmanaged with no status");+ indexesTable()+ .findAllByRole("row")+ .eq(0)+ .should("contain", "dba_made")+ .and("contain", "score")+ .and("contain", "Unmanaged")+ .and("contain", "—");+ });+});++function btreeIndex(name: string, columns: string[]) {+ return {+ kind: "btree",+ name,+ columns: columns.map((column) => ({ name: column })),+ };+}++function createIndexRequest(+ transformId: TransformId,+ structured: StructuredIndex,+) {+ return cy.request("POST", "/api/index/request", {+ transform_id: transformId,+ structured,+ });+}++function indexesTable() {+ return cy.findByRole("treegrid", { name: "Transform indexes" });+}++function matchHeaderName(label: string) {+ return new RegExp(`^${label}`);+}diff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.cljindex b7cf3f2d4cd..4013297ec01 100644--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj@@ -54,6 +54,7 @@"ParameterCard""DashboardCardSeries""MetabotPrompt"+ "TableIndex""TimelineEvent""TransformJobTransformTag""TransformTransformTag"])diff --git a/enterprise/backend/src/metabase_enterprise/transforms_python/base.clj b/enterprise/backend/src/metabase_enterprise/transforms_python/base.cljindex 31cd603c628..5778dbe5e4b 100644--- a/enterprise/backend/src/metabase_enterprise/transforms_python/base.clj+++ b/enterprise/backend/src/metabase_enterprise/transforms_python/base.clj@@ -95,13 +95,15 @@;;; ------------------------------------------------- Transfer Strategies --------------------------------------------------(defn- table-schema [table-name metadata]- {:name (if (keyword? table-name) table-name (keyword table-name))- :columns (mapv (fn [{:keys [name base_type]}]- {:name name- :type (python-runner/restricted-insert-type base_type)- :nullable? true})- (:fields metadata))})+(defn- table-schema [table-name metadata indexes]+ (cond-> {:name (if (keyword? table-name) table-name (keyword table-name))+ :columns (mapv (fn [{:keys [name base_type]}]+ {:name name+ :type (python-runner/restricted-insert-type base_type)+ :nullable? true})+ (:fields metadata))}+ ;; Python builds the table via `create-table!` (not a CTAS), so this is where inline indexes get rendered.+ (seq indexes) (assoc :indexes indexes)))(defn- insert-data!"Insert data from source into an existing table."@@ -117,14 +119,14 @@(defn- transfer-with-rename-tables-strategy!"Transfer data using the rename-tables*! multimethod with atomicity guarantees."- [driver db-id table-name metadata data-source]+ [driver db-id table-name metadata indexes data-source](let [source-table-name (transforms-base.u/temp-table-name driver (namespace table-name))temp-table-name (u/poll {:thunk #(transforms-base.u/temp-table-name driver (namespace table-name)):done? #(not= source-table-name %):interval-ms 1})](log/info "Using rename-tables strategy with atomicity guarantees")(try- (create-table-and-insert-data! driver db-id (table-schema source-table-name metadata) data-source)+ (create-table-and-insert-data! driver db-id (table-schema source-table-name metadata indexes) data-source)(transforms-base.u/rename-tables! driver db-id {table-name temp-table-namesource-table-name table-name})(transforms-base.u/drop-table! driver db-id temp-table-name)@@ -137,11 +139,11 @@(defn- transfer-with-create-drop-rename-strategy!"Transfer data using create + drop + rename to minimize time without data."- [driver db-id table-name metadata data-source]+ [driver db-id table-name metadata indexes data-source](let [source-table-name (transforms-base.u/temp-table-name driver (namespace table-name))](log/info "Using create-drop-rename strategy to minimize downtime")(try- (create-table-and-insert-data! driver db-id (table-schema source-table-name metadata) data-source)+ (create-table-and-insert-data! driver db-id (table-schema source-table-name metadata indexes) data-source)(transforms-base.u/drop-table! driver db-id table-name)(driver/rename-table! driver db-id source-table-name table-name)(catch Exception e@@ -153,11 +155,11 @@(defn- transfer-with-drop-create-fallback-strategy!"Transfer data using drop + create fallback strategy."- [driver db-id table-name metadata data-source]+ [driver db-id table-name metadata indexes data-source](log/info "Using drop-create fallback strategy")(try(transforms-base.u/drop-table! driver db-id table-name)- (create-table-and-insert-data! driver db-id (table-schema table-name metadata) data-source)+ (create-table-and-insert-data! driver db-id (table-schema table-name metadata indexes) data-source)(catch Exception e(log/error e "Failed to transfer data using drop-create fallback strategy")(throw e))))@@ -168,7 +170,7 @@(let [db-id (:id db)staging (transforms-base.u/temp-table-name driver (namespace table-name))](transforms-base.u/validate-merge-unique-key! unique-key (mapv :name (:fields metadata)))- (create-table-and-insert-data! driver db-id (table-schema staging metadata) data-source)+ (create-table-and-insert-data! driver db-id (table-schema staging metadata nil) data-source)(try(let [[sql & params] (sql.qp/format-honeysql driver {:select [:*], :from [staging]})select {:query sql, :params (vec params)}@@ -201,13 +203,16 @@(not table-exists?)(do(log/info "New table")- (create-table-and-insert-data! driver db-id (table-schema table-name metadata) data-source))+ (create-table-and-insert-data! driver db-id+ (table-schema table-name metadata (:indexes target))+ data-source))unique-key(upsert-with-merge-strategy! driver db table-name metadata data-source unique-key):else- (insert-data! driver db-id (table-schema table-name metadata) data-source)))))+ ;; Append into an existing table: no create, so no inline indexes to apply.+ (insert-data! driver db-id (table-schema table-name metadata nil) data-source)))))(defmethod transfer-file-to-db :table[driver {db-id :id :as db}@@ -215,22 +220,23 @@metadata temp-file](let [table-name (transforms-base.u/qualified-table-name driver target)table-exists? (transforms-base.u/target-table-exists? transform)+ indexes (:indexes target)data-source {:type :jsonl-file:file temp-file}](cond(not table-exists?)(do(log/info "New table")- (create-table-and-insert-data! driver db-id (table-schema table-name metadata) data-source))+ (create-table-and-insert-data! driver db-id (table-schema table-name metadata indexes) data-source))(driver.u/supports? driver :atomic-renames db)- (transfer-with-rename-tables-strategy! driver db-id table-name metadata data-source)+ (transfer-with-rename-tables-strategy! driver db-id table-name metadata indexes data-source)(driver.u/supports? driver :rename db)- (transfer-with-create-drop-rename-strategy! driver db-id table-name metadata data-source)+ (transfer-with-create-drop-rename-strategy! driver db-id table-name metadata indexes data-source):else- (transfer-with-drop-create-fallback-strategy! driver db-id table-name metadata data-source))))+ (transfer-with-drop-create-fallback-strategy! driver db-id table-name metadata indexes data-source))));;; ------------------------------------------------- Cancellation -------------------------------------------------diff --git a/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.cljindex 39282320c54..c1506034e18 100644--- a/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj+++ b/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj@@ -124,6 +124,7 @@:model/SourceSegmentDaily:model/SsoRelayState:model/SupportAccessGrantLog+ :model/TableIndex:model/TaskHistory:model/TaskRun:model/Tenantdiff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.cljindex 496711b23bb..2680fad3cb0 100644--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj@@ -2145,7 +2145,7 @@{:transform_id transform-id:tag_id daily-tag-id:position 2}]- (let [ser (serdes/extract-one "Transform" {} (t2/hydrate (t2/select-one :model/Transform :id transform-id) :tags))]+ (let [ser (serdes/extract-one "Transform" {} (t2/hydrate (t2/select-one :model/Transform :id transform-id) :tags :indexes))](testing "basic Transform structure"(is (=? {:serdes/meta [{:model "Transform":id transform-eid}]@@ -2176,7 +2176,7 @@(is (contains? deps [{:model "TransformTag" :id custom-tag-eid}]))(is (contains? deps [{:model "TransformTag" :id daily-tag-eid}])))))(testing "python transform source-tables export"- (let [ser (serdes/extract-one "Transform" {} (t2/hydrate (t2/select-one :model/Transform :id python-transform-id) :tags))]+ (let [ser (serdes/extract-one "Transform" {} (t2/hydrate (t2/select-one :model/Transform :id python-transform-id) :tags :indexes))](is (=? {:source {:type :python:source-database "My Database":source-tables [{:alias "orders"@@ -2208,7 +2208,7 @@:name "orphan_target"}}];; Delete the database — ON DELETE SET NULL nulls source_database_id and target_db_id.(t2/delete! :model/Database db-id)- (let [reloaded (t2/hydrate (t2/select-one :model/Transform :id transform-id) :tags)+ (let [reloaded (t2/hydrate (t2/select-one :model/Transform :id transform-id) :tags :indexes)ser (serdes/extract-one "Transform" {} reloaded)](is (nil? (:source_database_id reloaded))"Database deletion should have nulled the column")diff --git a/enterprise/backend/test/metabase_enterprise/transforms/incremental_test.clj b/enterprise/backend/test/metabase_enterprise/transforms/incremental_test.cljindex df9231b3355..1a04a77a856 100644--- a/enterprise/backend/test/metabase_enterprise/transforms/incremental_test.clj+++ b/enterprise/backend/test/metabase_enterprise/transforms/incremental_test.clj@@ -18,6 +18,7 @@[metabase.test :as mt][metabase.transforms-base.util :as transforms-base.u][metabase.transforms.execute :as transforms.execute]+ [metabase.transforms.index-test-util :as index-util][metabase.transforms.test-dataset :as transforms-dataset][metabase.transforms.test-util :as transforms.tu :refer [with-transform-cleanup!]][next.jdbc :as next.jdbc]@@ -703,3 +704,80 @@checkpoint (get-checkpoint-value (:id transform))](is (= 17 row-count) "Should append 1 new row (16 + 1 = 17)")(is (some? checkpoint) "Checkpoint should be updated"))))))))))))))))++(defn- incremental-index-test-drivers+ "Index-supporting drivers that also run incremental transforms (effectively postgres today; the incremental suite+ excludes redshift/clickhouse/sqlserver)."+ []+ (into #{} (filter (index-util/index-test-drivers)) (test-drivers)))++(deftest ^:synchronized ^:mb/transforms-python-test declared-indexes-on-incremental-transform-test+ (testing "incremental: the first (full) run creates the target's declared indexes; an append run preserves them"+ ;; The first run has no watermark, so it's a full rebuild that creates the indexes. The append run keeps the+ ;; live table, so `apply-target-indexes!`'s full-rebuild gate skips it (a broken gate would re-create them).+ (mt/test-drivers (incremental-index-test-drivers)+ (mt/with-premium-features #{:transforms-basic :transforms-python}+ (mt/dataset transforms-dataset/transforms-test+ (let [{:keys [indexes expected physical-indexes]} (index-util/driver-cases driver/*driver*)+ checkpoint-config (:integer checkpoint-configs)+ checkpoint-field (:field-name checkpoint-config)]+ (doseq [transform-type [:mbql :python]]+ (testing (str "transform-type " transform-type)+ (with-transform-cleanup! [{table-name :name :as target} (target-table-gen "incremental_index")]+ (let [payload (make-incremental-transform-payload "Incremental Index Transform"+ target transform-type checkpoint-config)+ schema (:schema target)]+ (mt/with-temp [:model/Transform transform payload]+ (t2/insert! :model/TableIndex (for [index indexes]+ {:transform_id (:id transform)+ :index_name (or (:name index) (name (:kind index)))+ :structured index}))+ (testing "first (full) run creates the declared indexes"+ (execute-transform-with-ordering! transform transform-type checkpoint-field+ {:run-method :manual})+ (transforms.tu/wait-for-table table-name 10000)+ (is (= expected (physical-indexes (mt/db) schema table-name))))+ (testing "append run preserves the indexes"+ (with-insert-test-products! [{:name "Incremental Index Product" :category "Gadget"+ :price 379.99 :created-at "2024-01-20T10:00:00"}]+ (let [transform (t2/select-one :model/Transform (:id transform))]+ (execute-transform-with-ordering! transform transform-type checkpoint-field+ {:run-method :manual})+ (is (= expected (physical-indexes (mt/db) schema table-name)))))))))))))))))++(deftest ^:synchronized index-added-mid-lifecycle-forces-rebuild-test+ (testing "an index request created after the watermark is set forces the next run to rebuild and apply it"+ ;; Nothing resets the watermark here: the pending TableIndex row alone must flip `full-incremental-run?`, so a+ ;; broken pending-changes gate would leave this run an append and the index would never reach the warehouse.+ (mt/test-drivers (incremental-index-test-drivers)+ (mt/with-premium-features #{:transforms-basic}+ (mt/dataset transforms-dataset/transforms-test+ (let [{:keys [expected physical-indexes indexes]} (index-util/driver-cases driver/*driver*)+ checkpoint-config (:integer checkpoint-configs)+ checkpoint-field (:field-name checkpoint-config)]+ ;; name-set catalogs only; other drivers report shapes this test can't extend generically+ (when (set? expected)+ (with-transform-cleanup! [{table-name :name :as target} (target-table-gen "incremental_midrun_idx")]+ (mt/with-temp [:model/Transform transform (make-incremental-transform-payload+ "Mid-lifecycle Index Transform"+ target :mbql checkpoint-config)]+ (testing "a first run establishes the watermark"+ (execute-transform-with-ordering! transform :mbql checkpoint-field {:run-method :manual})+ (transforms.tu/wait-for-table table-name 10000)+ (is (some? (get-checkpoint-value (:id transform)))))+ ;; the driver's own first index kind: a kind it doesn't advertise is dropped before any DDL runs.+ (t2/insert! :model/TableIndex {:transform_id (:id transform)+ :index_name "mid_run_idx"+ :structured (assoc (first indexes) :name "mid_run_idx")})+ (testing "the watermark survives the request untouched"+ (is (some? (get-checkpoint-value (:id transform)))))+ (testing "the next run rebuilds and the index lands in the warehouse"+ (let [transform (t2/select-one :model/Transform (:id transform))]+ (execute-transform-with-ordering! transform :mbql checkpoint-field {:run-method :manual})+ (is (contains? (physical-indexes (mt/db) (:schema target) table-name) "mid_run_idx"))+ (is (= :succeeded (t2/select-one-fn :status :model/TableIndex+ :transform_id (:id transform)+ :index_name "mid_run_idx")))))+ (testing "once settled, the run after that appends again"+ (let [transform (t2/select-one :model/Transform (:id transform))]+ (is (not (transforms-base.u/full-incremental-run? transform))))))))))))))diff --git a/frontend/src/metabase-types/api/icon.ts b/frontend/src/metabase-types/api/icon.tsindex 5e5024f625a..5b16eba4277 100644--- a/frontend/src/metabase-types/api/icon.ts+++ b/frontend/src/metabase-types/api/icon.ts@@ -261,6 +261,7 @@ export type IconName =| "tab"| "table"| "table2"+ | "table_index"| "text_bold"| "text_italic"| "text_strike"diff --git a/frontend/src/metabase-types/api/index-manager.ts b/frontend/src/metabase-types/api/index-manager.tsnew file mode 100644index 00000000000..878b1143586--- /dev/null+++ b/frontend/src/metabase-types/api/index-manager.ts@@ -0,0 +1,176 @@+import type { TransformId } from "./transform";+import type { UserId } from "./user";++export type TableIndexRequestId = number;++export type IndexColumnDirection = "asc" | "desc";++export type IndexColumn = {+ name: string;+ direction?: IndexColumnDirection;+};++export const CLASSICAL_INDEX_KINDS = [+ "btree",+ "hash",+ "gin",+ "gist",+ "brin",+ "spgist",+ "fulltext",+ "spatial",+ "clustered",+ "nonclustered",+ "columnstore",+] as const;+export type ClassicalIndexKind = (typeof CLASSICAL_INDEX_KINDS)[number];++export type ClassicalIndex = {+ kind: ClassicalIndexKind;+ name: string;+ columns: IndexColumn[];+ include?: string[];+ unique?: boolean;+};++export type SortKeyStyle = "compound" | "interleaved";++export type SortKeyIndex = {+ kind: "sortkey";+ style: SortKeyStyle;+ columns: IndexColumn[];+};++export type DistKeyIndex = {+ kind: "distkey";+ column: string;+};++export type ClusteringIndex = {+ kind: "clustering";+ name?: string;+ columns: IndexColumn[];+};++export type OrderByIndex = {+ kind: "order-by";+ columns: IndexColumn[];+};++export const SKIP_INDEX_TYPES = [+ "minmax",+ "set",+ "bloom_filter",+ "ngrambf_v1",+ "tokenbf_v1",+] as const;+export type SkipIndexType = (typeof SKIP_INDEX_TYPES)[number];++export type SkipIndex = {+ kind: "skip-index";+ name: string;+ columns: IndexColumn[];+ type: SkipIndexType;+ "type-args"?: unknown[];+ granularity?: number;+};++export type StructuredIndex =+ | ClassicalIndex+ | SortKeyIndex+ | DistKeyIndex+ | ClusteringIndex+ | OrderByIndex+ | SkipIndex;++export type IndexKind = StructuredIndex["kind"];++export const TABLE_INDEX_REQUEST_STATUSES = [+ "create-pending",+ "update-pending",+ "delete-pending",+ "running",+ "succeeded",+ "failed",+] as const;+export type TableIndexRequestStatus =+ (typeof TABLE_INDEX_REQUEST_STATUSES)[number];++export type TableIndexRequest = {+ id: TableIndexRequestId;+ transform_id: TransformId;+ index_name: string;+ structured: StructuredIndex;+ status: TableIndexRequestStatus;+ error_message: string | null;+ created_by: UserId | null;+ created_at: string;+ updated_at: string;+ last_executed_at: string | null;+};++export type TableIndexEntry = {+ metabase_managed: boolean;+ present_in_warehouse: boolean;+ name: string | null;+ kind: string;+ key_columns: string[];+ include_columns: (string | null)[];+ is_unique: boolean;+ is_primary: boolean;+ is_valid: boolean;+ partial_predicate: string | null;+ access_method: string | null;+ request?: TableIndexRequest;+};++export type ListTableIndexesRequest = {+ "transform-id": TransformId;+};++export type ListTableIndexesResponse = {+ data: TableIndexEntry[];+};++export type CreateTableIndexRequest = {+ transform_id: TransformId;+ structured: StructuredIndex;+};++export type UpdateTableIndexRequest = {+ id: TableIndexRequestId;+ structured: StructuredIndex;+};++export type IndexFieldType =+ | "string"+ | "boolean"+ | "select"+ | "integer"+ | "columns";++export type IndexFieldOption = {+ name: string;+ value: string;+};++export type IndexField = {+ name: string;+ "display-name": string;+ description?: string;+ type: IndexFieldType;+ required?: boolean;+ directions?: boolean;+ options?: IndexFieldOption[];+};++export type IndexMethodLifecycle = "standalone" | "inline";++export type IndexMethod = {+ lifecycle: IndexMethodLifecycle;+ "display-name": string;+ description?: string;+ fields: IndexField[];+};++export type RequestableIndexes = Partial<Record<IndexKind, IndexMethod>>;diff --git a/frontend/src/metabase-types/api/index.ts b/frontend/src/metabase-types/api/index.tsindex c8457421b08..50cd3ed1fb7 100644--- a/frontend/src/metabase-types/api/index.ts+++ b/frontend/src/metabase-types/api/index.ts@@ -30,6 +30,7 @@ export * from "./field";export * from "./geojson";export * from "./group";export * from "./icon";+export * from "./index-manager";export * from "./insight";export * from "./llm";export * from "./logger";diff --git a/frontend/src/metabase-types/api/mocks/index-manager.ts b/frontend/src/metabase-types/api/mocks/index-manager.tsnew file mode 100644index 00000000000..0a89be036b8--- /dev/null+++ b/frontend/src/metabase-types/api/mocks/index-manager.ts@@ -0,0 +1,103 @@+import type {+ IndexField,+ IndexMethod,+ RequestableIndexes,+ TableIndexEntry,+ TableIndexRequest,+} from "metabase-types/api";++export const createMockTableIndexRequest = (+ opts?: Partial<TableIndexRequest>,+): TableIndexRequest => ({+ id: 1,+ transform_id: 1,+ index_name: "btree",+ structured: {+ kind: "btree",+ name: "btree",+ columns: [{ name: "id" }],+ },+ status: "create-pending",+ error_message: null,+ created_by: 1,+ created_at: "2020-01-01T00:00:00.000Z",+ updated_at: "2020-01-01T00:00:00.000Z",+ last_executed_at: null,+ ...opts,+});++export const createMockTableIndexEntry = (+ opts?: Partial<TableIndexEntry>,+): TableIndexEntry => ({+ metabase_managed: true,+ present_in_warehouse: true,+ name: "btree",+ kind: "btree",+ key_columns: ["id"],+ include_columns: [],+ is_unique: false,+ is_primary: false,+ is_valid: true,+ partial_predicate: null,+ access_method: null,+ request: createMockTableIndexRequest(),+ ...opts,+});++const INDEX_NAME_FIELD: IndexField = {+ name: "name",+ "display-name": "Give your index a name",+ type: "string",+ required: true,+};++export const createMockIndexMethod = (+ opts?: Partial<IndexMethod>,+): IndexMethod => ({+ lifecycle: "standalone",+ "display-name": "B-Tree",+ fields: [INDEX_NAME_FIELD],+ ...opts,+});++export const createMockRequestableIndexes = (): RequestableIndexes => ({+ btree: createMockIndexMethod({+ "display-name": "B-Tree",+ description:+ "Default. Best for equality and range queries on sortable data; use it for most columns you filter, sort, or join by.",+ fields: [+ INDEX_NAME_FIELD,+ {+ name: "unique",+ "display-name": "Unique",+ description: "Enforce uniqueness across rows for indexed columns.",+ type: "boolean",+ },+ {+ name: "columns",+ "display-name": "Columns",+ description:+ "The column(s) the index will be built on. Usually the ones you filter or join by.",+ type: "columns",+ required: true,+ directions: true,+ },+ ],+ }),+ gin: createMockIndexMethod({+ "display-name": "GIN",+ description:+ "For values with multiple components. Best for full-text search, JSONB, and arrays—when you're searching inside a value.",+ fields: [+ INDEX_NAME_FIELD,+ {+ name: "columns",+ "display-name": "Columns",+ description:+ "The column(s) the index will be built on. Usually the ones you filter or join by.",+ type: "columns",+ required: true,+ },+ ],+ }),+});diff --git a/frontend/src/metabase-types/api/mocks/index.ts b/frontend/src/metabase-types/api/mocks/index.tsindex e8b913a32d9..38e46e1b320 100644--- a/frontend/src/metabase-types/api/mocks/index.ts+++ b/frontend/src/metabase-types/api/mocks/index.ts@@ -14,6 +14,7 @@ export * from "./erd";export * from "./field";export * from "./geojson";export * from "./group";+export * from "./index-manager";export * from "./insight";export * from "./logger";export * from "./measure";diff --git a/frontend/src/metabase-types/api/transform.ts b/frontend/src/metabase-types/api/transform.tsindex bcadba83497..99c055c9a02 100644--- a/frontend/src/metabase-types/api/transform.ts+++ b/frontend/src/metabase-types/api/transform.ts@@ -1,6 +1,7 @@import type { Collection, CollectionId } from "./collection";import type { DatabaseId } from "./database";import type { RowValue } from "./dataset";+import type { RequestableIndexes } from "./index-manager";import type { PaginationRequest, PaginationResponse } from "./pagination";import type { DatasetQuery, JoinStrategy } from "./query";import type { ScheduleDisplayType } from "./settings";@@ -67,6 +68,7 @@ export type Transform = {table?: Table | null;last_run?: TransformRun | null;creator?: UserInfo;+ requestable_indexes?: RequestableIndexes | null;};export type SuggestedTransform = Partial<Pick<Transform, "id">> &diff --git a/frontend/src/metabase/api/index-manager.ts b/frontend/src/metabase/api/index-manager.tsnew file mode 100644index 00000000000..531b05308fc--- /dev/null+++ b/frontend/src/metabase/api/index-manager.ts@@ -0,0 +1,89 @@+import type {+ CreateTableIndexRequest,+ ListTableIndexesRequest,+ ListTableIndexesResponse,+ TableIndexEntry,+ TableIndexRequest,+ TableIndexRequestId,+ UpdateTableIndexRequest,+} from "metabase-types/api";++import { Api } from "./api";+import {+ idTag,+ invalidateTags,+ listTag,+ provideTableIndexListTags,+ provideTableIndexTags,+} from "./tags";++export const indexManagerApi = Api.injectEndpoints({+ endpoints: (builder) => ({+ listTableIndexes: builder.query<TableIndexEntry[], ListTableIndexesRequest>(+ {+ query: (params) => ({+ method: "GET",+ url: "/api/index",+ params,+ }),+ transformResponse: (response: ListTableIndexesResponse) =>+ response.data,+ providesTags: (indexes = []) => provideTableIndexListTags(indexes),+ },+ ),+ getTableIndex: builder.query<TableIndexRequest, TableIndexRequestId>({+ query: (id) => ({+ method: "GET",+ url: `/api/index/request/${id}`,+ }),+ providesTags: (index) => (index ? provideTableIndexTags(index) : []),+ }),+ createTableIndex: builder.mutation<+ TableIndexRequest,+ CreateTableIndexRequest+ >({+ query: (body) => ({+ method: "POST",+ url: "/api/index/request",+ body,+ }),+ invalidatesTags: (_index, error) =>+ invalidateTags(error, [listTag("table-index")]),+ }),+ updateTableIndex: builder.mutation<+ TableIndexRequest,+ UpdateTableIndexRequest+ >({+ query: ({ id, structured }) => ({+ method: "PUT",+ url: `/api/index/request/${id}`,+ body: { structured },+ }),+ invalidatesTags: (_index, error, { id }) =>+ invalidateTags(error, [+ listTag("table-index"),+ idTag("table-index", id),+ ]),+ }),+ deleteTableIndex: builder.mutation<void, TableIndexRequestId>({+ query: (id) => ({+ method: "DELETE",+ url: `/api/index/request/${id}`,+ }),+ invalidatesTags: (_index, error, id) =>+ invalidateTags(error, [+ listTag("table-index"),+ idTag("table-index", id),+ ]),+ }),+ }),+});++export const {+ useListTableIndexesQuery,+ useGetTableIndexQuery,+ useLazyGetTableIndexQuery,+ useCreateTableIndexMutation,+ useUpdateTableIndexMutation,+ useDeleteTableIndexMutation,+} = indexManagerApi;diff --git a/frontend/src/metabase/api/index.ts b/frontend/src/metabase/api/index.tsindex 30502bcfa69..678b90b1dbd 100644--- a/frontend/src/metabase/api/index.ts+++ b/frontend/src/metabase/api/index.ts@@ -24,6 +24,7 @@ export * from "./frontend-errors";export * from "./glossary";export * from "./google";export * from "./group-table-access-policy";+export * from "./index-manager";export * from "./ldap";export * from "./llm";export * from "./login-history";diff --git a/frontend/src/metabase/api/tags/constants.ts b/frontend/src/metabase/api/tags/constants.tsindex 1f3361f7484..5cddab76023 100644--- a/frontend/src/metabase/api/tags/constants.ts+++ b/frontend/src/metabase/api/tags/constants.ts@@ -28,6 +28,7 @@ export const TAG_TYPES = ["field-values","glossary","indexed-entity",+ "table-index","llm-models","logger-preset","measure",diff --git a/frontend/src/metabase/api/tags/utils.ts b/frontend/src/metabase/api/tags/utils.tsindex 7feb558a19d..40f01c4081c 100644--- a/frontend/src/metabase/api/tags/utils.ts+++ b/frontend/src/metabase/api/tags/utils.ts@@ -1,6 +1,7 @@import type { TagDescription } from "@reduxjs/toolkit/query";import { isVirtualDashCard } from "metabase/utils/dashboard";+import { isNotNull } from "metabase/utils/types";import type {Alert,ApiKey,@@ -46,6 +47,8 @@ import type {SearchResult,Segment,Table,+ TableIndexEntry,+ TableIndexRequest,TableRemapping,Task,TaskRun,@@ -670,6 +673,27 @@ export function provideSubscriptionTags(return [idTag("subscription", subscription.id)];}+export function provideTableIndexTags(+ index: TableIndexRequest,+): TagDescription<TagType>[] {+ return [+ idTag("table-index", index.id),+ idTag("transform", index.transform_id),+ ];+}++export function provideTableIndexListTags(+ indexes: TableIndexEntry[],+): TagDescription<TagType>[] {+ return [+ listTag("table-index"),+ ...indexes+ .map((index) => index.request)+ .filter(isNotNull)+ .flatMap(provideTableIndexTags),+ ];+}+export function provideTableListTags(tables: Table[],): TagDescription<TagType>[] {diff --git a/frontend/src/metabase/api/transform.ts b/frontend/src/metabase/api/transform.tsindex 82c2ffda4cd..266c21b491c 100644--- a/frontend/src/metabase/api/transform.ts+++ b/frontend/src/metabase/api/transform.ts@@ -68,6 +68,7 @@ export const transformApi = Api.injectEndpoints({tag("table"),listTag("table-remapping"),listTag("transform-run"),+ listTag("table-index"),]),onQueryStarted: async (id, { dispatch, queryFulfilled }) => {const patchResult = dispatch(diff --git a/frontend/src/metabase/common/data-studio/components/TitleSection/TitleSection.tsx b/frontend/src/metabase/common/data-studio/components/TitleSection/TitleSection.tsxindex 64be65c373b..9a10f278f71 100644--- a/frontend/src/metabase/common/data-studio/components/TitleSection/TitleSection.tsx+++ b/frontend/src/metabase/common/data-studio/components/TitleSection/TitleSection.tsx@@ -5,6 +5,7 @@ import { Card, Group, Stack, Text, Title } from "metabase/ui";type TitleSectionProps = {label: ReactNode;description?: ReactNode;+ actions?: ReactNode;children?: ReactNode;"data-testid"?: string;};@@ -12,16 +13,18 @@ type TitleSectionProps = {export function TitleSection({label,description,+ actions,children,"data-testid": dataTestId,}: TitleSectionProps) {return (<Stack data-testid={dataTestId}>- <Group>+ <Group justify="space-between" wrap="nowrap"><Stack flex={1} gap="sm"><Title order={4}>{label}</Title>{description != null && <Text c="text-secondary">{description}</Text>}</Stack>+ {actions}</Group><Card p={0} shadow="none" withBorder>{children}diff --git a/frontend/src/metabase/common/data-studio/components/TitleSection/TitleSection.unit.spec.tsx b/frontend/src/metabase/common/data-studio/components/TitleSection/TitleSection.unit.spec.tsxindex 4e1001d57ce..ad1a5905f78 100644--- a/frontend/src/metabase/common/data-studio/components/TitleSection/TitleSection.unit.spec.tsx+++ b/frontend/src/metabase/common/data-studio/components/TitleSection/TitleSection.unit.spec.tsx@@ -7,10 +7,15 @@ import { TitleSection } from "./TitleSection";type SetupOpts = {label?: string;children?: ReactNode;+ actions?: ReactNode;};-function setup({ label = "Default Title", children }: SetupOpts = {}) {- renderWithProviders(<TitleSection label={label}>{children}</TitleSection>);+function setup({ label = "Default Title", children, actions }: SetupOpts = {}) {+ renderWithProviders(+ <TitleSection label={label} actions={actions}>+ {children}+ </TitleSection>,+ );}describe("TitleSection", () => {@@ -23,4 +28,12 @@ describe("TitleSection", () => {expect(screen.getByText(label)).toBeInTheDocument();expect(screen.getByText("Title section content")).toBeInTheDocument();});++ it("should render the actions slot", () => {+ setup({ actions: <button>Create index</button> });++ expect(+ screen.getByRole("button", { name: "Create index" }),+ ).toBeInTheDocument();+ });});diff --git a/frontend/src/metabase/metadata/components/FieldVisibilityPicker/FieldVisibilityPicker.tsx b/frontend/src/metabase/metadata/components/FieldVisibilityPicker/FieldVisibilityPicker.tsxindex c87e729129b..4f1a59b4bbc 100644--- a/frontend/src/metabase/metadata/components/FieldVisibilityPicker/FieldVisibilityPicker.tsx+++ b/frontend/src/metabase/metadata/components/FieldVisibilityPicker/FieldVisibilityPicker.tsx@@ -2,17 +2,12 @@ import { t } from "ttag";import { FIELD_VISIBILITY_TYPES } from "metabase/common/utils/fields";import {- Flex,- Icon,Select,- SelectItem,+ SelectItemWithDescription,type SelectProps,- Text,} from "metabase/ui";import type { FieldVisibilityType } from "metabase-types/api";-import S from "./FieldVisibilityPicker.module.css";-const DATA = getData();interface Props extends Omit<SelectProps, "data" | "value" | "onChange"> {@@ -49,27 +44,16 @@ export const FieldVisibilityPicker = ({data={DATA}placeholder={t`Select a field visibility`}renderOption={(item) => {- const selected = item.option.value === value;const option = DATA.find((option) => option.value === item.option.value,);return (- <SelectItem selected={selected}>- <Icon name={selected ? "check" : "empty"} />-- <Flex direction="column" flex="1" gap="xs">- <Text c="inherit" fw="bold" lh="1rem">- {item.option.label}- </Text>-- {option?.description && (- <Text c="text-disabled" className={S.description} lh="1rem">- {option.description}- </Text>- )}- </Flex>- </SelectItem>+ <SelectItemWithDescription+ selected={item.option.value === value}+ label={item.option.label}+ description={option?.description}+ />);}}value={value}diff --git a/frontend/src/metabase/transforms/components/TransformHeader/TransformTabs.tsx b/frontend/src/metabase/transforms/components/TransformHeader/TransformTabs.tsxindex a50df3c31c2..0c0e7e64ab1 100644--- a/frontend/src/metabase/transforms/components/TransformHeader/TransformTabs.tsx+++ b/frontend/src/metabase/transforms/components/TransformHeader/TransformTabs.tsx@@ -35,6 +35,10 @@ function getTabs(id: TransformId): PaneHeaderTab[] {label: t`Settings`,to: Urls.transformSettings(id),},+ {+ label: t`Indexes`,+ to: Urls.transformIndexes(id),+ },];if (PLUGIN_TRANSFORMS_PYTHON.shouldShowInspectTab) {diff --git a/frontend/src/metabase/transforms/pages/TransformIndexesPage/IndexEditorModal/ColumnsField.tsx b/frontend/src/metabase/transforms/pages/TransformIndexesPage/IndexEditorModal/ColumnsField.tsxnew file mode 100644index 00000000000..16449471d71--- /dev/null+++ b/frontend/src/metabase/transforms/pages/TransformIndexesPage/IndexEditorModal/ColumnsField.tsx@@ -0,0 +1,88 @@+import { useField } from "formik";+import type { ReactNode } from "react";+import { t } from "ttag";++import { type ComboboxItem, Input, MultiSelect, Stack } from "metabase/ui";+import type { IndexColumn, IndexColumnDirection } from "metabase-types/api";++import { DirectionList } from "./DirectionList";++type ColumnsFieldProps = {+ name: string;+ label?: ReactNode;+ description?: ReactNode;+ options: ComboboxItem[];+ supportsDirections: boolean;+ disabled?: boolean;+};++export function ColumnsField({+ name,+ label,+ description,+ options,+ supportsDirections,+ disabled,+}: ColumnsFieldProps) {+ const [+ { value: selectedColumns = [] },+ { error, touched },+ { setValue, setTouched },+ ] = useField<IndexColumn[]>(name);++ function handleColumnChange(names: string[]) {+ setValue(+ names.map((columnName) => {+ const existingColumnSelection = selectedColumns.find(+ (column) => column.name === columnName,+ );+ if (existingColumnSelection) {+ return existingColumnSelection;+ }+ return supportsDirections+ ? { name: columnName, direction: "asc" }+ : { name: columnName };+ }),+ );+ setTouched(true);+ }++ function handleDirectionChange(+ columnName: string,+ direction: IndexColumnDirection,+ ) {+ setValue(+ selectedColumns.map((column) =>+ column.name === columnName ? { ...column, direction } : column,+ ),+ );+ }++ return (+ <Input.Wrapper+ label={label}+ description={description}+ error={touched ? error : null}+ >+ <Stack gap="sm" mt="xs">+ <MultiSelect+ data={options}+ value={selectedColumns.map((column) => column.name)}+ onChange={handleColumnChange}+ onBlur={() => setTouched(true)}+ placeholder={t`Select columns`}+ searchable+ disabled={disabled}+ />+ {supportsDirections && selectedColumns.length > 0 && (+ <DirectionList+ columns={selectedColumns}+ options={options}+ onChange={handleDirectionChange}+ disabled={disabled}+ />+ )}+ </Stack>+ </Input.Wrapper>+ );+}diff --git a/frontend/src/metabase/transforms/pages/TransformIndexesPage/IndexEditorModal/DirectionList.tsx b/frontend/src/metabase/transforms/pages/TransformIndexesPage/IndexEditorModal/DirectionList.tsxnew file mode 100644index 00000000000..393ac74b684--- /dev/null+++ b/frontend/src/metabase/transforms/pages/TransformIndexesPage/IndexEditorModal/DirectionList.tsx@@ -0,0 +1,62 @@+import { t } from "ttag";++import {+ Card,+ type ComboboxItem,+ Group,+ SegmentedControl,+ Stack,+ Text,+} from "metabase/ui";+import type { IndexColumn, IndexColumnDirection } from "metabase-types/api";++type DirectionListProps = {+ columns: IndexColumn[];+ options: ComboboxItem[];+ onChange: (columnName: string, direction: IndexColumnDirection) => void;+ disabled?: boolean;+};++export function DirectionList({+ columns,+ options,+ onChange,+ disabled,+}: DirectionListProps) {+ return (+ <Card withBorder shadow="none" p="md">+ <Stack gap="sm">+ <Text fw="bold">{t`Sort order for each column to be stored in`}</Text>+ {columns.map((column) => (+ <Group key={column.name} justify="space-between" wrap="nowrap">+ <Text>{getColumnLabel(options, column.name)}</Text>+ <SegmentedControl+ value={column.direction}+ onChange={(direction) =>+ onChange(column.name, direction as IndexColumnDirection)+ }+ data={getDirectionOptions()}+ disabled={disabled}+ />+ </Group>+ ))}+ </Stack>+ </Card>+ );+}++function getColumnLabel(columns: ComboboxItem[], columnName: string) {+ return (+ columns.find((option) => option.value === columnName)?.label ?? columnName+ );+}++function getDirectionOptions(): {+ value: IndexColumnDirection;+ label: string;+}[] {+ return [+ { value: "asc", label: t`Asc` },+ { value: "desc", label: t`Desc` },+ ];+}diff --git a/frontend/src/metabase/transforms/pages/TransformIndexesPage/IndexEditorModal/IndexEditorForm.tsx b/frontend/src/metabase/transforms/pages/TransformIndexesPage/IndexEditorModal/IndexEditorForm.tsxnew file mode 100644index 00000000000..fabacc2517e--- /dev/null+++ b/frontend/src/metabase/transforms/pages/TransformIndexesPage/IndexEditorModal/IndexEditorForm.tsx@@ -0,0 +1,97 @@+import { useFormikContext } from "formik";+import { t } from "ttag";++import { Form, FormSubmitButton } from "metabase/forms";+import {+ Button,+ type ComboboxItem,+ Group,+ Select,+ SelectItemWithDescription,+ Stack,+} from "metabase/ui";+import type { IndexField, IndexKind } from "metabase-types/api";++import { IndexFieldInput } from "./IndexFieldInput";+import { getIndexTypeDescription } from "./constants";+import type { IndexKindOption } from "./types";+import type { IndexFormValues } from "./utils";++type IndexEditorFormProps = {+ kind: IndexKind;+ kindOptions: IndexKindOption[];+ fields: IndexField[];+ columnOptions: ComboboxItem[];+ isEditing: boolean;+ submitLabel: string;+ onKindChange: (kind: IndexKind, currentValues: IndexFormValues) => void;+ onClose: () => void;+};++export function IndexEditorForm({+ kind,+ kindOptions,+ fields,+ columnOptions,+ isEditing,+ submitLabel,+ onKindChange,+ onClose,+}: IndexEditorFormProps) {+ const { values } = useFormikContext<IndexFormValues>();+ // The order of fields in the form is driven by the BE schema+ const [firstField, ...restFields] = fields;++ return (+ <Form>+ <Stack gap="lg" mt="sm">+ {firstField && (+ <IndexFieldInput+ key={firstField.name}+ field={firstField}+ columnOptions={columnOptions}+ disabled={isEditing && firstField.name === "name"}+ autoFocus={!isEditing}+ />+ )}++ <Select+ label={t`Index type`}+ description={getIndexTypeDescription()}+ data={kindOptions}+ value={kind}+ onChange={(value) => value && onKindChange(value, values)}+ disabled={isEditing}+ allowDeselect={false}+ renderOption={({ option }) => {+ const description = kindOptions.find(+ (kindOption) => kindOption.value === option.value,+ )?.description;+ return (+ <SelectItemWithDescription+ selected={option.value === kind}+ showCheckIcon={false}+ label={option.label}+ description={description}+ />+ );+ }}+ />++ {restFields.map((field) => (+ <IndexFieldInput+ key={field.name}+ field={field}+ columnOptions={columnOptions}+ disabled={isEditing && field.name === "name"}+ />+ ))}++ <Group justify="flex-end">+ <Button variant="subtle" onClick={onClose}>{t`Cancel`}</Button>+ <FormSubmitButton label={submitLabel} variant="filled" />+ </Group>+ </Stack>+ </Form>+ );+}diff --git a/frontend/src/metabase/transforms/pages/TransformIndexesPage/IndexEditorModal/IndexEditorModal.tsx b/frontend/src/metabase/transforms/pages/TransformIndexesPage/IndexEditorModal/IndexEditorModal.tsxnew file mode 100644index 00000000000..29a8bfaac42--- /dev/null+++ b/frontend/src/metabase/transforms/pages/TransformIndexesPage/IndexEditorModal/IndexEditorModal.tsx@@ -0,0 +1,165 @@+import { useState } from "react";+import { match } from "ts-pattern";+import { t } from "ttag";++import {+ skipToken,+ useCreateTableIndexMutation,+ useGetTableQueryMetadataQuery,+ useUpdateTableIndexMutation,+} from "metabase/api";+import { getErrorMessage } from "metabase/api/utils";+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { useToast } from "metabase/common/hooks";+import { FormProvider } from "metabase/forms";+import { type ComboboxItem, Modal, Text } from "metabase/ui";+import { getObjectKeys } from "metabase/utils/objects";+import type {+ IndexKind,+ Table,+ TableIndexEntry,+ Transform,+} from "metabase-types/api";++import { IndexEditorForm } from "./IndexEditorForm";+import type { IndexKindOption } from "./types";+import {+ type IndexFormValues,+ buildInitialValues,+ buildValidationSchema,+ toStructured,+} from "./utils";++type IndexEditorModalProps = {+ transform: Transform;+ index?: TableIndexEntry;+ onClose: () => void;+};++export function IndexEditorModal({+ transform,+ index,+ onClose,+}: IndexEditorModalProps) {+ const request = index?.request;+ const isEditing = request !== undefined;+ const tableId = transform.table?.id;+ const requestableIndexes = transform.requestable_indexes;+ const kinds = requestableIndexes ? getObjectKeys(requestableIndexes) : [];+ const indexKindOptions: IndexKindOption[] = kinds.map((kind) => {+ const method = requestableIndexes?.[kind];+ return {+ value: kind,+ label: method?.["display-name"] ?? kind,+ description: method?.description ?? null,+ };+ });+ const [kind, setKind] = useState<IndexKind | undefined>(+ request?.structured.kind ?? kinds[0],+ );+ const [carriedValues, setCarriedValues] = useState<IndexFormValues>({});++ function handleKindChange(nextKind: IndexKind, values: IndexFormValues) {+ setCarriedValues(values);+ setKind(nextKind);+ }++ const {+ data: table,+ isLoading,+ error,+ } = useGetTableQueryMetadataQuery(+ tableId !== undefined ? { id: tableId } : skipToken,+ );++ const method = kind !== undefined ? requestableIndexes?.[kind] : undefined;+ const columnOptions = getColumnOptions(table);+ const fields = method?.fields ?? [];+ const initialValues = buildInitialValues(+ fields,+ request?.structured,+ carriedValues,+ );+ const validationSchema = buildValidationSchema(fields);+ const [createTableIndex] = useCreateTableIndexMutation();+ const [updateTableIndex] = useUpdateTableIndexMutation();+ const [sendToast] = useToast();++ async function handleSubmit(values: IndexFormValues) {+ if (kind === undefined) {+ return;+ }+ const structured = toStructured(kind, fields, values);+ try {+ if (isEditing) {+ await updateTableIndex({ id: request.id, structured }).unwrap();+ sendToast({ message: t`Index updated` });+ } else {+ await createTableIndex({+ transform_id: transform.id,+ structured,+ }).unwrap();+ sendToast({ message: t`Index created` });+ }+ onClose();+ } catch (submitError) {+ sendToast({+ message: getErrorMessage(submitError, t`Failed to save index`),+ icon: "warning",+ });+ throw submitError;+ }+ }++ return (+ <Modal+ opened+ title={isEditing ? t`Edit index` : t`Create an index`}+ padding="xl"+ onClose={onClose}+ >+ {isLoading || error !== undefined ? (+ <LoadingAndErrorWrapper loading={isLoading} error={error} />+ ) : kind === undefined ||+ method === undefined ||+ tableId === undefined ? (+ <Text c="text-secondary">+ {match(tableId)+ .with(+ undefined,+ () => t`Run the transform before editing its indexes.`,+ )+ .otherwise(() => t`This index type is no longer available.`)}+ </Text>+ ) : (+ <FormProvider+ key={kind}+ initialValues={initialValues}+ validationSchema={validationSchema}+ onSubmit={handleSubmit}+ >+ <IndexEditorForm+ kind={kind}+ kindOptions={indexKindOptions}+ fields={fields}+ columnOptions={columnOptions}+ isEditing={isEditing}+ submitLabel={isEditing ? t`Update index` : t`Create index`}+ onKindChange={handleKindChange}+ onClose={onClose}+ />+ </FormProvider>+ )}+ </Modal>+ );+}++function getColumnOptions(table: Table | undefined): ComboboxItem[] {+ if (!table?.fields) {+ return [];+ }+ return table.fields.map((field) => ({+ value: field.name,+ label: field.display_name ?? field.name,+ }));+}diff --git a/frontend/src/metabase/transforms/pages/TransformIndexesPage/IndexEditorModal/IndexEditorModal.unit.spec.tsx b/frontend/src/metabase/transforms/pages/TransformIndexesPage/IndexEditorModal/IndexEditorModal.unit.spec.tsxnew file mode 100644index 00000000000..b8259e3e992--- /dev/null+++ b/frontend/src/metabase/transforms/pages/TransformIndexesPage/IndexEditorModal/IndexEditorModal.unit.spec.tsx@@ -0,0 +1,272 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";++import { setupTableIndexEndpoints } from "__support__/server-mocks/index-manager";+import { setupTableQueryMetadataEndpoint } from "__support__/server-mocks/table";+import { renderWithProviders, screen, waitFor } from "__support__/ui";+import type {+ RequestableIndexes,+ StructuredIndex,+ Table,+ TableIndexEntry,+} from "metabase-types/api";+import {+ createMockField,+ createMockRequestableIndexes,+ createMockTable,+ createMockTableIndexEntry,+ createMockTableIndexRequest,+ createMockTransform,+} from "metabase-types/api/mocks";++import { IndexEditorModal } from "./IndexEditorModal";++const TABLE = createMockTable({+ id: 10,+ fields: [+ createMockField({ id: 1, name: "city", display_name: "City name" }),+ createMockField({ id: 2, name: "country", display_name: "Country" }),+ ],+});++function setup({+ index,+ table = TABLE,+ requestableIndexes = createMockRequestableIndexes(),+}: {+ index?: TableIndexEntry;+ table?: Table | null;+ requestableIndexes?: RequestableIndexes;+} = {}) {+ const transform = createMockTransform({+ id: 1,+ table,+ requestable_indexes: requestableIndexes,+ });++ setupTableQueryMetadataEndpoint(TABLE);+ setupTableIndexEndpoints(+ transform.id,+ index?.request != null ? [index.request] : [],+ );++ const onClose = jest.fn();+ renderWithProviders(+ <IndexEditorModal transform={transform} index={index} onClose={onClose} />,+ { withUndos: true },+ );++ return { onClose };+}++describe("IndexEditorModal", () => {+ it("creates a btree index with directions and unique", async () => {+ setup();++ expect(+ await screen.findByText(+ "The data structure used to organize the index. B-tree works well for most lookups, sorting, and range queries.",+ ),+ ).toBeInTheDocument();++ await userEvent.type(+ await screen.findByLabelText("Give your index a name"),+ "index 1",+ );++ await userEvent.click(screen.getByPlaceholderText("Select columns"));+ await userEvent.click(+ await screen.findByRole("option", { name: "City name" }),+ );+ await userEvent.click(+ await screen.findByRole("option", { name: "Country" }),+ );++ await userEvent.click(screen.getByRole("switch"));++ await userEvent.click(screen.getByRole("button", { name: "Create index" }));++ const body = await waitForBody("createTableIndex");++ expect(body.transform_id).toBe(1);+ expect(body.structured).toEqual({+ kind: "btree",+ name: "index 1",+ columns: [+ { name: "city", direction: "asc" },+ { name: "country", direction: "asc" },+ ],+ unique: true,+ });+ });++ it("does not offer directions or a unique switch for gin", async () => {+ setup();++ await userEvent.click(await screen.findByLabelText("Index type"));+ await userEvent.click(await screen.findByRole("option", { name: /GIN/ }));++ expect(screen.queryByRole("switch")).not.toBeInTheDocument();++ await userEvent.type(+ await screen.findByLabelText("Give your index a name"),+ "idx_search",+ );+ await userEvent.click(screen.getByPlaceholderText("Select columns"));+ await userEvent.click(+ await screen.findByRole("option", { name: "City name" }),+ );++ expect(+ screen.queryByText("Sort order for each column to be stored in"),+ ).not.toBeInTheDocument();++ await userEvent.click(screen.getByRole("button", { name: "Create index" }));++ const body = await waitForBody("createTableIndex");+ expect(body.structured).toEqual({+ kind: "gin",+ name: "idx_search",+ columns: [{ name: "city" }],+ });+ });++ it("retains the name and selected columns when changing the index type", async () => {+ setup();++ await userEvent.type(+ await screen.findByLabelText("Give your index a name"),+ "shared_idx",+ );++ await userEvent.click(screen.getByPlaceholderText("Select columns"));+ await userEvent.click(+ await screen.findByRole("option", { name: "City name" }),+ );+ await userEvent.click(+ await screen.findByRole("option", { name: "Country" }),+ );++ await userEvent.click(screen.getByLabelText("Index type"));+ await userEvent.click(await screen.findByRole("option", { name: /GIN/ }));++ expect(screen.getByLabelText("Give your index a name")).toHaveValue(+ "shared_idx",+ );+ expect(screen.getByText("City name")).toBeInTheDocument();+ expect(screen.getByText("Country")).toBeInTheDocument();++ await userEvent.click(screen.getByRole("button", { name: "Create index" }));++ const body = await waitForBody("createTableIndex");+ expect(body.structured).toEqual({+ kind: "gin",+ name: "shared_idx",+ columns: [{ name: "city" }, { name: "country" }],+ });+ });++ it("blocks submitting without a required name", async () => {+ setup();++ await userEvent.click(+ await screen.findByRole("button", { name: "Create index" }),+ );++ expect((await screen.findAllByText("required")).length).toBeGreaterThan(0);+ expect(fetchMock.callHistory.called("createTableIndex")).toBe(false);+ });++ it("edits an existing index and only sends structured via PUT", async () => {+ const structured: StructuredIndex = {+ kind: "btree",+ name: "idx_existing",+ columns: [{ name: "city", direction: "asc" }],+ unique: false,+ };+ const index = createMockTableIndexEntry({+ metabase_managed: true,+ request: createMockTableIndexRequest({ id: 42, structured }),+ });++ setup({ index });++ const nameInput = await screen.findByLabelText("Give your index a name");+ expect(nameInput).toBeDisabled();+ expect(nameInput).toHaveValue("idx_existing");+ expect(screen.getByLabelText("Index type")).toBeDisabled();++ await userEvent.click(screen.getByRole("button", { name: "Update index" }));++ const body = await waitForBody("updateTableIndex-42");+ expect(Object.keys(body)).toEqual(["structured"]);+ expect(body.structured.name).toBe("idx_existing");+ });++ it("shows an error toast when the request fails", async () => {+ setup();+ fetchMock.modifyRoute("createTableIndex", {+ response: { status: 400, body: {} },+ });++ await userEvent.type(+ await screen.findByLabelText("Give your index a name"),+ "idx",+ );+ await userEvent.click(screen.getByPlaceholderText("Select columns"));+ await userEvent.click(+ await screen.findByRole("option", { name: "City name" }),+ );+ await userEvent.click(screen.getByRole("button", { name: "Create index" }));++ expect(await screen.findByText("Failed to save index")).toBeInTheDocument();+ expect(+ await screen.findByRole("button", { name: "Failed" }),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Success" }),+ ).not.toBeInTheDocument();+ });++ it("shows a message instead of a form when the transform has no target table", async () => {+ const index = createMockTableIndexEntry({+ request: createMockTableIndexRequest({+ structured: { kind: "btree", name: "idx", columns: [{ name: "city" }] },+ }),+ });++ setup({ index, table: null });++ expect(+ await screen.findByText("Run the transform before editing its indexes."),+ ).toBeInTheDocument();+ expect(+ screen.queryByLabelText("Give your index a name"),+ ).not.toBeInTheDocument();+ });++ it("shows a message when the index kind is no longer requestable", async () => {+ const index = createMockTableIndexEntry({+ request: createMockTableIndexRequest({+ structured: { kind: "btree", name: "idx", columns: [{ name: "city" }] },+ }),+ });++ setup({ index, requestableIndexes: {} });++ expect(+ await screen.findByText("This index type is no longer available."),+ ).toBeInTheDocument();+ expect(+ screen.queryByLabelText("Give your index a name"),+ ).not.toBeInTheDocument();+ });+});++async function waitForBody(name: string) {+ await waitFor(() => {+ expect(fetchMock.callHistory.called(name)).toBe(true);+ });+ const call = fetchMock.callHistory.lastCall(name);+ return JSON.parse(call?.options?.body as string);+}diff --git a/frontend/src/metabase/transforms/pages/TransformIndexesPage/IndexEditorModal/IndexFieldInput.tsx b/frontend/src/metabase/transforms/pages/TransformIndexesPage/IndexEditorModal/IndexFieldInput.tsxnew file mode 100644index 00000000000..8e103d1a345--- /dev/null+++ b/frontend/src/metabase/transforms/pages/TransformIndexesPage/IndexEditorModal/IndexFieldInput.tsx@@ -0,0 +1,85 @@+import { match } from "ts-pattern";++import {+ FormNumberInput,+ FormSelect,+ FormSwitch,+ FormTextInput,+} from "metabase/forms";+import type { ComboboxItem } from "metabase/ui";+import type { IndexField } from "metabase-types/api";++import { ColumnsField } from "./ColumnsField";++type IndexFieldInputProps = {+ field: IndexField;+ columnOptions: ComboboxItem[];+ disabled?: boolean;+ autoFocus?: boolean;+};++export function IndexFieldInput({+ field,+ columnOptions,+ disabled,+ autoFocus,+}: IndexFieldInputProps) {+ const label = field["display-name"];+ const description = field.description;++ return match(field.type)+ .with("boolean", () => {+ // Per design, the unique switch renders its description as the inline label+ const isUniqueField = field.name === "unique";+ return (+ <FormSwitch+ name={field.name}+ label={isUniqueField ? (description ?? label) : label}+ description={isUniqueField ? undefined : description}+ disabled={disabled}+ size="sm"+ />+ );+ })+ .with("select", () => (+ <FormSelect+ name={field.name}+ label={label}+ description={description}+ data={(field.options ?? []).map((option) => ({+ value: option.value,+ label: option.name,+ }))}+ disabled={disabled}+ />+ ))+ .with("integer", () => (+ <FormNumberInput+ name={field.name}+ label={label}+ description={description}+ disabled={disabled}+ />+ ))+ .with("columns", () => (+ <ColumnsField+ name={field.name}+ label={label}+ description={description}+ options={columnOptions}+ supportsDirections={field.directions ?? false}+ disabled={disabled}+ />+ ))+ .otherwise(() => (+ <FormTextInput+ name={field.name}+ label={label}+ description={description}+ disabled={disabled}+ autoFocus={autoFocus}+ data-autofocus={autoFocus}+ autoComplete="off"+ />+ ));+}diff --git a/frontend/src/metabase/transforms/pages/TransformIndexesPage/IndexEditorModal/constants.ts b/frontend/src/metabase/transforms/pages/TransformIndexesPage/IndexEditorModal/constants.tsnew file mode 100644index 00000000000..208d32c82e0--- /dev/null+++ b/frontend/src/metabase/transforms/pages/TransformIndexesPage/IndexEditorModal/constants.ts@@ -0,0 +1,5 @@+import { t } from "ttag";++export function getIndexTypeDescription(): string {+ return t`The data structure used to organize the index. B-tree works well for most lookups, sorting, and range queries.`;+}diff --git a/frontend/src/metabase/transforms/pages/TransformIndexesPage/IndexEditorModal/types.ts b/frontend/src/metabase/transforms/pages/TransformIndexesPage/IndexEditorModal/types.tsnew file mode 100644index 00000000000..5767db78c48--- /dev/null+++ b/frontend/src/metabase/transforms/pages/TransformIndexesPage/IndexEditorModal/types.ts@@ -0,0 +1,7 @@+import type { IndexKind } from "metabase-types/api";++export type IndexKindOption = {+ value: IndexKind;+ label: string;+ description: string | null;+};diff --git a/frontend/src/metabase/transforms/pages/TransformIndexesPage/IndexEditorModal/utils.ts b/frontend/src/metabase/transforms/pages/TransformIndexesPage/IndexEditorModal/utils.tsnew file mode 100644index 00000000000..a5bab306aee--- /dev/null+++ b/frontend/src/metabase/transforms/pages/TransformIndexesPage/IndexEditorModal/utils.ts@@ -0,0 +1,98 @@+import * as Yup from "yup";++import * as Errors from "metabase/utils/errors";+import type {+ IndexColumn,+ IndexField,+ IndexKind,+ StructuredIndex,+} from "metabase-types/api";++export type IndexFieldValue = string | number | boolean | IndexColumn[] | null;++export type IndexFormValues = Record<string, IndexFieldValue>;++function defaultFieldValue(field: IndexField): IndexFieldValue {+ switch (field.type) {+ case "boolean":+ return false;+ case "columns":+ return [];+ case "integer":+ return null;+ case "select":+ return field.options?.[0]?.value ?? "";+ default:+ return "";+ }+}++export function buildInitialValues(+ fields: IndexField[],+ structured?: StructuredIndex,+ carriedValues?: IndexFormValues,+): IndexFormValues {+ const source = structured as Record<string, IndexFieldValue> | undefined;+ return Object.fromEntries(+ fields.map((field) => [+ field.name,+ carriedValues?.[field.name] ??+ source?.[field.name] ??+ defaultFieldValue(field),+ ]),+ );+}++function getFieldSchema(field: IndexField): Yup.AnySchema {+ switch (field.type) {+ case "columns": {+ const schema = Yup.array().of(+ Yup.object({+ name: Yup.string().required(),+ direction: Yup.string().oneOf(["asc", "desc"]).optional(),+ }),+ );+ return field.required ? schema.min(1, Errors.required) : schema;+ }+ case "boolean":+ return Yup.boolean();+ case "integer": {+ const schema = Yup.number().nullable();+ return field.required ? schema.required(Errors.required) : schema;+ }+ default: {+ const schema = Yup.string();+ return field.required ? schema.required(Errors.required) : schema;+ }+ }+}++export function buildValidationSchema(fields: IndexField[]) {+ return Yup.object(+ Object.fromEntries(+ fields.map((field) => [field.name, getFieldSchema(field)]),+ ),+ );+}++export function toStructured(+ kind: IndexKind,+ fields: IndexField[],+ values: IndexFormValues,+): StructuredIndex {+ const structured: Record<string, IndexFieldValue> = { kind };+ for (const field of fields) {+ const value = values[field.name];+ if (field.type === "columns" && Array.isArray(value)) {+ structured[field.name] = field.directions+ ? value.map((column) => ({+ name: column.name,+ direction: column.direction ?? "asc",+ }))+ : value.map((column) => ({ name: column.name }));+ } else {+ structured[field.name] = value;+ }+ }+ return structured as StructuredIndex;+}diff --git a/frontend/src/metabase/transforms/pages/TransformIndexesPage/IndexPageActions.tsx b/frontend/src/metabase/transforms/pages/TransformIndexesPage/IndexPageActions.tsxnew file mode 100644index 00000000000..e1e497d9f8d--- /dev/null+++ b/frontend/src/metabase/transforms/pages/TransformIndexesPage/IndexPageActions.tsx@@ -0,0 +1,35 @@+import { t } from "ttag";++import { Button, Tooltip } from "metabase/ui";++export function IndexPageActions({+ readOnly = false,+ targetTableExists: hasTable,+ handleCreate,+ canCreate,+}: {+ readOnly: boolean | undefined;+ targetTableExists: boolean;+ handleCreate: () => void;+ canCreate: boolean;+}) {+ if (readOnly) {+ return null;+ }++ const createButton = (+ <Button variant="filled" disabled={!canCreate} onClick={handleCreate}>+ {t`Create index`}+ </Button>+ );++ const actions = hasTable ? (+ createButton+ ) : (+ <Tooltip label={t`Run the transform before adding indexes`}>+ {createButton}+ </Tooltip>+ );++ return actions;+}diff --git a/frontend/src/metabase/transforms/pages/TransformIndexesPage/NoIndexes.tsx b/frontend/src/metabase/transforms/pages/TransformIndexesPage/NoIndexes.tsxnew file mode 100644index 00000000000..e056b17cb0f--- /dev/null+++ b/frontend/src/metabase/transforms/pages/TransformIndexesPage/NoIndexes.tsx@@ -0,0 +1,18 @@+import { t } from "ttag";++import { Flex, Text } from "metabase/ui";++import TransformIndexesEmpty from "./assets/transform-indexes-empty.svg?component";++export function NoIndexes() {+ return (+ <Flex gap="md" direction="column" justify="center" align="center" mih={360}>+ <TransformIndexesEmpty aria-hidden />+ <Text+ c="text-secondary"+ maw={360}+ ta="center"+ >{t`Index the key columns of your transforms to make them faster and more efficient.`}</Text>+ </Flex>+ );+}diff --git a/frontend/src/metabase/transforms/pages/TransformIndexesPage/TransformIndexTable/IndexRowMenu.tsx b/frontend/src/metabase/transforms/pages/TransformIndexesPage/TransformIndexTable/IndexRowMenu.tsxnew file mode 100644index 00000000000..1730ca7ad92--- /dev/null+++ b/frontend/src/metabase/transforms/pages/TransformIndexesPage/TransformIndexTable/IndexRowMenu.tsx@@ -0,0 +1,53 @@+import type { MouseEvent } from "react";+import { t } from "ttag";++import { ActionIcon, Icon, Menu } from "metabase/ui";+import type { TableIndexEntry } from "metabase-types/api";++import { isManagedIndex, isPendingDeletion } from "./utils";++type IndexRowMenuProps = {+ index: TableIndexEntry;+ onEdit: (index: TableIndexEntry) => void;+ onDelete: (index: TableIndexEntry) => void;+};++export function IndexRowMenu({ index, onEdit, onDelete }: IndexRowMenuProps) {+ if (!isManagedIndex(index)) {+ return null;+ }++ const isDisabled = isPendingDeletion(index);++ function handleIconClick(event: MouseEvent) {+ event.preventDefault();+ event.stopPropagation();+ }++ return (+ <Menu position="bottom-end">+ <Menu.Target>+ <ActionIcon aria-label={t`Index actions`} onClick={handleIconClick}>+ <Icon name="ellipsis" />+ </ActionIcon>+ </Menu.Target>+ <Menu.Dropdown onClick={(event) => event.stopPropagation()}>+ <Menu.Item+ leftSection={<Icon name="pencil" />}+ onClick={() => onEdit(index)}+ disabled={isDisabled}+ >+ {t`Edit`}+ </Menu.Item>+ <Menu.Item+ c={isDisabled ? undefined : "danger"}+ leftSection={<Icon name="trash" />}+ onClick={() => onDelete(index)}+ disabled={isDisabled}+ >+ {t`Delete`}+ </Menu.Item>+ </Menu.Dropdown>+ </Menu>+ );+}diff --git a/frontend/src/metabase/transforms/pages/TransformIndexesPage/TransformIndexTable/TransformIndexTable.tsx b/frontend/src/metabase/transforms/pages/TransformIndexesPage/TransformIndexTable/TransformIndexTable.tsxnew file mode 100644index 00000000000..9db9f2e6adc--- /dev/null+++ b/frontend/src/metabase/transforms/pages/TransformIndexesPage/TransformIndexTable/TransformIndexTable.tsx@@ -0,0 +1,134 @@+import type { OnChangeFn, Row, SortingState } from "@tanstack/react-table";+import { useCallback, useMemo, useState } from "react";+import { t } from "ttag";++import { useListUsersQuery } from "metabase/api";+import { ListEmptyState } from "metabase/common/components/ListEmptyState";+import { useSetting } from "metabase/common/hooks";+import type { TreeTableColumnDef } from "metabase/ui";+import { TreeTable, useTreeTableInstance } from "metabase/ui";+import { isNullOrUndefined } from "metabase/utils/types";+import type { TableIndexEntry, UserId } from "metabase-types/api";++import { getColumns } from "./columns";+import type { IndexRow } from "./types";+import { getIndexKey, isManagedIndex, isPendingDeletion } from "./utils";++type TransformIndexTableProps = {+ indexes: TableIndexEntry[];+ kindLabels: Map<string, string>;+ readOnly?: boolean;+ onEdit: (index: TableIndexEntry) => void;+ onDelete: (index: TableIndexEntry) => void;+};++const DEFAULT_SORTING: SortingState = [{ id: "name", desc: false }];++export function TransformIndexTable({+ indexes,+ kindLabels,+ readOnly,+ onEdit,+ onDelete,+}: TransformIndexTableProps) {+ const systemTimezone = useSetting("system-timezone");+ const { data: usersResponse } = useListUsersQuery();+ const [sorting, setSorting] = useState<SortingState>(DEFAULT_SORTING);++ const usersById = useMemo(() => {+ const map = new Map<UserId, string>();+ for (const user of usersResponse?.data ?? []) {+ map.set(user.id, user.common_name);+ }+ return map;+ }, [usersResponse]);++ const rows = useMemo<IndexRow[]>(+ () =>+ indexes.map((index, position) => {+ const userId = index.request?.created_by;+ const modifiedBy = isNullOrUndefined(userId)+ ? ""+ : (usersById.get(userId) ?? "");+ return {+ ...index,+ id: getIndexKey(index, position),+ modifiedBy,+ };+ }),+ [indexes, usersById],+ );++ const columns = useMemo(+ () =>+ getColumns({+ systemTimezone,+ kindLabels,+ actions: readOnly ? undefined : { onEdit, onDelete },+ }),+ [systemTimezone, kindLabels, readOnly, onEdit, onDelete],+ );++ const handleRowClick = useCallback(+ (row: Row<IndexRow>) => {+ const index = row.original;+ if (!readOnly && isManagedIndex(index) && !isPendingDeletion(index)) {+ onEdit(index);+ }+ },+ [readOnly, onEdit],+ );++ // Trigger remount and reflow when status column changes.+ // This ensures that column widths are correctly measured after a status change.+ const measureKey = useMemo(+ () => indexes.map(({ request }) => request?.status).join(","),+ [indexes],+ );++ return (+ <TransformIndexTableBody+ key={measureKey}+ rows={rows}+ columns={columns}+ sorting={sorting}+ onSortingChange={setSorting}+ onRowClick={handleRowClick}+ />+ );+}++type TransformIndexTableBodyProps = {+ rows: IndexRow[];+ columns: TreeTableColumnDef<IndexRow>[];+ sorting: SortingState;+ onSortingChange: OnChangeFn<SortingState>;+ onRowClick: (row: Row<IndexRow>) => void;+};++function TransformIndexTableBody({+ rows,+ columns,+ sorting,+ onSortingChange,+ onRowClick,+}: TransformIndexTableBodyProps) {+ const treeTableInstance = useTreeTableInstance<IndexRow>({+ data: rows,+ columns,+ getNodeId: (row) => row.id,+ enableSorting: true,+ sorting,+ onSortingChange,+ });++ return (+ <TreeTable+ instance={treeTableInstance}+ hierarchical={false}+ emptyState={<ListEmptyState label={t`No indexes yet`} />}+ ariaLabel={t`Transform indexes`}+ onRowClick={onRowClick}+ />+ );+}diff --git a/frontend/src/metabase/transforms/pages/TransformIndexesPage/TransformIndexTable/TransformIndexTable.unit.spec.tsx b/frontend/src/metabase/transforms/pages/TransformIndexesPage/TransformIndexTable/TransformIndexTable.unit.spec.tsxnew file mode 100644index 00000000000..ec53712cb6e--- /dev/null+++ b/frontend/src/metabase/transforms/pages/TransformIndexesPage/TransformIndexTable/TransformIndexTable.unit.spec.tsx@@ -0,0 +1,331 @@+import userEvent from "@testing-library/user-event";++import { setupUsersEndpoints } from "__support__/server-mocks";+import {+ getIcon,+ mockGetBoundingClientRect,+ queryIcon,+ renderWithProviders,+ screen,+ waitForLoaderToBeRemoved,+ within,+} from "__support__/ui";+import type { TableIndexEntry, UserListResult } from "metabase-types/api";+import {+ createMockTableIndexEntry,+ createMockTableIndexRequest,+ createMockUserListResult,+} from "metabase-types/api/mocks";++import { TransformIndexTable } from "./TransformIndexTable";++type SetupOpts = {+ indexes?: TableIndexEntry[];+ kindLabels?: Map<string, string>;+ users?: UserListResult[];+ readOnly?: boolean;+};++function setup({+ indexes = [],+ kindLabels = new Map(),+ users = [],+ readOnly = false,+}: SetupOpts = {}) {+ mockGetBoundingClientRect({ width: 1000, height: 600 });+ setupUsersEndpoints(users);++ const onEdit = jest.fn();+ const onDelete = jest.fn();+ renderWithProviders(+ <TransformIndexTable+ indexes={indexes}+ kindLabels={kindLabels}+ readOnly={readOnly}+ onEdit={onEdit}+ onDelete={onDelete}+ />,+ );++ return { onEdit, onDelete };+}++describe("TransformIndexTable", () => {+ it("renders the column headers", async () => {+ setup({ indexes: [createMockTableIndexEntry()] });+ await waitForLoaderToBeRemoved();++ for (const header of [+ "Name",+ "Type",+ "Columns",+ "Source",+ "Status",+ "Last modified by",+ "Last run",+ ]) {+ expect(screen.getByText(header)).toBeInTheDocument();+ }+ });++ it("renders the index name, type and columns", async () => {+ setup({+ indexes: [+ createMockTableIndexEntry({+ name: "idx_orders",+ kind: "gin",+ key_columns: ["total", "created_at"],+ }),+ ],+ });+ await waitForLoaderToBeRemoved();++ expect(screen.getByText("idx_orders")).toBeInTheDocument();+ expect(screen.getByText("gin")).toBeInTheDocument();+ expect(screen.getByText("total, created_at")).toBeInTheDocument();+ });++ it("shows the driver-provided label for the index kind, falling back to the raw kind", async () => {+ setup({+ kindLabels: new Map([["btree", "B-Tree"]]),+ indexes: [+ createMockTableIndexEntry({ name: "idx_btree", kind: "btree" }),+ createMockTableIndexEntry({ name: "idx_gin", kind: "gin" }),+ ],+ });+ await waitForLoaderToBeRemoved();++ expect(screen.getByText("B-Tree")).toBeInTheDocument();+ expect(screen.getByText("gin")).toBeInTheDocument();+ });++ it("falls back to the index kind when the index has no name", async () => {+ setup({+ indexes: [createMockTableIndexEntry({ name: null, kind: "distkey" })],+ });+ await waitForLoaderToBeRemoved();++ const table = screen.getByRole("treegrid", {+ name: "Transform indexes",+ });+ // The kind shows in both the Name (fallback) and Type columns.+ expect(within(table).getAllByText("distkey")).toHaveLength(2);+ });++ it("labels metabase-managed indexes as 'Managed'", async () => {+ setup({+ indexes: [createMockTableIndexEntry({ metabase_managed: true })],+ });+ await waitForLoaderToBeRemoved();++ expect(screen.getByText("Managed")).toBeInTheDocument();+ });++ it("labels non-managed indexes as 'Unmanaged'", async () => {+ setup({+ indexes: [createMockTableIndexEntry({ metabase_managed: false })],+ });+ await waitForLoaderToBeRemoved();++ expect(screen.getByText("Unmanaged")).toBeInTheDocument();+ });++ it("formats the request status", async () => {+ setup({+ indexes: [+ createMockTableIndexEntry({+ name: "idx_pending",+ request: createMockTableIndexRequest({+ id: 1,+ status: "create-pending",+ }),+ }),+ createMockTableIndexEntry({+ name: "idx_removing",+ request: createMockTableIndexRequest({+ id: 2,+ status: "delete-pending",+ }),+ }),+ ],+ });+ await waitForLoaderToBeRemoved();++ expect(screen.getByText("Pending")).toBeInTheDocument();+ expect(screen.getByText("Removing")).toBeInTheDocument();+ });++ it("shows an info tooltip for pending statuses", async () => {+ setup({+ indexes: [+ createMockTableIndexEntry({+ request: createMockTableIndexRequest({ status: "create-pending" }),+ }),+ ],+ });+ await waitForLoaderToBeRemoved();++ expect(screen.getByText("Pending")).toBeInTheDocument();+ await userEvent.hover(getIcon("info_outline"));+ expect(+ await screen.findByText(+ "Changes will be applied the next time the transform runs",+ ),+ ).toBeInTheDocument();+ });++ it("does not show the pending info icon for terminal statuses", async () => {+ setup({+ indexes: [+ createMockTableIndexEntry({+ request: createMockTableIndexRequest({+ status: "succeeded",+ error_message: null,+ }),+ }),+ ],+ });+ await waitForLoaderToBeRemoved();++ expect(screen.getByText("Succeeded")).toBeInTheDocument();+ expect(queryIcon("info_outline")).not.toBeInTheDocument();+ });++ it("resolves the last modified by user name", async () => {+ setup({+ users: [createMockUserListResult({ id: 7, common_name: "Ed Winters" })],+ indexes: [+ createMockTableIndexEntry({+ request: createMockTableIndexRequest({ created_by: 7 }),+ }),+ ],+ });++ expect(await screen.findByText("Ed Winters")).toBeInTheDocument();+ });++ it("shows 'Never' when the index has not been run", async () => {+ setup({+ indexes: [+ createMockTableIndexEntry({+ request: createMockTableIndexRequest({ last_executed_at: null }),+ }),+ ],+ });+ await waitForLoaderToBeRemoved();++ expect(screen.getByText("Never")).toBeInTheDocument();+ });++ it("offers edit and delete for a managed index with a request", async () => {+ const index = createMockTableIndexEntry({+ metabase_managed: true,+ request: createMockTableIndexRequest({ id: 5 }),+ });+ const { onEdit, onDelete } = setup({ indexes: [index] });+ await waitForLoaderToBeRemoved();++ await userEvent.click(+ screen.getByRole("button", { name: "Index actions" }),+ );+ await userEvent.click(await screen.findByText("Edit"));+ expect(onEdit).toHaveBeenCalledWith(+ expect.objectContaining({ name: "btree" }),+ );++ await userEvent.click(+ screen.getByRole("button", { name: "Index actions" }),+ );+ await userEvent.click(await screen.findByText("Delete"));+ expect(onDelete).toHaveBeenCalledWith(+ expect.objectContaining({ name: "btree" }),+ );+ });++ it("opens the editor only when clicking an editable managed index row", async () => {+ const managed = createMockTableIndexEntry({+ name: "idx_managed",+ metabase_managed: true,+ request: createMockTableIndexRequest({ id: 5 }),+ });+ const unmanaged = createMockTableIndexEntry({+ name: "idx_unmanaged",+ metabase_managed: false,+ request: undefined,+ });+ const removing = createMockTableIndexEntry({+ name: "idx_removing",+ metabase_managed: true,+ request: createMockTableIndexRequest({ id: 6, status: "delete-pending" }),+ });+ const { onEdit } = setup({ indexes: [managed, unmanaged, removing] });+ await waitForLoaderToBeRemoved();++ await userEvent.click(screen.getByText("idx_unmanaged"));+ await userEvent.click(screen.getByText("idx_removing"));+ expect(onEdit).not.toHaveBeenCalled();++ // opening the row menu must not bubble into a row click+ const managedRow = screen.getByRole("row", { name: /idx_managed/ });+ await userEvent.click(+ within(managedRow).getByRole("button", { name: "Index actions" }),+ );+ expect(await screen.findByText("Edit")).toBeInTheDocument();+ expect(onEdit).not.toHaveBeenCalled();+ await userEvent.keyboard("{Escape}");++ await userEvent.click(screen.getByText("idx_managed"));+ expect(onEdit).toHaveBeenCalledTimes(1);+ expect(onEdit).toHaveBeenCalledWith(+ expect.objectContaining({ name: "idx_managed" }),+ );+ });++ it("does not open the editor when clicking a row in read-only mode", async () => {+ const index = createMockTableIndexEntry({+ name: "idx_readonly",+ metabase_managed: true,+ request: createMockTableIndexRequest({ id: 5 }),+ });+ const { onEdit } = setup({ indexes: [index], readOnly: true });+ await waitForLoaderToBeRemoved();++ await userEvent.click(screen.getByText("idx_readonly"));+ expect(onEdit).not.toHaveBeenCalled();+ });++ it("does not offer a menu for unmanaged indexes", async () => {+ setup({+ indexes: [+ createMockTableIndexEntry({+ metabase_managed: false,+ request: undefined,+ }),+ ],+ });+ await waitForLoaderToBeRemoved();++ expect(screen.getByText("Unmanaged")).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Index actions" }),+ ).not.toBeInTheDocument();+ });++ it("does not render the actions column when read-only", async () => {+ setup({+ readOnly: true,+ indexes: [+ createMockTableIndexEntry({+ metabase_managed: true,+ request: createMockTableIndexRequest({ id: 5 }),+ }),+ ],+ });+ await waitForLoaderToBeRemoved();++ expect(screen.getByText("Managed")).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Index actions" }),+ ).not.toBeInTheDocument();+ });+});diff --git a/frontend/src/metabase/transforms/pages/TransformIndexesPage/TransformIndexTable/columns.tsx b/frontend/src/metabase/transforms/pages/TransformIndexesPage/TransformIndexTable/columns.tsxnew file mode 100644index 00000000000..0df9d143e75--- /dev/null+++ b/frontend/src/metabase/transforms/pages/TransformIndexesPage/TransformIndexTable/columns.tsx@@ -0,0 +1,164 @@+import { t } from "ttag";++import { parseTimestampWithTimezone } from "metabase/transforms/utils";+import type { TreeTableColumnDef } from "metabase/ui";+import { Ellipsified, Flex, Group, Icon, Tooltip } from "metabase/ui";+import { EMPTY_CELL_PLACEHOLDER } from "metabase/utils/constants";+import type { TableIndexEntry } from "metabase-types/api";++import { IndexRowMenu } from "./IndexRowMenu";+import type { IndexRow } from "./types";+import { formatStatus, getIndexName, isPendingStatus } from "./utils";++const ACTIONS_COLUMN_WIDTH = 56;++type Actions = {+ onEdit: (index: TableIndexEntry) => void;+ onDelete: (index: TableIndexEntry) => void;+};++type ColumnsProps = {+ systemTimezone: string | undefined;+ kindLabels: Map<string, string>;+ actions: Actions | undefined;+};++export function getColumns({+ systemTimezone,+ kindLabels,+ actions,+}: ColumnsProps): TreeTableColumnDef<IndexRow>[] {+ const columns: TreeTableColumnDef<IndexRow>[] = [+ {+ id: "name",+ header: t`Name`,+ minWidth: "auto",+ maxAutoWidth: 240,+ enableSorting: true,+ accessorFn: (index) => getIndexName(index),+ cell: ({ getValue }) => (+ <Group gap="sm" wrap="nowrap">+ <Icon name="table_index" c="brand" />+ <Ellipsified>{String(getValue())}</Ellipsified>+ </Group>+ ),+ },+ {+ id: "type",+ header: t`Type`,+ width: "auto",+ enableSorting: true,+ accessorFn: (index) => kindLabels.get(index.kind) ?? index.kind,+ cell: ({ getValue }) => <Ellipsified>{String(getValue())}</Ellipsified>,+ },+ {+ id: "columns",+ header: t`Columns`,+ width: "auto",+ maxAutoWidth: 240,+ enableSorting: true,+ accessorFn: (index) => index.key_columns.join(", "),+ cell: ({ getValue }) => {+ const value = String(getValue());+ return value.length > 0 ? (+ <Ellipsified>{value}</Ellipsified>+ ) : (+ EMPTY_CELL_PLACEHOLDER+ );+ },+ },+ {+ id: "source",+ header: t`Source`,+ width: "auto",+ enableSorting: true,+ accessorFn: (index) =>+ index.metabase_managed ? t`Managed` : t`Unmanaged`,+ cell: ({ getValue }) => <Ellipsified>{String(getValue())}</Ellipsified>,+ },+ {+ id: "status",+ header: t`Status`,+ width: "auto",+ enableSorting: true,+ accessorFn: (index) => formatStatus(index.request?.status),+ cell: ({ row, getValue }) => {+ const request = row.original.request;+ const errorMessage = request?.error_message;+ return (+ <Group gap="sm" wrap="nowrap">+ <Ellipsified>{String(getValue())}</Ellipsified>+ {errorMessage != null && (+ <Tooltip label={errorMessage}>+ <Icon name="info_outline" c="text-secondary" />+ </Tooltip>+ )}+ {isPendingStatus(request?.status) && (+ <Tooltip+ label={t`Changes will be applied the next time the transform runs`}+ >+ <Icon name="info_outline" c="text-secondary" />+ </Tooltip>+ )}+ </Group>+ );+ },+ },+ {+ id: "modified-by",+ header: t`Last modified by`,+ width: "auto",+ maxAutoWidth: 200,+ enableSorting: true,+ accessorFn: (index) => index.modifiedBy,+ cell: ({ getValue }) => {+ const value = String(getValue());+ return value.length > 0 ? (+ <Ellipsified>{value}</Ellipsified>+ ) : (+ EMPTY_CELL_PLACEHOLDER+ );+ },+ },+ {+ id: "last-run",+ header: t`Last run`,+ width: "auto",+ enableSorting: true,+ accessorFn: (index) => index.request?.last_executed_at ?? null,+ cell: ({ getValue }) => {+ const lastExecutedAt = getValue<string | null>();+ if (lastExecutedAt == null) {+ return t`Never`;+ }+ return (+ <Ellipsified>+ {parseTimestampWithTimezone(lastExecutedAt, systemTimezone).format(+ "lll",+ )}+ </Ellipsified>+ );+ },+ },+ ];++ if (actions != null) {+ columns.push({+ id: "actions",+ header: "",+ width: ACTIONS_COLUMN_WIDTH,+ enableSorting: false,+ cell: ({ row }) => (+ <Flex justify="center">+ <IndexRowMenu+ index={row.original}+ onEdit={actions.onEdit}+ onDelete={actions.onDelete}+ />+ </Flex>+ ),+ });+ }++ return columns;+}diff --git a/frontend/src/metabase/transforms/pages/TransformIndexesPage/TransformIndexTable/index.ts b/frontend/src/metabase/transforms/pages/TransformIndexesPage/TransformIndexTable/index.tsnew file mode 100644index 00000000000..b96e61b4bc6--- /dev/null+++ b/frontend/src/metabase/transforms/pages/TransformIndexesPage/TransformIndexTable/index.ts@@ -0,0 +1 @@+export * from "./TransformIndexTable";diff --git a/frontend/src/metabase/transforms/pages/TransformIndexesPage/TransformIndexTable/types.ts b/frontend/src/metabase/transforms/pages/TransformIndexesPage/TransformIndexTable/types.tsnew file mode 100644index 00000000000..09eff0c0618--- /dev/null+++ b/frontend/src/metabase/transforms/pages/TransformIndexesPage/TransformIndexTable/types.ts@@ -0,0 +1,8 @@+import type { TableIndexEntry } from "metabase-types/api";++type IndexRowId = string;++export type IndexRow = TableIndexEntry & {+ id: IndexRowId;+ modifiedBy: string;+};diff --git a/frontend/src/metabase/transforms/pages/TransformIndexesPage/TransformIndexTable/utils.ts b/frontend/src/metabase/transforms/pages/TransformIndexesPage/TransformIndexTable/utils.tsnew file mode 100644index 00000000000..41a53d5cbf8--- /dev/null+++ b/frontend/src/metabase/transforms/pages/TransformIndexesPage/TransformIndexTable/utils.ts@@ -0,0 +1,66 @@+import { match } from "ts-pattern";+import { t } from "ttag";++import { EMPTY_CELL_PLACEHOLDER } from "metabase/utils/constants";+import { getObjectKeys } from "metabase/utils/objects";+import type {+ RequestableIndexes,+ TableIndexEntry,+ TableIndexRequestStatus,+} from "metabase-types/api";++export function getKindLabels(+ requestableIndexes: RequestableIndexes | null | undefined,+): Map<string, string> {+ const labels = new Map<string, string>();+ for (const kind of getObjectKeys(requestableIndexes ?? {})) {+ labels.set(kind, requestableIndexes?.[kind]?.["display-name"] ?? kind);+ }+ return labels;+}++export function getIndexName(index: TableIndexEntry): string {+ return index.name ?? index.kind;+}++export function getIndexKey(index: TableIndexEntry, position: number): string {+ if (index.request?.id !== undefined) {+ return `request-${index.request.id}`;+ }++ return `index-${getIndexName(index)}-${position}`;+}++export function isManagedIndex(index: TableIndexEntry): boolean {+ return index.metabase_managed && index.request?.id !== undefined;+}++export function isPendingDeletion(index: TableIndexEntry): boolean {+ return index.request?.status === "delete-pending";+}++export function isPendingStatus(+ status: TableIndexRequestStatus | undefined,+): boolean {+ return (+ status === "create-pending" ||+ status === "update-pending" ||+ status === "delete-pending"+ );+}++export function formatStatus(+ status: TableIndexRequestStatus | undefined,+): string {+ if (status === undefined) {+ return EMPTY_CELL_PLACEHOLDER;+ }++ return match(status)+ .with("create-pending", "update-pending", () => t`Pending`)+ .with("delete-pending", () => t`Removing`)+ .with("running", () => t`Running`)+ .with("succeeded", () => t`Succeeded`)+ .with("failed", () => t`Failed`)+ .exhaustive();+}diff --git a/frontend/src/metabase/transforms/pages/TransformIndexesPage/TransformIndexesPage.tsx b/frontend/src/metabase/transforms/pages/TransformIndexesPage/TransformIndexesPage.tsxnew file mode 100644index 00000000000..28b8cefe047--- /dev/null+++ b/frontend/src/metabase/transforms/pages/TransformIndexesPage/TransformIndexesPage.tsx@@ -0,0 +1,164 @@+import { useState } from "react";+import { t } from "ttag";++import {+ skipToken,+ useDeleteTableIndexMutation,+ useGetTransformQuery,+ useListTableIndexesQuery,+} from "metabase/api";+import { getErrorMessage } from "metabase/api/utils";+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { PageContainer } from "metabase/common/data-studio/components/PageContainer";+import { TitleSection } from "metabase/common/data-studio/components/TitleSection";+import { useToast } from "metabase/common/hooks";+import { useConfirmation } from "metabase/common/hooks/use-confirmation";+import { useTransformPermissions } from "metabase/transforms/hooks/use-transform-permissions";+import { Center } from "metabase/ui";+import * as Urls from "metabase/urls";+import { isNullOrUndefined } from "metabase/utils/types";+import type { TableIndexEntry, Transform } from "metabase-types/api";++import { TransformHeader } from "../../components/TransformHeader";++import { IndexEditorModal } from "./IndexEditorModal/IndexEditorModal";+import { IndexPageActions } from "./IndexPageActions";+import { NoIndexes } from "./NoIndexes";+import { TransformIndexTable } from "./TransformIndexTable";+import { getKindLabels } from "./TransformIndexTable/utils";++type TransformIndexesPageProps = {+ params: {+ transformId?: string;+ };+};++export function TransformIndexesPage({ params }: TransformIndexesPageProps) {+ const transformId = Urls.extractEntityId(params.transformId);+ const {+ data: transform,+ isLoading: isLoadingTransform,+ error: transformError,+ } = useGetTransformQuery(transformId ?? skipToken);+ const { readOnly, isLoadingDatabases, databasesError } =+ useTransformPermissions({ transform });+ const isLoading = isLoadingTransform || isLoadingDatabases;+ const error = transformError || databasesError;++ if (transform === undefined || isLoading || !isNullOrUndefined(error)) {+ return (+ <Center h="100%">+ <LoadingAndErrorWrapper loading={isLoading} error={error} />+ </Center>+ );+ }++ return (+ <PageContainer data-testid="transforms-indexes-content">+ <TransformHeader transform={transform} readOnly={readOnly} />+ <TransformIndexesContent transform={transform} readOnly={readOnly} />+ </PageContainer>+ );+}++function TransformIndexesContent({+ transform,+ readOnly = false,+}: {+ transform: Transform;+ readOnly: boolean | undefined;+}) {+ const {+ data: indexes = [],+ isLoading,+ error,+ } = useListTableIndexesQuery({ "transform-id": transform.id });+ const { deleteIndex, confirmationModal } = useDeleteIndex();+ const targetTableExists = transform.table != null;+ const hasRequestableIndexes =+ Object.keys(transform.requestable_indexes ?? {}).length > 0;+ const canCreate = targetTableExists && hasRequestableIndexes && !readOnly;+ const [editorState, setEditorState] = useState<{+ index?: TableIndexEntry;+ } | null>(null);++ const handleCreate = () => setEditorState({});+ const handleEdit = (index: TableIndexEntry) => setEditorState({ index });++ if (isLoading || !isNullOrUndefined(error)) {+ return (+ <Center flex={1}>+ <LoadingAndErrorWrapper loading={isLoading} error={error} />+ </Center>+ );+ }++ return (+ <>+ <TitleSection+ label={t`Indexes`}+ actions={+ <IndexPageActions+ readOnly={readOnly}+ targetTableExists={targetTableExists}+ handleCreate={handleCreate}+ canCreate={canCreate}+ />+ }+ >+ {indexes.length === 0 ? (+ <NoIndexes />+ ) : (+ <TransformIndexTable+ indexes={indexes}+ kindLabels={getKindLabels(transform.requestable_indexes)}+ readOnly={readOnly}+ onEdit={handleEdit}+ onDelete={deleteIndex}+ />+ )}+ </TitleSection>+ {editorState != null && (+ <IndexEditorModal+ transform={transform}+ index={editorState.index}+ onClose={() => setEditorState(null)}+ />+ )}+ {confirmationModal}+ </>+ );+}++function useDeleteIndex() {+ const [sendToast] = useToast();+ const [deleteTableIndex] = useDeleteTableIndexMutation();+ const { modalContent: confirmationModal, show: showConfirmation } =+ useConfirmation();++ function deleteIndex(index: TableIndexEntry) {+ const requestId = index.request?.id;+ if (requestId == null) {+ return;+ }+ showConfirmation({+ title: t`Delete this index?`,+ message: t`This removes the index from the warehouse.`,+ confirmButtonText: t`Delete`,+ confirmButtonProps: { color: "danger" },+ onConfirm: async () => {+ try {+ await deleteTableIndex(requestId).unwrap();+ sendToast({ message: t`Index deleted` });+ } catch (deleteError) {+ sendToast({+ message: getErrorMessage(deleteError, t`Failed to delete index`),+ icon: "warning",+ });+ }+ },+ });+ }++ return { deleteIndex, confirmationModal };+}diff --git a/frontend/src/metabase/transforms/pages/TransformIndexesPage/TransformIndexesPage.unit.spec.tsx b/frontend/src/metabase/transforms/pages/TransformIndexesPage/TransformIndexesPage.unit.spec.tsxnew file mode 100644index 00000000000..b8dc97f9dcc--- /dev/null+++ b/frontend/src/metabase/transforms/pages/TransformIndexesPage/TransformIndexesPage.unit.spec.tsx@@ -0,0 +1,168 @@+import {+ setupCollectionByIdEndpoint,+ setupDatabasesEndpoints,+ setupGetTransformEndpoint,+ setupListTableIndexesEndpoint,+ setupUserMetabotPermissionsEndpoint,+ setupUsersEndpoints,+} from "__support__/server-mocks";+import {+ mockGetBoundingClientRect,+ renderWithProviders,+ screen,+ waitForLoaderToBeRemoved,+} from "__support__/ui";+import { Route } from "metabase/router";+import * as Urls from "metabase/urls";+import type {+ TableIndexEntry,+ Transform,+ UserListResult,+} from "metabase-types/api";+import {+ createMockCollection,+ createMockDatabase,+ createMockTableIndexEntry,+ createMockTableIndexRequest,+ createMockTransform,+ createMockUserListResult,+} from "metabase-types/api/mocks";++import { TransformIndexesPage } from "./TransformIndexesPage";++type SetupOpts = {+ transform?: Transform;+ indexes?: TableIndexEntry[];+ users?: UserListResult[];+};++function setup({+ transform = createMockTransform({ id: 1, name: "Test Transform" }),+ indexes = [],+ users = [],+}: SetupOpts = {}) {+ mockGetBoundingClientRect({ width: 1000, height: 600 });+ setupDatabasesEndpoints([+ createMockDatabase({ id: 1, transforms_permissions: "write" }),+ ]);+ setupCollectionByIdEndpoint({+ collections: [createMockCollection({ id: "root" })],+ });+ setupUserMetabotPermissionsEndpoint();+ setupUsersEndpoints(users);++ setupGetTransformEndpoint(transform);+ setupListTableIndexesEndpoint(transform.id, indexes);++ const initialRoute = Urls.transformIndexes(transform.id);+ const path = initialRoute.replace(`/${transform.id}/`, "/:transformId/");++ renderWithProviders(<Route path={path} component={TransformIndexesPage} />, {+ withRouter: true,+ initialRoute,+ });++ return { transform };+}++describe("TransformIndexesPage", () => {+ it("renders the empty state when there are no indexes", async () => {+ setup({ indexes: [] });+ await waitForLoaderToBeRemoved();++ expect(+ screen.getByText(+ "Index the key columns of your transforms to make them faster and more efficient.",+ ),+ ).toBeInTheDocument();+ });++ it("renders the list of indexes", async () => {+ setup({+ indexes: [+ createMockTableIndexEntry({+ name: "idx_orders_id",+ kind: "btree",+ key_columns: ["id"],+ request: createMockTableIndexRequest({ id: 1 }),+ }),+ createMockTableIndexEntry({+ name: "idx_orders_total",+ kind: "gin",+ key_columns: ["total"],+ request: createMockTableIndexRequest({ id: 2 }),+ }),+ ],+ });+ await waitForLoaderToBeRemoved();++ expect(screen.getByText("idx_orders_id")).toBeInTheDocument();+ expect(screen.getByText("idx_orders_total")).toBeInTheDocument();+ });++ it("renders the index columns, type, source and status", async () => {+ setup({+ indexes: [+ createMockTableIndexEntry({+ name: "idx_city_country",+ kind: "btree",+ metabase_managed: true,+ key_columns: ["City name", "Country"],+ request: createMockTableIndexRequest({ status: "create-pending" }),+ }),+ ],+ });+ await waitForLoaderToBeRemoved();++ expect(screen.getByText("idx_city_country")).toBeInTheDocument();+ expect(screen.getByText("btree")).toBeInTheDocument();+ expect(screen.getByText("City name, Country")).toBeInTheDocument();+ expect(screen.getByText("Managed")).toBeInTheDocument();+ expect(screen.getByText("Pending")).toBeInTheDocument();+ });++ it("resolves the last modified by user name", async () => {+ setup({+ users: [createMockUserListResult({ id: 7, common_name: "Maz Ameli" })],+ indexes: [+ createMockTableIndexEntry({+ name: "idx_orders_id",+ request: createMockTableIndexRequest({ created_by: 7 }),+ }),+ ],+ });+ await waitForLoaderToBeRemoved();++ expect(await screen.findByText("Maz Ameli")).toBeInTheDocument();+ });++ it("shows 'Never' when the index has not been run", async () => {+ setup({+ indexes: [+ createMockTableIndexEntry({+ name: "idx_orders_id",+ request: createMockTableIndexRequest({ last_executed_at: null }),+ }),+ ],+ });+ await waitForLoaderToBeRemoved();++ expect(screen.getByText("Never")).toBeInTheDocument();+ });++ it("falls back to the index kind when the index has no name", async () => {+ setup({+ indexes: [+ createMockTableIndexEntry({+ name: null,+ kind: "distkey",+ request: createMockTableIndexRequest({ status: "create-pending" }),+ }),+ ],+ });+ await waitForLoaderToBeRemoved();++ // The kind appears in both the Name (fallback) and Type columns.+ expect(screen.getAllByText("distkey")).toHaveLength(2);+ });+});diff --git a/frontend/src/metabase/transforms/pages/TransformIndexesPage/assets/transform-indexes-empty.svg b/frontend/src/metabase/transforms/pages/TransformIndexesPage/assets/transform-indexes-empty.svgnew file mode 100644index 00000000000..d4ce0ac3609--- /dev/null+++ b/frontend/src/metabase/transforms/pages/TransformIndexesPage/assets/transform-indexes-empty.svg@@ -0,0 +1,7 @@+<svg width="96" height="96" viewBox="0 0 96 96" fill="none" xmlns="http://www.w3.org/2000/svg">+<circle cx="48" cy="48" r="48" fill="#F6F7F8"/>+<path d="M57 41H47" stroke="#071722" stroke-opacity="0.51" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>+<path d="M57 48H47" stroke="#071722" stroke-opacity="0.51" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>+<path d="M57 55H47" stroke="#071722" stroke-opacity="0.51" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>+<path d="M39 44L43 48L39 52" stroke="#071722" stroke-opacity="0.51" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>+</svg>diff --git a/frontend/src/metabase/transforms/pages/TransformIndexesPage/index.ts b/frontend/src/metabase/transforms/pages/TransformIndexesPage/index.tsnew file mode 100644index 00000000000..ce00672165b--- /dev/null+++ b/frontend/src/metabase/transforms/pages/TransformIndexesPage/index.ts@@ -0,0 +1 @@+export * from "./TransformIndexesPage";diff --git a/frontend/src/metabase/transforms/routes.tsx b/frontend/src/metabase/transforms/routes.tsxindex b1a425de392..138983e65eb 100644--- a/frontend/src/metabase/transforms/routes.tsx+++ b/frontend/src/metabase/transforms/routes.tsx@@ -17,6 +17,7 @@ import {} from "./pages/NewTransformPage";import { RunListPage } from "./pages/RunListPage";import { TransformDependenciesPage } from "./pages/TransformDependenciesPage";+import { TransformIndexesPage } from "./pages/TransformIndexesPage";import { TransformListPage } from "./pages/TransformListPage";import { TransformQueryPage } from "./pages/TransformQueryPage";import { TransformRunPage } from "./pages/TransformRunPage";@@ -42,6 +43,7 @@ export function getDataStudioTransformRoutes() {<Route path=":transformId/edit" component={TransformQueryPage} /><Route path=":transformId/run" component={TransformRunPage} /><Route path=":transformId/settings" component={TransformSettingsPage} />+ <Route path=":transformId/indexes" component={TransformIndexesPage} />{PLUGIN_TRANSFORMS_PYTHON.getInspectorRoutes()}{PLUGIN_DEPENDENCIES.isEnabled && (<Routediff --git a/frontend/src/metabase/ui/components/data-display/TreeTable/hooks/useColumnSizing.tsx b/frontend/src/metabase/ui/components/data-display/TreeTable/hooks/useColumnSizing.tsxindex f26aac3de34..b5a92485435 100644--- a/frontend/src/metabase/ui/components/data-display/TreeTable/hooks/useColumnSizing.tsx+++ b/frontend/src/metabase/ui/components/data-display/TreeTable/hooks/useColumnSizing.tsx@@ -324,7 +324,14 @@ function MeasureContent<TData extends TreeNodeData>({>{typeof column.header === "string" && (<div data-measure-header style={{ whiteSpace: "nowrap" }}>- <SortableHeaderPill name={column.header} />+ <SortableHeaderPill+ name={column.header}+ sort={+ table.getColumn(column.id)?.getCanSort()+ ? "desc"+ : undefined+ }+ /></div>)}{rowsToMeasure.map((row) => {diff --git a/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts b/frontend/src/metabase/ui/components/icons/Icon/icons/index.tsindex 764c49777a3..e2841ceab25 100644--- a/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts+++ b/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts@@ -528,6 +528,8 @@ import table_component from "./table.svg?component";import table_source from "./table.svg?source";import table2_component from "./table2.svg?component";import table2_source from "./table2.svg?source";+import table_index_component from "./table_index.svg?component";+import table_index_source from "./table_index.svg?source";import test_tube_component from "./test_tube.svg?component";import test_tube_source from "./test_tube.svg?source";import text_bold_component from "./text_bold.svg?component";@@ -1633,6 +1635,10 @@ export const Icons: Record<IconName, { component: React.VFC; source: string }> =component: table2_component,source: table2_source,},+ table_index: {+ component: table_index_component,+ source: table_index_source,+ },text_bold: {component: text_bold_component,source: text_bold_source,diff --git a/frontend/src/metabase/ui/components/icons/Icon/icons/table_index.svg b/frontend/src/metabase/ui/components/icons/Icon/icons/table_index.svgnew file mode 100644index 00000000000..8f8a80c177a--- /dev/null+++ b/frontend/src/metabase/ui/components/icons/Icon/icons/table_index.svg@@ -0,0 +1,6 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="currentColor">+<path d="M14.0002 3.33331H7.3335" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>+<path d="M14.0002 8H7.3335" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>+<path d="M14.0002 12.6667H7.3335" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>+<path d="M2 5.33331L4.66667 7.99998L2 10.6666" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>+</svg>diff --git a/frontend/src/metabase/metadata/components/FieldVisibilityPicker/FieldVisibilityPicker.module.css b/frontend/src/metabase/ui/components/inputs/Select/SelectItem/SelectItemWithDescription.module.csssimilarity index 100%rename from frontend/src/metabase/metadata/components/FieldVisibilityPicker/FieldVisibilityPicker.module.cssrename to frontend/src/metabase/ui/components/inputs/Select/SelectItem/SelectItemWithDescription.module.cssdiff --git a/frontend/src/metabase/ui/components/inputs/Select/SelectItem/SelectItemWithDescription.tsx b/frontend/src/metabase/ui/components/inputs/Select/SelectItem/SelectItemWithDescription.tsxnew file mode 100644index 00000000000..1b61f88f74c--- /dev/null+++ b/frontend/src/metabase/ui/components/inputs/Select/SelectItem/SelectItemWithDescription.tsx@@ -0,0 +1,43 @@+import { type ReactNode, type Ref, forwardRef } from "react";++import { Flex, Icon, Text } from "metabase/ui";++import { SelectItem, type SelectItemProps } from "./SelectItem";+import S from "./SelectItemWithDescription.module.css";++export interface SelectItemWithDescriptionProps extends SelectItemProps {+ label: ReactNode;+ description?: ReactNode;+ showCheckIcon?: boolean;+}++export const SelectItemWithDescription = forwardRef(+ function SelectItemWithDescription(+ {+ label,+ description,+ showCheckIcon = true,+ selected,+ ...props+ }: SelectItemWithDescriptionProps,+ ref: Ref<HTMLDivElement>,+ ) {+ return (+ <SelectItem ref={ref} selected={selected} {...props}>+ {showCheckIcon && <Icon name={selected ? "check" : "empty"} />}++ <Flex direction="column" flex="1" gap="xs">+ <Text c="inherit" fw="bold" lh="1rem">+ {label}+ </Text>++ {description && (+ <Text c="text-disabled" className={S.description} lh="1rem">+ {description}+ </Text>+ )}+ </Flex>+ </SelectItem>+ );+ },+);diff --git a/frontend/src/metabase/ui/components/inputs/Select/SelectItem/index.ts b/frontend/src/metabase/ui/components/inputs/Select/SelectItem/index.tsindex 78982e42788..9473af34df0 100644--- a/frontend/src/metabase/ui/components/inputs/Select/SelectItem/index.ts+++ b/frontend/src/metabase/ui/components/inputs/Select/SelectItem/index.ts@@ -1,3 +1,4 @@export * from "./DefaultSelectItem";export * from "./SelectItem";+export * from "./SelectItemWithDescription";export * from "./utils";diff --git a/frontend/src/metabase/urls/transforms.ts b/frontend/src/metabase/urls/transforms.tsindex 9092ce3bc51..a705c3afb0b 100644--- a/frontend/src/metabase/urls/transforms.ts+++ b/frontend/src/metabase/urls/transforms.ts@@ -71,6 +71,10 @@ export function transformSettings(transformId: TransformId) {return `${TRANSFORMS_ROOT_URL}/${transformId}/settings`;}+export function transformIndexes(transformId: TransformId) {+ return `${TRANSFORMS_ROOT_URL}/${transformId}/indexes`;+}+export function transformDependencies(transformId: TransformId) {return `${TRANSFORMS_ROOT_URL}/${transformId}/dependencies`;}diff --git a/frontend/src/metabase/utils/objects.ts b/frontend/src/metabase/utils/objects.tsindex ba557011ba5..823307ab2a5 100644--- a/frontend/src/metabase/utils/objects.ts+++ b/frontend/src/metabase/utils/objects.ts@@ -5,7 +5,7 @@ export const getObjectEntries = <K extends string, V>(};export const getObjectKeys = <K extends string>(- obj: Record<K, unknown>,+ obj: Partial<Record<K, unknown>>,): K[] => {return Object.keys(obj) as K[];};diff --git a/frontend/test/__support__/server-mocks/index-manager.ts b/frontend/test/__support__/server-mocks/index-manager.tsnew file mode 100644index 00000000000..0536a31215a--- /dev/null+++ b/frontend/test/__support__/server-mocks/index-manager.ts@@ -0,0 +1,58 @@+import fetchMock from "fetch-mock";++import type {+ TableIndexEntry,+ TableIndexRequest,+ TransformId,+} from "metabase-types/api";+import { createMockTableIndexRequest } from "metabase-types/api/mocks";++export function setupListTableIndexesEndpoint(+ transformId: TransformId,+ indexes: TableIndexEntry[] = [],+) {+ fetchMock.get({+ url: `path:/api/index`,+ query: { "transform-id": transformId },+ response: { data: indexes },+ name: `listTableIndexes-${transformId}`,+ });+}++export function setupTableIndexEndpoints(+ transformId: TransformId,+ indexRequests: TableIndexRequest[] = [],+) {+ fetchMock.get({+ url: `path:/api/index`,+ query: { "transform-id": transformId },+ response: { data: indexRequests },+ name: `listTableIndexes-${transformId}`,+ });++ indexRequests.forEach((index) => {+ fetchMock.get(`path:/api/index/request/${index.id}`, index, {+ name: `getTableIndex-${index.id}`,+ });+ fetchMock.delete(`path:/api/index/request/${index.id}`, 204, {+ name: `deleteTableIndex-${index.id}`,+ });+ fetchMock.put(+ `path:/api/index/request/${index.id}`,+ async (call) => {+ const lastCall = fetchMock.callHistory.lastCall(call.url);+ return { ...index, ...(await lastCall?.request?.json()) };+ },+ { name: `updateTableIndex-${index.id}` },+ );+ });++ fetchMock.post(+ `path:/api/index/request`,+ async (call) => {+ const lastCall = fetchMock.callHistory.lastCall(call.url);+ return createMockTableIndexRequest(await lastCall?.request?.json());+ },+ { name: `createTableIndex` },+ );+}diff --git a/frontend/test/__support__/server-mocks/index.ts b/frontend/test/__support__/server-mocks/index.tsindex a9126edd7dd..56a808bc001 100644--- a/frontend/test/__support__/server-mocks/index.ts+++ b/frontend/test/__support__/server-mocks/index.ts@@ -28,6 +28,7 @@ export * from "./geojson";export * from "./google";export * from "./group";export * from "./impersonation";+export * from "./index-manager";export * from "./library";export * from "./logger";export * from "./measure";diff --git a/frontend/test/__support__/server-mocks/transform.ts b/frontend/test/__support__/server-mocks/transform.tsindex 7f6e1315516..c5e13010f99 100644--- a/frontend/test/__support__/server-mocks/transform.ts+++ b/frontend/test/__support__/server-mocks/transform.ts@@ -24,6 +24,10 @@ export function setupListTransformsEndpoint(transforms: Transform[]) {fetchMock.get(`path:/api/transform`, transforms);}+export function setupGetTransformEndpoint(transform: Transform) {+ fetchMock.get(`path:/api/transform/${transform.id}`, transform);+}+export function setupListTransformTagsEndpoint(tags: TransformTag[]) {fetchMock.get(`path:/api/transform-tag`, tags);}diff --git a/mage/test/mage/modules_test.clj b/mage/test/mage/modules_test.cljindex 11e3444153e..99ddf40e759 100644--- a/mage/test/mage/modules_test.clj+++ b/mage/test/mage/modules_test.clj@@ -363,7 +363,8 @@;; Added premium-features to driver-affecting-overrides (#69561);; 2026-04-07 Bumped to 41 due to agent-lib addition (Metabot MBQL improvements #71524);; 2026-06-04 Bumped to 42 due to run-tracking addition (Zombie transform reaper #75194)- max-allowed-count 42]+ ;; 2026-06-24 Bumped to 44 for indexes + indexes-rest (Index manager #75848)+ max-allowed-count 44](is (<= (count modules-triggering-drivers) max-allowed-count)(format "Too many modules trigger driver tests! Expected <= %d, got %d.Modules triggering driver tests: %sdiff --git a/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk.clj b/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk.cljindex 21c54124cae..c1ab9836744 100644--- a/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk.clj+++ b/modules/drivers/bigquery-cloud-sdk/src/metabase/driver/bigquery_cloud_sdk.clj@@ -14,6 +14,7 @@;; isolation (`init-workspace-isolation!`, `grant-workspace-read-access!`,;; `check-isolation-permissions`, `destroy-workspace-isolation!`).[metabase.driver.bigquery-cloud-sdk.workspaces]+ [metabase.driver.common :as driver.common][metabase.driver.common.table-rows-sample :as table-rows-sample][metabase.driver.connection :as driver.conn][metabase.driver.settings :as driver.settings]@@ -26,7 +27,7 @@[metabase.driver.sync :as driver.s][metabase.util :as u][metabase.util.date-2 :as u.date]- [metabase.util.i18n :refer [tru]]+ [metabase.util.i18n :refer [deferred-tru tru]][metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.performance :refer [mapv some empty? not-empty]]@@ -46,6 +47,7 @@BigQuery$TableOptionBigQueryExceptionBigQueryOptions+ ClusteringDatasetDatasetIdField@@ -56,6 +58,7 @@JobInfoQueryJobConfigurationSchema+ StandardTableDefinitionTableTableDefinition$TypeTableId@@ -991,6 +994,9 @@:expressions/integer true:expressions/text true:identifiers-with-spaces true+ ;; clustering is the only index-equivalent, inlined as CLUSTER BY (no standalone DDL)+ :index/fetch true+ :index/inline-create true:metadata/key-constraints false:metadata/table-existence-check true:nested-fields true@@ -1102,6 +1108,56 @@[_ native-form](sql.u/format-sql-and-fix-params :mysql native-form))+;;; +----------------------------------------------------------------------------------------------------------------++;;; | Indexes (Index Manager) |+;;; +----------------------------------------------------------------------------------------------------------------+++;; BigQuery has no secondary indexes. Clustering is the index-equivalent, inlined as `CLUSTER BY` into both creation+;; seams (the CTAS in `compile-transform` and the CREATE TABLE in `create-table!`). It's unnamed, so reconcile matches+;; it by kind + columns.++(defmethod driver/supported-index-methods :bigquery-cloud-sdk+ [_driver _database]+ {:clustering {:lifecycle :inline+ :display-name (deferred-tru "Clustering")+ :fields [driver.common/index-columns-field]}})++(defn- clustering-clause+ "Inline `CLUSTER BY col, ...` clause for a table's `indexes`, or nil when there's no clustering."+ [indexes]+ (when-let [{:keys [columns]} (some #(when (= :clustering (:kind %)) %) indexes)]+ (let [cols (str/join ", " (map #(sql.u/quote-name :bigquery-cloud-sdk :field (:name %)) columns))]+ (format "CLUSTER BY %s" cols))))++(defn- table-clustering-columns+ "Clustering columns of the BigQuery `table` in `schema`, in clustering order, or nil when the table is absent, isn't a+ standard table (view/external), or isn't clustered. Reads table metadata directly, no SQL."+ [database schema table]+ (when-not (or (str/blank? schema) (str/blank? table))+ (let [details (driver.conn/effective-details database)+ client (database-details->client details)+ project-id (bigquery.common/get-project-id details)]+ (when-let [^Table bq-table (get-table* client project-id schema table)]+ (let [definition (.getDefinition bq-table)]+ (when (instance? StandardTableDefinition definition)+ (when-let [^Clustering clustering (.getClustering ^StandardTableDefinition definition)]+ (not-empty (vec (.getFields clustering))))))))))++(defmethod driver/fetch-table-indexes :bigquery-cloud-sdk+ [_driver database schema table]+ (if-let [cluster-cols (table-clustering-columns database schema table)]+ [{:name nil+ :kind :clustering+ :access-method nil+ :is-unique false+ :is-primary false+ :is-valid true+ :key-columns cluster-cols+ :include-columns []+ :partial-predicate nil+ :definition (format "CLUSTER BY %s" (str/join ", " cluster-cols))}]+ []))+;;; +----------------------------------------------------------------------------------------------------------------+;;; | Transforms Support |;;; +----------------------------------------------------------------------------------------------------------------+@@ -1113,10 +1169,13 @@(qn (name table)))))(defmethod driver/compile-transform :bigquery-cloud-sdk- [_driver {:keys [query output-table]}]+ [_driver {:keys [query output-table indexes]}](let [{sql-query :query sql-params :params} query- table-str (get-table-str output-table)]- [(format "CREATE OR REPLACE TABLE %s AS %s" table-str sql-query)+ table-str (get-table-str output-table)+ cluster (clustering-clause indexes)]+ [(if cluster+ (format "CREATE OR REPLACE TABLE %s %s AS %s" table-str cluster sql-query)+ (format "CREATE OR REPLACE TABLE %s AS %s" table-str sql-query))sql-params]))(defmethod driver/compile-insert :bigquery-cloud-sdk@@ -1132,8 +1191,10 @@[(str "DROP TABLE IF EXISTS " table-str)]))(defmethod driver/create-table! :bigquery-cloud-sdk- [driver database-id table-name column-definitions & {:keys [primary-key]}]- (let [sql (#'driver.sql-jdbc/create-table!-sql driver table-name column-definitions :primary-key primary-key)+ [driver database-id table-name column-definitions & {:keys [primary-key indexes]}]+ (let [base (#'driver.sql-jdbc/create-table!-sql driver table-name column-definitions :primary-key primary-key)+ cluster (clustering-clause indexes)+ sql (if cluster (str base " " cluster) base)database (t2/select-one :model/Database database-id)conn-spec (driver/connection-spec driver database)](driver/execute-raw-queries! driver conn-spec [sql])))diff --git a/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk_test.clj b/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk_test.cljindex 059e5357b13..f61f8b58501 100644--- a/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk_test.clj+++ b/modules/drivers/bigquery-cloud-sdk/test/metabase/driver/bigquery_cloud_sdk_test.clj@@ -1545,3 +1545,13 @@:value "Gadget"}]))](is (= ["Aerodynamic Leather Computer" "Gadget"](mt/first-row (qp/process-query query)))))))++(deftest ^:parallel clustering-clause-test+ (testing "clustering renders an inline CLUSTER BY with backtick-quoted columns, in order"+ (is (= "CLUSTER BY `category`, `price`"+ (#'bigquery/clustering-clause [{:kind :clustering :columns [{:name "category"} {:name "price"}]}]))))+ (testing "no clustering index -> no clause"+ (is (nil? (#'bigquery/clustering-clause [{:kind :btree :columns [{:name "category"}]}]))))+ (testing "a SQL-injection payload in a clustering column is backtick-escaped, so it can only ever be an identifier"+ (is (= "CLUSTER BY `c``; DROP TABLE x; --`"+ (#'bigquery/clustering-clause [{:kind :clustering :columns [{:name "c`; DROP TABLE x; --"}]}])))))diff --git a/modules/drivers/clickhouse/src/metabase/driver/clickhouse.clj b/modules/drivers/clickhouse/src/metabase/driver/clickhouse.cljindex 482488ab58d..ff5dbe5eff4 100644--- a/modules/drivers/clickhouse/src/metabase/driver/clickhouse.clj+++ b/modules/drivers/clickhouse/src/metabase/driver/clickhouse.clj@@ -9,6 +9,7 @@[metabase.driver.clickhouse-nippy][metabase.driver.clickhouse-qp][metabase.driver.clickhouse-version :as clickhouse-version]+ [metabase.driver.common :as driver.common][metabase.driver.connection :as driver.conn][metabase.driver.ddl.interface :as ddl.i][metabase.driver.sql :as driver.sql]@@ -20,8 +21,9 @@[metabase.driver.sql.util :as sql.u][metabase.driver.util :as driver.u][metabase.util :as u]- [metabase.util.i18n :refer [tru]]- [metabase.util.log :as log])+ [metabase.util.i18n :refer [deferred-tru tru]]+ [metabase.util.log :as log]+ [metabase.util.performance :as perf])(:import(com.clickhouse.client.api.query QuerySettings)(java.sql Connection SQLException Statement PreparedStatement)@@ -55,6 +57,11 @@:expressions/float true:expressions/integer true:expressions/text true+ ;; ClickHouse uses both index lifecycles: ORDER BY is inlined into the MergeTree engine+ ;; clause at creation, while data-skipping indexes are added as separate statements after.+ :index/fetch true+ :index/inline-create true+ :index/standalone-create true:left-join (not driver-api/is-test?):metadata/key-constraints false:now true@@ -250,31 +257,163 @@;; filenames as table/column names. But its an approximation206)+(defn- escape-ident+ ;; Backslash-escape rather than double the backtick: ClickHouse identifiers follow string-literal escaping, where+ ;; a preceding backslash would defeat quote-doubling.+ [s]+ (-> s+ (str/replace "\\" "\\\\")+ (str/replace "`" "\\`")))+(defn- quote-name [s](let [s (if (and (keyword? s) (namespace s)) (str (namespace s) "." (name s)) s)parts (filter identity (str/split (name s) #"\."))]- (str/join "." (map #(str "`" % "`") parts))))+ (str/join "." (map #(str "`" (escape-ident %) "`") parts))))++;;; +----------------------------------------------------------------------------------------------------------------++;;; | Indexes (Index Manager) |+;;; +----------------------------------------------------------------------------------------------------------------+++;; ClickHouse exercises both index lifecycles. ORDER BY (the MergeTree sorting key) is inlined into the table at+;; creation, so it is rendered at both creation seams: the CTAS in `compile-transform` (SQL transforms) and the+;; CREATE TABLE in `create-table!` (Python transforms). A data-skipping index is applied afterwards as a separate+;; statement via `compile-create-index`.++(defmethod driver/supported-index-methods :clickhouse+ [_driver _database]+ {:order-by {:lifecycle :inline+ :display-name (deferred-tru "Sorting key")+ :fields [driver.common/index-columns-field]}+ :skip-index {:lifecycle :standalone+ :display-name (deferred-tru "Skip index")+ :fields [driver.common/index-name-field+ driver.common/index-columns-field+ {:name "type"+ :display-name (deferred-tru "Type")+ :type :select+ :required true+ ;; only arg-free types; set/ngrambf_v1/tokenbf_v1 need params the form can't supply yet+ :options [{:name (deferred-tru "Min/max") :value "minmax"}+ {:name (deferred-tru "Bloom filter") :value "bloom_filter"}]}+ driver.common/index-granularity-field]}})++(defn- order-by-columns+ "Columns for the MergeTree ORDER BY: the inline `:order-by` index's columns when present, else the primary key (the+ existing behavior). Returns a seq of column-name strings."+ [{:keys [primary-key indexes]}]+ (or (some->> indexes (filter (comp #{:order-by} :kind)) first :columns (map :name) seq)+ primary-key))++(defn- order-by-clause+ "Render `ORDER BY (...)` for the given table opts. MergeTree requires an ORDER BY; with no order-by index and no+ primary key it is the empty tuple `ORDER BY ()` (an unsorted table)."+ [opts]+ (format "ORDER BY (%s)" (str/join ", " (map quote-name (order-by-columns opts)))))++(defn- allow-nullable-key-setting+ "The `allow_nullable_key = 1` MergeTree setting, or nil when there's no sorting key. Transform target columns are+ nullable, and MergeTree rejects a nullable sorting key without this."+ [opts]+ (when (seq (order-by-columns opts))+ "allow_nullable_key = 1"))++(defn- skip-index-type-sql+ [type type-args]+ (if (seq type-args)+ (format "%s(%s)" (name type) (str/join ", " type-args))+ (name type)))++(defmethod driver/compile-create-index :clickhouse+ [_driver schema table {index-name :name, :keys [columns type type-args granularity if-not-exists]}]+ ;; A data-skipping index needs two statements: ADD INDEX registers it (metadata only, applies to new parts), then+ ;; MATERIALIZE INDEX backfills it over the existing parts.+ (let [target (quote-name (if (seq schema) (keyword schema table) (keyword table)))+ idx (quote-name index-name)+ expr (str/join ", " (map (comp quote-name :name) columns))]+ [[(format "ALTER TABLE %s ADD INDEX %s%s (%s) TYPE %s GRANULARITY %d"+ target (if if-not-exists "IF NOT EXISTS " "") idx expr+ (skip-index-type-sql type type-args) (or granularity 1))]+ [(format "ALTER TABLE %s MATERIALIZE INDEX %s" target idx)]]))++(defn- strip-wrapping-parens+ "Drop one `(...)` that wraps the whole expression (a skip-index `expr` has one, a sorting key doesn't)."+ [^String s]+ (cond-> s (and (str/starts-with? s "(") (str/ends-with? s ")")) (subs 1 (dec (count s)))))++(defn- expr->columns+ "Best-effort split of a ClickHouse key expression into its top-level columns/expressions. A quoted name like+ `weird,name` becomes a bare element; a real expression like `lower(email)` stays one element."+ [expr]+ (if-let [s (perf/not-empty expr)]+ (perf/mapv #(driver.common/unquote-ident (str/trim %) \`)+ (driver.common/split-top-level-commas (strip-wrapping-parens s)))+ []))++;; Named skip-indexes come from `system.data_skipping_indices`; the inline MergeTree sorting key+;; (`system.tables.sorting_key`) is emitted with `:name nil`. Blank `schema` falls back to `currentDatabase()`.+(defmethod driver/fetch-table-indexes :clickhouse+ [_driver database schema table]+ (let [conn-spec (sql-jdbc.conn/db->pooled-connection-spec database)+ db (perf/not-empty schema)+ skip-idxs (->> (jdbc/query+ conn-spec+ [(str "SELECT name, type, type_full, expr, granularity "+ "FROM system.data_skipping_indices "+ "WHERE database = coalesce(?, currentDatabase()) AND table = ? "+ "ORDER BY name")+ db table])+ (perf/mapv (fn [{:keys [name type type_full expr granularity]}]+ {:name name+ :kind :skip-index+ :access-method type+ :is-unique false+ :is-primary false+ :is-valid true+ :key-columns (expr->columns expr)+ :include-columns []+ :partial-predicate nil+ :definition (format "INDEX %s %s TYPE %s GRANULARITY %s"+ name expr type_full granularity)})))+ sorting (-> (jdbc/query+ conn-spec+ [(str "SELECT sorting_key FROM system.tables "+ "WHERE database = coalesce(?, currentDatabase()) AND name = ?")+ db table])+ first :sorting_key)]+ (cond-> skip-idxs+ (perf/not-empty sorting) (conj {:name nil+ :kind :order-by+ :access-method nil+ :is-unique false+ :is-primary false+ :is-valid true+ :key-columns (expr->columns sorting)+ :include-columns []+ :partial-predicate nil+ :definition (format "ORDER BY (%s)" sorting)}))))(defn- create-table!-sql"Creates a ClickHouse table with the given name and column definitions. It assumes the engine is MergeTree,so it only works with Clickhouse Cloud and single node on-premise deployments at the moment."- [_driver table-name column-definitions & {:keys [primary-key] :as opts}]+ [_driver table-name column-definitions & {:as opts}](str/join "\n"[(#'sql-jdbc/create-table!-sql :sql-jdbc table-name column-definitions opts)"ENGINE = MergeTree"- (format "ORDER BY (%s)" (str/join ", " (map quote-name primary-key)))- ;; disable insert idempotency to allow duplicate inserts- "SETTINGS replicated_deduplication_window = 0"]))+ (order-by-clause opts)+ ;; disable insert idempotency to allow duplicate inserts; permit a nullable sorting key (see+ ;; `allow-nullable-key-setting`).+ (str "SETTINGS replicated_deduplication_window = 0"+ (when-let [s (allow-nullable-key-setting opts)] (str ", " s)))]))(defmethod driver/create-table! :clickhouse- [driver db-id table-name column-definitions & {:keys [primary-key]}]+ [driver db-id table-name column-definitions & {:as opts}](sql-jdbc.execute/do-with-connection-with-optionsdriverdb-id{:write? true}(fn [^java.sql.Connection conn](with-open [stmt (.createStatement conn)]- (let [sql (create-table!-sql driver table-name column-definitions :primary-key primary-key)]+ (let [sql (create-table!-sql driver table-name column-definitions opts)](.execute stmt sql))))));; rename-tables!* only supported by the atomic engine@@ -367,14 +506,15 @@(str/starts-with? msg "Code: 81"))))(defmethod driver/compile-transform :clickhouse- [driver {:keys [query output-table]}]+ [driver {:keys [query output-table indexes]}](let [{sql-query :query sql-params :params} query- pieces [(sql.qp/format-honeysql driver {:create-table output-table})- ;; TODO(rileythomp, 2025-08-22): Is there a better way to do this?- ;; i.e. only do this if we don't have a non-nullable field to use as a primary key?- (sql.qp/format-honeysql driver {:raw "ORDER BY ()"})- ["AS"]- [sql-query sql-params]]+ ;; A sorting key needs `allow_nullable_key`; the SETTINGS clause has to go before `AS SELECT`.+ settings (when-let [s (allow-nullable-key-setting {:indexes indexes})]+ (sql.qp/format-honeysql driver {:raw (str "SETTINGS " s)}))+ pieces (cond-> [(sql.qp/format-honeysql driver {:create-table output-table})+ (sql.qp/format-honeysql driver {:raw (order-by-clause {:indexes indexes})})]+ settings (conj settings)+ :always (conj ["AS"] [sql-query sql-params]))sql (str/join " " (map first pieces))](into [sql] (mapcat rest) pieces)))diff --git a/modules/drivers/clickhouse/test/metabase/driver/clickhouse/index_test.clj b/modules/drivers/clickhouse/test/metabase/driver/clickhouse/index_test.cljnew file mode 100644index 00000000000..ed7a590739a--- /dev/null+++ b/modules/drivers/clickhouse/test/metabase/driver/clickhouse/index_test.clj@@ -0,0 +1,185 @@+(ns ^:mb/driver-tests metabase.driver.clickhouse.index-test+ "Tests for the ClickHouse index driver methods (Index Manager). ClickHouse exercises both lifecycles in one driver:+ the inline ORDER BY at both creation seams (the CTAS in `compile-transform` and the CREATE TABLE in `create-table!`)+ and the standalone data-skipping index (`compile-create-index`, which is multi-statement).++ The rendering/capability checks are pure and need no connection. `order-by-inlined-live-test` and+ `skip-index-live-test` run the seams against a real ClickHouse and read the result back out of `system.tables`+ (the sorting key) and `system.data_skipping_indices` (the skip index), so the indexes are verified to actually take+ effect on the physical table, not just to render."+ (:require+ [clojure.java.jdbc :as jdbc]+ [clojure.test :refer :all]+ [metabase.driver :as driver]+ [metabase.driver.clickhouse :as clickhouse]+ [metabase.driver.sql-jdbc.connection :as sql-jdbc.conn]+ [metabase.test :as mt]+ [metabase.util.malli.registry :as mr]))++(deftest ^:parallel feature-flags-test+ (testing "ClickHouse advertises both index lifecycles"+ (is (true? (driver/database-supports? :clickhouse :index/inline-create nil)))+ (is (true? (driver/database-supports? :clickhouse :index/standalone-create nil)))))++(deftest ^:parallel supported-index-methods-test+ (testing "ClickHouse advertises the inline order-by and the standalone skip-index, with form fields"+ (let [methods (driver/supported-index-methods :clickhouse nil)+ type-field (->> (get-in methods [:skip-index :fields])+ (filter #(= "type" (:name %)))+ first)]+ (is (mr/validate :metabase.driver/supported-index-methods methods))+ (is (= {:order-by :inline, :skip-index :standalone}+ (update-vals methods :lifecycle)))+ (is (= ["columns"] (map :name (get-in methods [:order-by :fields]))))+ (is (= ["name" "columns" "type" "granularity"]+ (map :name (get-in methods [:skip-index :fields]))))+ (is (= #{"minmax" "bloom_filter"}+ (set (map :value (:options type-field))))))))++;;; --- inline ORDER BY at both creation seams ---++(def ^:private order-by-columns+ [["a" "Int64"] ["b" "Int64"]])++(def ^:private order-by-cases+ ;; The table/column identifiers come from the shared `:sql-jdbc` renderer (double-quoted); the ORDER BY columns are+ ;; rendered with ClickHouse `quote-name` (backticks), matching the driver's pre-existing ORDER BY rendering.+ ;; A sorting key gets `allow_nullable_key = 1`, since transform target columns are nullable and MergeTree otherwise+ ;; rejects a nullable sorting key. The unsorted `ORDER BY ()` case has no key, so it doesn't.+ [{:label "order-by index sets the MergeTree sorting key and allows a nullable key"+ :indexes [{:kind :order-by :columns [{:name "a"} {:name "b"}]}]+ :ctas "CREATE TABLE `events` ORDER BY (`a`, `b`) SETTINGS allow_nullable_key = 1 AS SELECT 1"+ :create-table "CREATE TABLE \"events\" (\"a\" Int64, \"b\" Int64)\nENGINE = MergeTree\nORDER BY (`a`, `b`)\nSETTINGS replicated_deduplication_window = 0, allow_nullable_key = 1"}+ {:label "no order-by index -> empty ORDER BY () (unsorted), no nullable-key setting"+ :indexes []+ :ctas "CREATE TABLE `events` ORDER BY () AS SELECT 1"+ :create-table "CREATE TABLE \"events\" (\"a\" Int64, \"b\" Int64)\nENGINE = MergeTree\nORDER BY ()\nSETTINGS replicated_deduplication_window = 0"}])++(deftest ^:parallel order-by-inlined-at-both-creation-seams-test+ (doseq [{:keys [label indexes ctas create-table]} order-by-cases]+ (testing label+ (testing "CTAS seam (compile-transform, SQL transforms)"+ (is (= [ctas ["p"]]+ (driver/compile-transform :clickhouse {:output-table :events+ :query {:query "SELECT 1" :params ["p"]}+ :indexes indexes}))))+ (testing "CREATE TABLE seam (create-table!, Python transforms)"+ (is (= create-table+ (#'clickhouse/create-table!-sql :clickhouse :events order-by-columns {:indexes indexes})))))))++;;; --- standalone data-skipping index ---++(deftest ^:parallel compile-create-index-test+ (testing "a skip-index renders ADD INDEX + MATERIALIZE INDEX (backfill existing parts)"+ (is (= [["ALTER TABLE `events` ADD INDEX `idx_a` (`a`) TYPE minmax GRANULARITY 4"]+ ["ALTER TABLE `events` MATERIALIZE INDEX `idx_a`"]]+ (driver/compile-create-index :clickhouse nil "events"+ {:name "idx_a" :columns [{:name "a"}] :type :minmax :granularity 4}))))+ (testing "bloom_filter (the other arg-free advertised type) renders TYPE bloom_filter, no args"+ (is (= [["ALTER TABLE `events` ADD INDEX `idx_a` (`a`) TYPE bloom_filter GRANULARITY 4"]+ ["ALTER TABLE `events` MATERIALIZE INDEX `idx_a`"]]+ (driver/compile-create-index :clickhouse nil "events"+ {:name "idx_a" :columns [{:name "a"}] :type :bloom_filter :granularity 4}))))+ (testing "type args render, schema qualifies, granularity defaults to 1"+ (is (= [["ALTER TABLE `public`.`events` ADD INDEX `idx_ab` (`a`, `b`) TYPE set(100) GRANULARITY 1"]+ ["ALTER TABLE `public`.`events` MATERIALIZE INDEX `idx_ab`"]]+ (driver/compile-create-index :clickhouse "public" "events"+ {:name "idx_ab" :columns [{:name "a"} {:name "b"}] :type :set :type-args [100]}))))+ (testing ":if-not-exists renders ADD INDEX IF NOT EXISTS"+ (is (= [["ALTER TABLE `events` ADD INDEX IF NOT EXISTS `idx_a` (`a`) TYPE minmax GRANULARITY 4"]+ ["ALTER TABLE `events` MATERIALIZE INDEX `idx_a`"]]+ (driver/compile-create-index :clickhouse nil "events"+ {:name "idx_a" :columns [{:name "a"}] :type :minmax :granularity 4+ :if-not-exists true}))))+ (testing "backticks and backslashes in identifiers are escaped, so a hostile name cannot break out"+ (is (= [["ALTER TABLE `events` ADD INDEX `idx\\`; DROP TABLE x; --` (`a\\\\\\`b`) TYPE minmax GRANULARITY 1"]+ ["ALTER TABLE `events` MATERIALIZE INDEX `idx\\`; DROP TABLE x; --`"]]+ (driver/compile-create-index :clickhouse nil "events"+ {:name "idx`; DROP TABLE x; --" :columns [{:name "a\\`b"}] :type :minmax})))))++;;; --------------------------------------- Live execute path ----------------------------------------++;; All tables here land in the connection's default database (created unqualified), so the catalog lookups filter on+;; database = "default". Tests are :synchronized, not :parallel: they create and drop tables in that shared database.++(defn- sorting-key+ "The MergeTree sorting key of `db`.`table` as ClickHouse reports it, e.g. \"a, b\" (or \"\" for an unsorted table)."+ [conn-spec db table]+ (-> (jdbc/query conn-spec+ ["SELECT sorting_key FROM system.tables WHERE database = ? AND name = ?" db table])+ first :sorting_key))++(defn- only-skip-index+ "The single data-skipping index on `db`.`table` as `{:name ..., :type ..., :expr ..., :granularity ...}`, or nil when+ there is none. Looked up by table (not by name) so the assertion doesn't couple to how the index name is prefixed.+ Granularity is a UInt64, so coerce it to a long for a clean comparison against the literal we pass in."+ [conn-spec db table]+ (when-let [{:keys [name type expr granularity]}+ (first (jdbc/query conn-spec+ [(str "SELECT name, type, expr, granularity FROM system.data_skipping_indices "+ "WHERE database = ? AND table = ?")+ db table]))]+ {:name name :type type :expr expr :granularity (long granularity)}))++(def ^:private live-order-by-cases+ "Each case drives one ORDER BY index through both live seams and asserts the sorting key the physical table reports."+ [{:label "order-by index sets the MergeTree sorting key" :slug "idx"+ :indexes [{:kind :order-by :columns [{:name "a"} {:name "b"}]}]+ :expected "a, b"}+ {:label "no order-by index -> empty ORDER BY () (unsorted table)" :slug "noidx"+ :indexes []+ :expected ""}])++(deftest ^:synchronized order-by-inlined-live-test+ (testing "an inlined ORDER BY actually sets the sorting key at both creation seams"+ (mt/test-driver :clickhouse+ (let [details (mt/dbdef->connection-details :clickhouse :db {:database-name "default"})+ conn-spec (sql-jdbc.conn/connection-details->spec :clickhouse details)]+ (mt/with-temp [:model/Database db {:engine :clickhouse, :details details}]+ (doseq [{:keys [label slug indexes expected]} live-order-by-cases]+ (testing label+ (let [ctas-table (str (gensym (str "mb_ob_ctas_" slug "_")))+ crt-table (str (gensym (str "mb_ob_crt_" slug "_")))+ drop! (fn [t] (jdbc/execute! conn-spec [(format "DROP TABLE IF EXISTS `%s`" t)]))]+ (testing "CTAS seam (compile-transform): run the rendered CTAS, read the sorting key back"+ (drop! ctas-table)+ (try+ (let [[sql params] (driver/compile-transform+ :clickhouse+ {:output-table (keyword ctas-table)+ :query {:query "SELECT 1 AS a, 2 AS b"}+ :indexes indexes})]+ (jdbc/execute! conn-spec (into [sql] params))+ (is (= expected (sorting-key conn-spec "default" ctas-table))))+ (finally (drop! ctas-table))))+ (testing "CREATE TABLE seam (create-table!): create the table, read the sorting key back"+ (drop! crt-table)+ (try+ (driver/create-table! :clickhouse (:id db) (keyword crt-table)+ order-by-columns {:indexes indexes})+ (is (= expected (sorting-key conn-spec "default" crt-table)))+ (finally (drop! crt-table))))))))))))++(deftest ^:synchronized skip-index-live-test+ (testing "the standalone-create path runs ADD INDEX + MATERIALIZE INDEX and the data-skipping index actually exists"+ (mt/test-driver :clickhouse+ (let [details (mt/dbdef->connection-details :clickhouse :db {:database-name "default"})+ conn-spec (sql-jdbc.conn/connection-details->spec :clickhouse details)+ table (str (gensym "mb_skip_"))+ index {:name "evt_minmax" :columns [{:name "a"}] :type :minmax :granularity 4}+ drop! (fn [] (jdbc/execute! conn-spec [(format "DROP TABLE IF EXISTS `%s`" table)]))]+ (mt/with-temp [:model/Database db {:engine :clickhouse, :details details}]+ (drop!)+ (try+ (driver/create-table! :clickhouse (:id db) (keyword table) order-by-columns {})+ (is (nil? (only-skip-index conn-spec "default" table))+ "index absent before the standalone-create step")+ (testing "ADD INDEX + MATERIALIZE INDEX create the index with the expected type, columns, and granularity"+ (driver/execute-raw-queries! :clickhouse conn-spec+ (driver/compile-create-index :clickhouse nil table index))+ ;; ClickHouse normalizes the index expression in the catalog and reports the single column wrapped in+ ;; parens, so `system.data_skipping_indices.expr` reads back as "(a)" for the `(a)` we submitted.+ (is (= {:type "minmax" :expr "(a)" :granularity 4}+ (-> (only-skip-index conn-spec "default" table)+ (select-keys [:type :expr :granularity])))))+ (finally (drop!))))))))diff --git a/modules/drivers/clickhouse/test/metabase/driver/clickhouse_test.clj b/modules/drivers/clickhouse/test/metabase/driver/clickhouse_test.cljindex 29c074ad8d4..6e926badd78 100644--- a/modules/drivers/clickhouse/test/metabase/driver/clickhouse_test.clj+++ b/modules/drivers/clickhouse/test/metabase/driver/clickhouse_test.clj@@ -5,6 +5,7 @@[clojure.java.jdbc :as jdbc][clojure.test :refer :all][metabase.driver :as driver]+ [metabase.driver.clickhouse :as clickhouse][metabase.driver.clickhouse-qp :as clickhouse-qp][metabase.driver.clickhouse-version :as clickhouse-version][metabase.driver.sql-jdbc :as sql-jdbc]@@ -31,6 +32,23 @@`(mt/with-dynamic-redefs ~bindings ~@body)`(mt/with-dynamic-fn-redefs ~bindings ~@body)))+(deftest ^:parallel expr->columns-test+ (testing "splits a ClickHouse key expression into its top-level columns/expressions (no live DB needed)"+ ;; the catalog strings here are the real stored forms: `system.tables.sorting_key` is unwrapped, a single-expression+ ;; `system.data_skipping_indices.expr` is paren-wrapped, and a function key carries its own inner comma.+ (are [expr expected] (= expected (#'clickhouse/expr->columns expr))+ "a, b" ["a" "b"] ; sorting key, no wrapper+ "(a, b)" ["a" "b"] ; skip-index, wrapped+ "a" ["a"]+ "(lower(s))" ["lower(s)"] ; wrapped single expression, not truncated+ "a, cityHash64(s, b)" ["a" "cityHash64(s, b)"] ; function key's inner comma is not a split point+ ;; a backtick-quoted name can hold a comma or paren; it must stay one column and come out bare+ "`weird,name`, b" ["weird,name" "b"]+ "`paren(col`, b" ["paren(col" "b"]+ "`back``tick`" ["back`tick"] ; doubled backtick is an escaped backtick+ "" [] ; blank -> [], so :key-columns stays schema-valid+ nil [])))+(deftest ^:parallel clickhouse-version(mt/test-driver :clickhouse(t2.with-temp/with-tempdiff --git a/modules/drivers/redshift/src/metabase/driver/redshift.clj b/modules/drivers/redshift/src/metabase/driver/redshift.cljindex 020c778eb7d..183384ee1bf 100644--- a/modules/drivers/redshift/src/metabase/driver/redshift.clj+++ b/modules/drivers/redshift/src/metabase/driver/redshift.clj@@ -7,6 +7,7 @@[java-time.api :as t][metabase.driver :as driver][metabase.driver-api.core :as driver-api]+ [metabase.driver.common :as driver.common][metabase.driver.postgres :as driver.postgres][metabase.driver.sql :as driver.sql][metabase.driver.sql-jdbc :as sql-jdbc]@@ -23,6 +24,7 @@[metabase.util :as u][metabase.util.date-2 :as u.date][metabase.util.honey-sql-2 :as h2x]+ [metabase.util.i18n :refer [deferred-tru]][metabase.util.json :as json][metabase.util.log :as log][metabase.util.match :as match]@@ -52,6 +54,12 @@:describe-is-nullable false:expression-literals true:identifiers-with-spaces false+ ;; Redshift has no secondary indexes; sortkeys are inlined into the table-creation+ ;; statement, not created afterwards. Override the `:postgres`-inherited standalone+ ;; support.+ :index/fetch true+ :index/inline-create true+ :index/standalone-create false:metadata/table-existence-check true:nested-field-columns false:regex/lookaheads-and-lookbehinds false@@ -220,6 +228,157 @@[_]:sunday)+;;; +----------------------------------------------------------------------------------------------------------------++;;; | Indexes (Index Manager) |+;;; +----------------------------------------------------------------------------------------------------------------+++(defmethod driver/supported-index-methods :redshift+ [_driver _database]+ ;; Redshift has no secondary indexes: a sortkey and a distribution style are inlined into the table at creation.+ ;; That's the CTAS for a SQL transform and the CREATE TABLE for a Python transform, so both are rendered in+ ;; `compile-transform` and `create-table!`.+ {:sortkey {:lifecycle :inline+ :display-name (deferred-tru "Sort key")+ :fields [driver.common/index-columns-field+ {:name "style"+ :display-name (deferred-tru "Style")+ :type :select+ :required true+ :options [{:name (deferred-tru "Compound") :value "compound"}+ {:name (deferred-tru "Interleaved") :value "interleaved"}]}]}+ :distkey {:lifecycle :inline+ :display-name (deferred-tru "Distribution key")+ :fields [{:name "style"+ :display-name (deferred-tru "Style")+ :type :select+ :required true+ ;; AUTO is Redshift's default and drifts over time, so it's not offered as a managed style;+ ;; an AUTO table still surfaces its current style as a (non-managed) index.+ :options [{:name (deferred-tru "Key") :value "key"}+ {:name (deferred-tru "All") :value "all"}+ {:name (deferred-tru "Even") :value "even"}]}+ ;; only the :key style takes a column, so this is not required+ {:name "columns"+ :display-name (deferred-tru "Columns")+ :type :columns}]}})++(defn- sortkey-clause+ "Render the inline sortkey clause for a table's `indexes`, e.g. `COMPOUND SORTKEY (\"a\", \"b\")`, or nil when there+ is no sortkey."+ [driver indexes]+ (when-let [{:keys [style columns]} (first (filter (comp #{:sortkey} :kind) indexes))]+ (let [style-sql (if (= style :interleaved) "INTERLEAVED" "COMPOUND")+ cols (str/join ", " (map #(sql.u/quote-name driver :field (:name %)) columns))]+ (format "%s SORTKEY (%s)" style-sql cols))))++(defn- distkey-clause+ "Render the inline distribution clause for a table's `indexes`, e.g. `DISTSTYLE KEY DISTKEY (\"a\")` or+ `DISTSTYLE ALL`, or nil when there is no distkey."+ [driver indexes]+ (when-let [{:keys [style columns]} (first (filter (comp #{:distkey} :kind) indexes))]+ (if (= style :key)+ (format "DISTSTYLE KEY DISTKEY (%s)" (sql.u/quote-name driver :field (:name (first columns))))+ (format "DISTSTYLE %s" (u/upper-case-en (name style))))))++(defn- table-attributes-clause+ "Render the inline Redshift table attributes (distribution then sort key) for `indexes`, in the order Redshift+ requires, or nil when there are none. Shared by both creation seams: the CTAS in `compile-transform` and the+ CREATE TABLE in `create-table!`."+ [driver indexes]+ (let [clauses (remove nil? [(distkey-clause driver indexes) (sortkey-clause driver indexes)])]+ (when (seq clauses)+ (str/join " " clauses))))++(defn- distkey-index+ "The distkey entry from a table's declared `reldiststyle` (0 EVEN, 1 KEY, 8 ALL) and KEY column; nil for AUTO (9) and+ anything else. Reads the declared style, not the effective one Redshift drifts AUTO tables toward."+ [reldiststyle key-column]+ (when-let [style (case (long reldiststyle) 0 "even", 1 "key", 8 "all", nil)]+ (let [key? (= style "key")]+ {:name nil+ :kind :distkey+ :access-method style+ :is-unique false+ :is-primary false+ :is-valid true+ :key-columns (if key? [key-column] [])+ :include-columns []+ :partial-predicate nil+ :definition (if key?+ (format "DISTSTYLE KEY DISTKEY (%s)" key-column)+ (format "DISTSTYLE %s" (u/upper-case-en style)))})))++;; Redshift has no secondary indexes; the only physical "indexes" are the inline unnamed sortkey and the distribution,+;; so we override the inherited Postgres `pg_index` query. `svv_redshift_columns.sortkey` is the 1-based position+;; (negative marks the whole key INTERLEAVED); `distkey` is true on the single KEY column. The declared distribution+;; style comes from `pg_class_info`, which reports it for empty tables (`svv_table_info` doesn't). Blank `schema`+;; falls back to `current_schema()`.+(defmethod driver/fetch-table-indexes :redshift+ [_driver database schema table]+ (let [spec (sql-jdbc.conn/db->pooled-connection-spec database)+ rows (jdbc/query+ spec+ [(str "SELECT column_name, sortkey, distkey FROM svv_redshift_columns "+ "WHERE schema_name = COALESCE(?, current_schema()) AND table_name = ? "+ "ORDER BY abs(sortkey)")+ (perf/not-empty schema) table])+ sort-rows (filter (comp (complement zero?) :sortkey) rows)+ key-col (perf/some #(when (:distkey %) (:column_name %)) rows)+ diststyle (-> (jdbc/query+ spec+ [(str "SELECT c.reldiststyle AS reldiststyle FROM pg_class_info c "+ "JOIN pg_namespace n ON n.oid = c.relnamespace "+ "WHERE n.nspname = COALESCE(?, current_schema()) AND c.relname = ?")+ (perf/not-empty schema) table])+ first :reldiststyle)+ distkey (some-> diststyle (distkey-index key-col))]+ (cond-> []+ (seq sort-rows)+ (conj (let [interleaved? (perf/some (comp neg? :sortkey) sort-rows)+ columns (perf/mapv :column_name sort-rows)]+ {:name nil+ :kind :sortkey+ :access-method nil+ :is-unique false+ :is-primary false+ :is-valid true+ :key-columns columns+ :include-columns []+ :partial-predicate nil+ :definition (format "%s SORTKEY (%s)"+ (if interleaved? "INTERLEAVED" "COMPOUND")+ (str/join ", " columns))}))+ distkey (conj distkey))))++(defmethod driver/compile-transform :redshift+ [driver {:keys [query output-table indexes] :as transform-details}]+ (if-let [clause (table-attributes-clause driver indexes)]+ (let [{sql-query :query sql-params :params} query+ k (keyword output-table)+ target (if (namespace k)+ (sql.u/quote-name driver :table (namespace k) (name k))+ (sql.u/quote-name driver :table (name k)))]+ [(format "CREATE TABLE %s %s AS %s" target clause sql-query)+ sql-params])+ ((get-method driver/compile-transform :sql) driver transform-details)))++(defn- create-table-sql+ "Render the `CREATE TABLE (...)` for a Python-transform target, inlining sortkey/distkey from `:indexes` when present.+ Reuses the `:sql-jdbc` renderer for the column list and appends the inline clause."+ [driver table-name column-definitions {:keys [primary-key indexes]}]+ (let [base (#'sql-jdbc/create-table!-sql driver table-name column-definitions :primary-key primary-key)]+ (if-let [clause (table-attributes-clause driver indexes)]+ (str base " " clause)+ base)))++(defmethod driver/create-table! :redshift+ [driver db-id table-name column-definitions & {:as opts}]+ ;; Same as the inherited `:sql-jdbc` impl, but inlines a sortkey when one is present. Non-transform callers+ ;; (e.g. uploads) pass no `:indexes`, so the rendered SQL is unchanged for them.+ (let [sql (create-table-sql driver table-name column-definitions opts)]+ (jdbc/with-db-transaction [conn (sql-jdbc.conn/db->pooled-connection-spec db-id)]+ (jdbc/execute! conn sql))))+;;; +----------------------------------------------------------------------------------------------------------------+;;; | metabase.driver.sql impls |;;; +----------------------------------------------------------------------------------------------------------------+diff --git a/modules/drivers/redshift/test/metabase/driver/redshift/index_test.clj b/modules/drivers/redshift/test/metabase/driver/redshift/index_test.cljnew file mode 100644index 00000000000..40fc8ee538f--- /dev/null+++ b/modules/drivers/redshift/test/metabase/driver/redshift/index_test.clj@@ -0,0 +1,168 @@+(ns ^:mb/driver-tests metabase.driver.redshift.index-test+ "Tests for the Redshift inline index driver methods (Index Manager, milestone 0): `supported-index-methods` and the+ sortkey rendering at both creation seams, the CTAS in `compile-transform` (SQL transforms) and the CREATE TABLE in+ `create-table!` (Python transforms).++ The rendering/capability checks are pure and need no connection. `sortkey-inlined-live-test` runs both seams against+ a real Redshift and reads the sortkey back out of the system catalog, so an inlined `SORTKEY` clause is verified to+ actually take effect on the physical table (not just to render)."+ (:require+ [clojure.java.jdbc :as jdbc]+ [clojure.test :refer :all]+ [metabase.driver :as driver]+ [metabase.driver.redshift :as redshift]+ [metabase.driver.sql-jdbc.connection :as sql-jdbc.conn]+ [metabase.test :as mt]+ [metabase.test.data.interface :as tx]+ [metabase.test.data.redshift :as redshift.tx]+ [metabase.util :as u]+ [metabase.util.malli.registry :as mr]))++(deftest ^:parallel feature-flags-test+ (testing "Redshift inlines indexes into the table-creation statement and does not create them afterwards"+ (is (true? (driver/database-supports? :redshift :index/inline-create nil)))+ (is (false? (driver/database-supports? :redshift :index/standalone-create nil)))))++(deftest ^:parallel supported-index-methods-test+ (testing "Redshift advertises inline sortkey + distkey with their form fields"+ (let [methods (driver/supported-index-methods :redshift nil)+ style-options (fn [kind]+ (->> (get-in methods [kind :fields])+ (filter #(= "style" (:name %)))+ first :options (map :value) set))]+ (is (mr/validate :metabase.driver/supported-index-methods methods))+ (is (= {:sortkey :inline :distkey :inline} (update-vals methods :lifecycle)))+ (is (= ["columns" "style"] (map :name (get-in methods [:sortkey :fields]))))+ (is (= ["style" "columns"] (map :name (get-in methods [:distkey :fields]))))+ (is (= #{"compound" "interleaved"} (style-options :sortkey)))+ (is (= #{"key" "all" "even"} (style-options :distkey))))))++;;; ------------------------------------------ DDL rendering ------------------------------------------++;; A sortkey is inlined at table creation, and a transform target is created two ways: the CTAS for SQL transforms+;; (`compile-transform`) and the `CREATE TABLE` for Python transforms (`create-table!`). Each case below drives BOTH+;; seams with the same index, so the same `SORTKEY` clause must appear at both (and the no-sortkey case must add+;; nothing to either: the CTAS delegates to the base, the CREATE TABLE stays upload-safe).+(def ^:private inline-columns+ [["a" "INTEGER"] ["b" "INTEGER"]])++(def ^:private inline-cases+ [{:label "compound sortkey (style omitted), single column"+ :table :events+ :indexes [{:kind :sortkey :columns [{:name "a"}]}]+ :ctas "CREATE TABLE \"events\" COMPOUND SORTKEY (\"a\") AS SELECT 1"+ :create-table "CREATE TABLE \"events\" (\"a\" INTEGER, \"b\" INTEGER) COMPOUND SORTKEY (\"a\")"}+ {:label "interleaved sortkey, multiple columns"+ :table :events+ :indexes [{:kind :sortkey :style :interleaved :columns [{:name "a"} {:name "b"}]}]+ :ctas "CREATE TABLE \"events\" INTERLEAVED SORTKEY (\"a\", \"b\") AS SELECT 1"+ :create-table "CREATE TABLE \"events\" (\"a\" INTEGER, \"b\" INTEGER) INTERLEAVED SORTKEY (\"a\", \"b\")"}+ {:label "schema-qualified target"+ :table :public/events+ :indexes [{:kind :sortkey :columns [{:name "a"}]}]+ :ctas "CREATE TABLE \"public\".\"events\" COMPOUND SORTKEY (\"a\") AS SELECT 1"+ :create-table "CREATE TABLE \"public\".\"events\" (\"a\" INTEGER, \"b\" INTEGER) COMPOUND SORTKEY (\"a\")"}+ {:label "no sortkey -> no inline clause at either seam"+ :table :events+ :indexes []+ :ctas "CREATE TABLE \"events\" AS SELECT 1"+ :create-table "CREATE TABLE \"events\" (\"a\" INTEGER, \"b\" INTEGER)"}+ {:label "key distribution renders DISTSTYLE KEY DISTKEY"+ :table :events+ :indexes [{:kind :distkey :style :key :columns [{:name "a"}]}]+ :ctas "CREATE TABLE \"events\" DISTSTYLE KEY DISTKEY (\"a\") AS SELECT 1"+ :create-table "CREATE TABLE \"events\" (\"a\" INTEGER, \"b\" INTEGER) DISTSTYLE KEY DISTKEY (\"a\")"}+ {:label "all distribution renders DISTSTYLE ALL, no column"+ :table :events+ :indexes [{:kind :distkey :style :all}]+ :ctas "CREATE TABLE \"events\" DISTSTYLE ALL AS SELECT 1"+ :create-table "CREATE TABLE \"events\" (\"a\" INTEGER, \"b\" INTEGER) DISTSTYLE ALL"}+ {:label "even distribution renders DISTSTYLE EVEN, no column"+ :table :events+ :indexes [{:kind :distkey :style :even}]+ :ctas "CREATE TABLE \"events\" DISTSTYLE EVEN AS SELECT 1"+ :create-table "CREATE TABLE \"events\" (\"a\" INTEGER, \"b\" INTEGER) DISTSTYLE EVEN"}+ {:label "distkey + sortkey render in Redshift's required order (distribution then sort)"+ :table :events+ :indexes [{:kind :distkey :style :key :columns [{:name "a"}]}+ {:kind :sortkey :columns [{:name "b"}]}]+ :ctas "CREATE TABLE \"events\" DISTSTYLE KEY DISTKEY (\"a\") COMPOUND SORTKEY (\"b\") AS SELECT 1"+ :create-table (str "CREATE TABLE \"events\" (\"a\" INTEGER, \"b\" INTEGER) "+ "DISTSTYLE KEY DISTKEY (\"a\") COMPOUND SORTKEY (\"b\")")}+ {:label "a SQL-injection payload in a sortkey column is quoted+escaped at both seams"+ :table :events+ :indexes [{:kind :sortkey :columns [{:name "a\"; DROP TABLE x; --"}]}]+ :ctas "CREATE TABLE \"events\" COMPOUND SORTKEY (\"a\"\"; DROP TABLE x; --\") AS SELECT 1"+ :create-table (str "CREATE TABLE \"events\" (\"a\" INTEGER, \"b\" INTEGER) "+ "COMPOUND SORTKEY (\"a\"\"; DROP TABLE x; --\")")}])++(deftest ^:parallel sortkey-inlined-at-both-creation-seams-test+ (doseq [{:keys [label table indexes ctas create-table]} inline-cases]+ (testing label+ (testing "CTAS seam (compile-transform, SQL transforms)"+ (is (= [ctas nil]+ (driver/compile-transform :redshift {:output-table table+ :query {:query "SELECT 1"}+ :indexes indexes}))))+ (testing "CREATE TABLE seam (create-table!, Python transforms)"+ (is (= create-table+ (#'redshift/create-table-sql :redshift table inline-columns {:indexes indexes})))))))++;;; --------------------------------------- Live execute path ----------------------------------------++(defn- sortkey-info+ "Read the sortkey of `schema`.`table` back out of the Redshift catalog as `{:columns [...] :style ...}`, or nil when+ the table has no sortkey. `svv_redshift_columns.sortkey` encodes both facts in one column: a positive value is the+ column's 1-based position in a COMPOUND key; an INTERLEAVED key alternates the sign, so any negative value marks the+ whole key interleaved while `abs` still gives the position."+ [spec schema table]+ (let [rows (jdbc/query spec+ [(str "SELECT column_name, sortkey FROM svv_redshift_columns "+ "WHERE schema_name = ? AND table_name = ? AND sortkey <> 0 "+ "ORDER BY abs(sortkey)")+ schema table])]+ (when (seq rows)+ {:columns (mapv :column_name rows)+ :style (if (some (comp neg? :sortkey) rows) :interleaved :compound)})))++(def ^:private live-cases+ "Each case drives one sortkey through both live seams and asserts the `sortkey-info` the physical table reports.+ Add a row to exercise a new style or column shape end-to-end against a real Redshift."+ [{:label "compound single-column sortkey"+ :indexes [{:kind :sortkey :columns [{:name "a"}]}]+ :expected {:columns ["a"] :style :compound}}+ {:label "interleaved multi-column sortkey"+ :indexes [{:kind :sortkey :style :interleaved :columns [{:name "a"} {:name "b"}]}]+ :expected {:columns ["a" "b"] :style :interleaved}}])++(deftest sortkey-inlined-live-test+ (testing "an inlined SORTKEY clause actually takes effect on the physical table at both creation seams"+ (mt/test-driver :redshift+ (let [db-details (tx/dbdef->connection-details :redshift nil nil)]+ (mt/with-temp [:model/Database database {:engine :redshift, :details db-details}]+ (let [schema (redshift.tx/unique-session-schema)+ spec (sql-jdbc.conn/db->pooled-connection-spec database)]+ (doseq [{:keys [label indexes expected]} live-cases]+ (testing label+ ;; unique per-case table names so the two seams (and parallel runs) don't collide in the shared schema+ (let [ctas-table (tx/db-qualified-table-name (:name database) "sk_ctas")+ create-table (tx/db-qualified-table-name (:name database) "sk_create")+ drop! (fn [t] (jdbc/execute! spec [(format "DROP TABLE IF EXISTS \"%s\".\"%s\"" schema t)]))]+ (testing "CTAS seam (compile-transform): run the rendered CTAS, read the sortkey back"+ (drop! ctas-table)+ (try+ (let [[sql params] (driver/compile-transform+ :redshift+ {:output-table (keyword schema ctas-table)+ :query {:query "SELECT 1 AS a, 2 AS b"}+ :indexes indexes})]+ (jdbc/execute! spec (into [sql] params))+ (is (= expected (sortkey-info spec schema ctas-table))))+ (finally (drop! ctas-table))))+ (testing "CREATE TABLE seam (create-table!): create the table, read the sortkey back"+ (drop! create-table)+ (try+ (driver/create-table! :redshift (u/the-id database) (keyword schema create-table)+ inline-columns {:indexes indexes})+ (is (= expected (sortkey-info spec schema create-table)))+ (finally (drop! create-table)))))))))))))diff --git a/modules/drivers/snowflake/src/metabase/driver/snowflake.clj b/modules/drivers/snowflake/src/metabase/driver/snowflake.cljindex c8b34fb9890..20eaffff391 100644--- a/modules/drivers/snowflake/src/metabase/driver/snowflake.clj+++ b/modules/drivers/snowflake/src/metabase/driver/snowflake.clj@@ -34,7 +34,7 @@[metabase.util :as u][metabase.util.date-2 :as u.date][metabase.util.honey-sql-2 :as h2x]- [metabase.util.i18n :refer [tru]]+ [metabase.util.i18n :refer [deferred-tru tru]][metabase.util.json :as json][metabase.util.log :as log][metabase.util.malli :as mu]@@ -67,10 +67,13 @@:expressions/float true:expressions/date true:identifiers-with-spaces true+ :index/fetch true+ :index/standalone-create true:split-part true:collate true:now true:database-routing true+ :transforms/index-ddl true:uploads true:metadata/table-existence-check true:regex/lookaheads-and-lookbehinds false@@ -1068,6 +1071,60 @@(jdbc/with-db-transaction [conn (sql-jdbc.conn/db->pooled-connection-spec db-id)](jdbc/execute! conn sql))))+;;; +----------------------------------------------------------------------------------------------------------------++;;; | Indexes (Index Manager) |+;;; +----------------------------------------------------------------------------------------------------------------+++;; Snowflake's only physical "index" is the table's single clustering key (`CLUSTER BY`); there are no secondary+;; indexes, so it's a standalone `:clustering` kind. The `:name` is Metabase-side only: the warehouse keeps clustering+;; keys unnamed, so fetch reports `:name nil` and reconcile matches by kind + columns.++(defmethod driver/supported-index-methods :snowflake+ [_driver _database]+ {:clustering {:lifecycle :standalone+ :display-name (deferred-tru "Clustering key")+ :fields [driver.common/index-name-field driver.common/index-columns-field]}})++(defmethod driver/compile-create-index :snowflake+ [driver schema table {:keys [columns]}]+ ;; Re-issuing the same CLUSTER BY is a no-op, so no IF NOT EXISTS needed.+ (let [target (apply sql.u/quote-name driver :table (if (not-empty schema) [schema table] [table]))+ cols (str/join ", " (map #(sql.u/quote-name driver :field (:name %)) columns))]+ [[(format "ALTER TABLE %s CLUSTER BY (%s)" target cols)]]))++(defn- parse-clustering-key+ "Parse a Snowflake `CLUSTERING_KEY` string like `LINEAR(category, price)` into its top-level column names/expressions+ in order. Returns nil for a table with no clustering key."+ [clustering-key]+ (when-let [s (not-empty (some-> clustering-key str/trim))]+ (let [inner (or (second (re-matches #"(?is)\s*LINEAR\s*\((.*)\)\s*" s)) s)]+ (->> (driver.common/split-top-level-commas inner)+ (map #(driver.common/unquote-ident (str/trim %) \"))+ (remove str/blank?)+ vec))))++;; `CLUSTERING_KEY` lives in the current database's INFORMATION_SCHEMA; a blank schema falls back to `current_schema()`.+(defmethod driver/fetch-table-indexes :snowflake+ [_driver database schema table]+ (let [clustering-key (-> (jdbc/query+ (sql-jdbc.conn/db->pooled-connection-spec database)+ [(str "SELECT clustering_key FROM information_schema.tables "+ "WHERE table_schema = COALESCE(?, current_schema()) AND table_name = ?")+ (not-empty schema) table])+ first :clustering_key)]+ (if-let [columns (not-empty (parse-clustering-key clustering-key))]+ [{:name nil+ :kind :clustering+ :access-method nil+ :is-unique false+ :is-primary false+ :is-valid true+ :key-columns columns+ :include-columns []+ :partial-predicate nil+ :definition (format "CLUSTER BY (%s)" (str/join ", " columns))}]+ [])))+(defmethod driver/table-name-length-limit :snowflake[_driver];; https://docs.snowflake.com/en/sql-reference/identifiersdiff --git a/modules/drivers/snowflake/test/metabase/driver/snowflake_test.clj b/modules/drivers/snowflake/test/metabase/driver/snowflake_test.cljindex 691690e8bff..eae9eadac64 100644--- a/modules/drivers/snowflake/test/metabase/driver/snowflake_test.clj+++ b/modules/drivers/snowflake/test/metabase/driver/snowflake_test.clj@@ -1735,6 +1735,18 @@(is (some? (mt/rows (qp/process-query query)))"Hour bucketing on a time field from a source query should not error")))))))+(deftest ^:parallel compile-create-index-test+ (testing "clustering renders ALTER TABLE ... CLUSTER BY with quoted identifiers"+ (is (= [["ALTER TABLE \"sch\".\"t\" CLUSTER BY (\"category\", \"price\")"]]+ (driver/compile-create-index :snowflake "sch" "t"+ {:kind :clustering :name "by_cat"+ :columns [{:name "category"} {:name "price"}]}))))+ (testing "a SQL-injection payload in a clustering column is quoted+escaped, so it can only ever be an identifier"+ (is (= [["ALTER TABLE \"t\" CLUSTER BY (\"c\"\"; DROP TABLE x; --\")"]]+ (driver/compile-create-index :snowflake nil "t"+ {:kind :clustering :name "by_cat"+ :columns [{:name "c\"; DROP TABLE x; --"}]})))))+(deftest upload-type->database-type-test(testing "upload types render to the expected Snowflake DDL via the generic create-table! path";; End-to-end behavior is covered by [[metabase.upload.impl-test]].diff --git a/modules/drivers/sqlserver/src/metabase/driver/sqlserver.clj b/modules/drivers/sqlserver/src/metabase/driver/sqlserver.cljindex c70f71395f3..3407faeded0 100644--- a/modules/drivers/sqlserver/src/metabase/driver/sqlserver.clj+++ b/modules/drivers/sqlserver/src/metabase/driver/sqlserver.clj@@ -1,6 +1,6 @@(ns metabase.driver.sqlserver"Driver for SQLServer databases. Uses the official Microsoft JDBC driver under the hood (pre-0.25.0, used jTDS)."- (:refer-clojure :exclude [mapv get-in])+ (:refer-clojure :exclude [mapv get-in not-empty])(:require[clojure.java.io :as io][clojure.java.jdbc :as jdbc]@@ -11,6 +11,7 @@[java-time.api :as t][metabase.driver :as driver][metabase.driver-api.core :as driver-api]+ [metabase.driver.common :as driver.common][metabase.driver.connection :as driver.conn][metabase.driver.sql :as driver.sql][metabase.driver.sql-jdbc :as sql-jdbc]@@ -29,12 +30,12 @@[metabase.sql-tools.core :as sql-tools][metabase.util :as u][metabase.util.honey-sql-2 :as h2x]- [metabase.util.i18n :refer [tru]]+ [metabase.util.i18n :refer [deferred-tru tru]][metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.match :as match][metabase.util.memoize :as memoize]- [metabase.util.performance :as perf :refer [mapv get-in]]+ [metabase.util.performance :as perf :refer [mapv get-in not-empty]][next.jdbc :as next.jdbc])(:import(java.sql Connection DatabaseMetaData PreparedStatement ResultSet Time)@@ -56,6 +57,8 @@:expression-literals true;; Index sync is turned off across the application as it is not used ATM.:index-info false+ :index/fetch true+ :index/standalone-create true:now true:regex false:test/jvm-timezone-setting false@@ -1248,6 +1251,98 @@(quote-schema schema)quoted-user)])))))+;;; +----------------------------------------------------------------------------------------------------------------++;;; | Indexes (Index Manager) |+;;; +----------------------------------------------------------------------------------------------------------------+++(defmethod driver/supported-index-methods :sqlserver+ [_driver _database]+ ;; Both rowstore kinds are B-tree, so both take UNIQUE and per-column ASC/DESC. Columnstore/XML/spatial are niche+ ;; and left out.+ (let [fields [driver.common/index-name-field+ (assoc driver.common/index-columns-field :directions true)+ driver.common/index-unique-field]]+ {:nonclustered {:lifecycle :standalone+ :display-name (deferred-tru "Nonclustered")+ :fields fields}+ :clustered {:lifecycle :standalone+ :display-name (deferred-tru "Clustered")+ :fields fields}}))++(defn- index-column-sql+ "Quote one indexed column, appending its `ASC`/`DESC` direction when set."+ [{col-name :name :keys [direction]}]+ (cond-> (quote-field col-name)+ direction (str " " (u/upper-case-en (name direction)))))++(defn- create-index-sql+ [schema table {index-name :name, :keys [kind columns unique]}]+ (let [target (apply sql.u/quote-name :sqlserver :table (if (not-empty schema) [schema table] [table]))+ cols (str/join ", " (map index-column-sql columns))]+ (format "CREATE %s%s INDEX %s ON %s (%s)"+ (if unique "UNIQUE " "")+ (if (= kind :clustered) "CLUSTERED" "NONCLUSTERED")+ (quote-field index-name)+ target+ cols)))++(defn- sql-string-literal+ "A SQL Server `N'...'` string literal for trusted `s`, escaping embedded quotes."+ [s]+ (str "N'" (sql.u/escape-sql s :ansi) \'))++(defmethod driver/compile-create-index :sqlserver+ [_driver schema table {index-name :name, :keys [if-not-exists] :as structured}]+ (let [create (create-index-sql schema table structured)]+ (if-not if-not-exists+ [[create]]+ ;; SQL Server has no `CREATE INDEX IF NOT EXISTS`, so guard the create with a T-SQL `IF NOT EXISTS (...)` that+ ;; runs it only when no index of this name exists on the table.+ (let [target (apply sql.u/quote-name :sqlserver :table (if (not-empty schema) [schema table] [table]))]+ [[(format "IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = %s AND object_id = OBJECT_ID(%s)) %s"+ (sql-string-literal index-name)+ (sql-string-literal target)+ create)]]))))++(defn- bit->bool+ "JDBC may hand back a SQL Server `bit` as a Boolean or a 0/1 number; normalize either to a boolean."+ [v]+ (if (number? v) (not (zero? v)) (boolean v)))++(defn- index-rows->index+ "Collapse one index's per-column `sys.index_columns` rows (key columns first, then INCLUDE columns) into an index map."+ [rows]+ (let [{:keys [index_name index_type is_unique is_primary is_disabled filter_definition]} (first rows)]+ {:name index_name+ :kind (if (= index_type "CLUSTERED") :clustered :nonclustered)+ :access-method (some-> index_type u/lower-case-en)+ :is-unique (bit->bool is_unique)+ :is-primary (bit->bool is_primary)+ :is-valid (not (bit->bool is_disabled))+ :key-columns (->> rows (remove (comp bit->bool :is_included)) (mapv :column_name))+ :include-columns (->> rows (filter (comp bit->bool :is_included)) (mapv :column_name))+ :partial-predicate filter_definition+ :definition nil}))++;; Only rowstore clustered (`type` 1) and nonclustered (2) indexes are reported; heaps, columnstore, XML, and spatial+;; are skipped. A missing table makes `OBJECT_ID` return NULL, so the predicate matches nothing and fetch returns [].+(defmethod driver/fetch-table-indexes :sqlserver+ [_driver database schema table]+ (let [qualified (apply sql.u/quote-name :sqlserver :table (if (not-empty schema) [schema table] [table]))]+ (->> (jdbc/query+ (sql-jdbc.conn/db->pooled-connection-spec database)+ ["SELECT i.name AS index_name, i.type_desc AS index_type, i.is_unique, i.is_primary_key AS is_primary,+ i.is_disabled, i.filter_definition, c.name AS column_name,+ ic.is_included_column AS is_included, ic.key_ordinal, ic.index_column_id+ FROM sys.indexes i+ JOIN sys.index_columns ic ON ic.object_id = i.object_id AND ic.index_id = i.index_id+ JOIN sys.columns c ON c.object_id = ic.object_id AND c.column_id = ic.column_id+ WHERE i.object_id = OBJECT_ID(?) AND i.type IN (1, 2)+ ORDER BY i.index_id, ic.is_included_column, ic.key_ordinal, ic.index_column_id"+ qualified])+ (partition-by :index_name)+ (mapv index-rows->index))))+(defmethod driver/llm-sql-dialect-resource :sqlserver [_]"metabot/prompts/dialects/sqlserver.md")diff --git a/modules/drivers/sqlserver/test/metabase/driver/sqlserver_test.clj b/modules/drivers/sqlserver/test/metabase/driver/sqlserver_test.cljindex de6fdce082b..507622bfdd0 100644--- a/modules/drivers/sqlserver/test/metabase/driver/sqlserver_test.clj+++ b/modules/drivers/sqlserver/test/metabase/driver/sqlserver_test.clj@@ -982,3 +982,35 @@(lib/expression "diff-minutes" diff-minutes)(qp/process-query)(mt/rows))))))))++(deftest ^:parallel compile-create-index-test+ (testing "nonclustered renders with double-quoted identifiers; UNIQUE only when asked, ASC/DESC per column"+ (is (= [["CREATE NONCLUSTERED INDEX \"by_cat\" ON \"t\" (\"category\")"]]+ (driver/compile-create-index :sqlserver nil "t"+ {:kind :nonclustered :name "by_cat" :columns [{:name "category"}]})))+ (is (= [["CREATE UNIQUE NONCLUSTERED INDEX \"by_cat\" ON \"dbo\".\"t\" (\"category\" DESC, \"price\" ASC)"]]+ (driver/compile-create-index :sqlserver "dbo" "t"+ {:kind :nonclustered :name "by_cat" :unique true+ :columns [{:name "category" :direction :desc} {:name "price" :direction :asc}]}))))+ (testing "clustered renders the CLUSTERED keyword"+ (is (= [["CREATE CLUSTERED INDEX \"by_cat\" ON \"t\" (\"category\")"]]+ (driver/compile-create-index :sqlserver nil "t"+ {:kind :clustered :name "by_cat" :columns [{:name "category"}]}))))+ (testing "SQL Server has no CREATE INDEX IF NOT EXISTS, so :if-not-exists guards via a T-SQL IF NOT EXISTS block"+ (let [[[stmt]] (driver/compile-create-index :sqlserver "dbo" "t"+ {:kind :nonclustered :name "by_cat" :if-not-exists true+ :columns [{:name "category"}]})]+ (is (str/starts-with? stmt "IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'by_cat'")+ "guards on the index name before creating")+ (is (str/includes? stmt "CREATE NONCLUSTERED INDEX \"by_cat\"")+ "still emits the create")))+ (testing "a SQL-injection payload is escaped in every context the name lands: quoted identifier and N'' literal"+ (let [[[stmt]] (driver/compile-create-index :sqlserver "dbo" "t"+ {:kind :nonclustered :name "by\"cat'; DROP TABLE x; --" :if-not-exists true+ :columns [{:name "cat\"; DROP TABLE x; --"}]})]+ (is (str/includes? stmt "CREATE NONCLUSTERED INDEX \"by\"\"cat'; DROP TABLE x; --\"")+ "index name is a doubled-quote identifier in the CREATE")+ (is (str/includes? stmt "(\"cat\"\"; DROP TABLE x; --\")")+ "column is a doubled-quote identifier")+ (is (str/includes? stmt "name = N'by\"cat''; DROP TABLE x; --'")+ "name in the IF NOT EXISTS guard is a doubled-quote N'' string literal"))))diff --git a/resources/migrations/064/20260615_metabase_table_indexes.yaml b/resources/migrations/064/20260615_metabase_table_indexes.yamlnew file mode 100644index 00000000000..21c899bb2aa--- /dev/null+++ b/resources/migrations/064/20260615_metabase_table_indexes.yaml@@ -0,0 +1,128 @@+## Index/clustering hints declared on a transform target table, reapplied on each full transform run.+## Each request binds to a transform; the target table is read off the transform's target_table_id.++databaseChangeLog:+ - changeSet:+ id: v64.ixrq01+ author: Ngoc Khuat+ comment: Create metabase_table_indexes table for transform target index/clustering hints+ changes:+ - createTable:+ tableName: metabase_table_indexes+ remarks: Index/clustering hints declared on a transform target, reapplied on each full transform run+ columns:+ - column:+ name: id+ type: int+ remarks: Auto-incrementing primary key+ autoIncrement: true+ constraints:+ primaryKey: true+ nullable: false+ - column:+ name: transform_id+ type: int+ remarks: FK to the transform that owns this index request+ constraints:+ nullable: false+ - column:+ name: index_name+ type: varchar(255)+ remarks: Physical index name, rendered verbatim into DDL+ constraints:+ nullable: false+ - column:+ name: structured+ type: ${text.type}+ remarks: JSON structured index definition (kind, columns, ...)+ constraints:+ nullable: false+ - column:+ name: status+ type: varchar(20)+ defaultValue: create-pending+ remarks: "Lifecycle status: create-pending, update-pending, delete-pending, running, succeeded, or failed"+ constraints:+ nullable: false+ - column:+ name: error_message+ type: ${text.type}+ remarks: Error from the last failed apply, if any+ constraints:+ nullable: true+ - column:+ name: created_by+ type: int+ remarks: FK to core_user.id who created this request+ constraints:+ nullable: true+ - column:+ name: created_at+ type: ${timestamp_type}+ remarks: Timestamp when this request was created+ constraints:+ nullable: false+ - column:+ name: updated_at+ type: ${timestamp_type}+ remarks: Timestamp when this request was last updated+ constraints:+ nullable: false+ - column:+ name: last_executed_at+ type: ${timestamp_type}+ remarks: Timestamp of the last apply attempt+ constraints:+ nullable: true++ - changeSet:+ id: v64.ixrq02+ author: Ngoc Khuat+ comment: Add unique constraint on metabase_table_indexes (transform_id, index_name)+ changes:+ - addUniqueConstraint:+ tableName: metabase_table_indexes+ columnNames: transform_id, index_name+ constraintName: uq_table_indexes_transform_id_index_name++ ## Indexes are created before the FK constraints below: MySQL/MariaDB require an+ ## index to back every FK and reuse an existing one, so this keeps rollback working+ ## (the FK is dropped before the index it would otherwise still need). Postgres+ ## doesn't auto-index FKs, which is what fks-are-indexed-test checks for.+ - changeSet:+ id: v64.ixrq04+ author: Ngoc Khuat+ comment: Index metabase_table_indexes.created_by+ changes:+ - createIndex:+ tableName: metabase_table_indexes+ indexName: idx_table_indexes_created_by+ columns:+ - column:+ name: created_by++ - changeSet:+ id: v64.ixrq05+ author: Ngoc Khuat+ comment: Add FK on metabase_table_indexes.transform_id+ changes:+ - addForeignKeyConstraint:+ baseTableName: metabase_table_indexes+ baseColumnNames: transform_id+ referencedTableName: transform+ referencedColumnNames: id+ constraintName: fk_table_indexes_transform_id+ onDelete: CASCADE++ - changeSet:+ id: v64.ixrq07+ author: Ngoc Khuat+ comment: Add FK on metabase_table_indexes.created_by+ changes:+ - addForeignKeyConstraint:+ baseTableName: metabase_table_indexes+ baseColumnNames: created_by+ referencedTableName: core_user+ referencedColumnNames: id+ constraintName: fk_table_indexes_created_by+ onDelete: SET NULLdiff --git a/src/metabase/api_routes/routes.clj b/src/metabase/api_routes/routes.cljindex 88739050173..82e2bfcd6c5 100644--- a/src/metabase/api_routes/routes.clj+++ b/src/metabase/api_routes/routes.clj@@ -31,6 +31,7 @@[metabase.glossary.api][metabase.health-inspector.api][metabase.indexed-entities.api]+ [metabase.indexes-rest.api][metabase.llm.api][metabase.logger.api][metabase.login-history.api]@@ -97,6 +98,7 @@metabase.geojson.api/keep-memetabase.glossary.api/keep-memetabase.indexed-entities.api/keep-me+ metabase.indexes-rest.api/keep-memetabase.logger.api/keep-memetabase.login-history.api/keep-memetabase.mcp.api/keep-me@@ -197,6 +199,7 @@"/glossary" (+auth 'metabase.glossary.api)"/google" (+auth metabase.sso.api/google-auth-routes)"/health-inspector" (+auth 'metabase.health-inspector.api)+ "/index" (+auth 'metabase.indexes-rest.api)"/ldap" (+auth metabase.sso.api/ldap-routes)"/llm" (+auth metabase.llm.api/routes)"/logger" (+auth 'metabase.logger.api)diff --git a/src/metabase/driver.clj b/src/metabase/driver.cljindex de10cffa0c9..0ea3812eb29 100644--- a/src/metabase/driver.clj+++ b/src/metabase/driver.clj@@ -844,6 +844,22 @@;; Does this driver support executing python transforms?:transforms/python;;+ ;; Does this driver support creating an index (in the broad sense -- see the comment above+ ;; [[supported-index-methods]]) as a standalone statement after the transform target table already exists?+ ;; Drivers with this feature implement [[supported-index-methods]] and [[compile-create-index]]. Contrast with+ ;; drivers that inline indexes into the table-creation statement itself (e.g. Redshift sortkeys).+ :index/standalone-create+ ;;+ ;; Does this driver inline an index into the table-creation statement itself (e.g. Redshift SORTKEY, BigQuery+ ;; CLUSTER BY) rather than creating it afterwards? Drivers with this feature implement [[supported-index-methods]]+ ;; and render the index in [[compile-transform]] (the CTAS for a SQL transform) and/or [[create-table!]] (the+ ;; CREATE TABLE for a Python transform).+ :index/inline-create+ ;;+ ;; Does this driver support reading the indexes that physically exist on a table? Drivers with this feature+ ;; implement [[fetch-table-indexes]].+ :index/fetch+ ;;;; Does this driver support calculating dependencies of native queries?:dependencies/native;;@@ -1543,6 +1559,122 @@dispatch-on-initialized-driver:hierarchy #'hierarchy)+;;; +----------------------------------------------------------------------------------------------------------------++;;; | Indexes (Index Manager) |+;;; +----------------------------------------------------------------------------------------------------------------+++;; "Index" is used in the broad sense here: anything that shapes the physical layout of a transform's target table.+;; Postgres/MySQL use real indexes, Snowflake/BigQuery clustering keys, Redshift sort/dist keys.++(mr/def ::index-field+ "One form field describing how to request an index: the same shape as a [[connection-properties]] descriptor, plus a+ `:columns` type for the indexed columns."+ [:map+ ;; key written into the structured request body, e.g. "unique"+ [:name :string]+ ;; deferred-i18n label (or string)+ [:display-name :any]+ ;; deferred-i18n user facing description+ [:description {:optional true} :any]+ [:type [:enum :string :boolean :select :integer :columns]]+ [:required {:optional true} :boolean]+ ;; `:columns` only: whether per-column asc/desc is offered+ [:directions {:optional true} :boolean]+ ;; `:select` only: choices, each `:value` an enum value of the kind's `::index-structured` branch+ [:options {:optional true} [:sequential [:map+ [:name :any]+ [:value :string]]]]])++(mr/def ::index-method+ "Metadata for one index kind a driver supports."+ [:map+ ;; deferred-i18n label for the index kind, e.g. "B-Tree" (localizable, so drivers own it rather than the FE)+ [:display-name :any]+ ;; deferred-i18n description of when to use this kind+ [:description {:optional true} :any]+ ;; :standalone = created by a separate statement after the table; :inline = part of the CREATE TABLE+ [:lifecycle [:enum :standalone :inline]]+ [:fields [:sequential [:ref ::index-field]]]])++(mr/def ::supported-index-methods+ "Return shape of [[supported-index-methods]]: index-kind -> metadata."+ [:map-of :keyword [:ref ::index-method]])++(defmulti supported-index-methods+ "Return the index methods this driver supports for transform target tables, as a map of `index-kind` -> metadata+ matching `::supported-index-methods`. Defaults to `{}` for drivers with no index support."+ {:added "0.63.0", :arglists '([driver database])}+ dispatch-on-initialized-driver+ :hierarchy #'hierarchy)++(defmethod supported-index-methods :default+ [_driver _database]+ {})++(defmulti compile-create-index+ "Render a `:standalone` index into the DDL statement(s) that create it on the existing `table` in `schema`.+ `structured` is the index description, e.g. `{:kind :btree, :name \"foo_bar\", :columns [{:name \"bar\"}]}`; it may+ also carry `:unique` and `:if-not-exists` booleans. The index's `:name` is rendered verbatim as the physical name.++ Returns a vector of `[sql-string & params]` queries suitable for [[execute-raw-queries!]]."+ {:added "0.63.0", :arglists '([driver schema table structured])}+ dispatch-on-initialized-driver+ :hierarchy #'hierarchy)++(defmulti refresh-table-stats!+ "Refresh the database's table statistics (e.g. `ANALYZE`) for `table` after a transform run materializes it, so+ query planners see fresh stats. Defaults to a no-op."+ {:added "0.63.0", :arglists '([driver database schema table transform-type])}+ dispatch-on-initialized-driver+ :hierarchy #'hierarchy)++(defmethod refresh-table-stats! :default+ [_driver _database _schema _table _transform-type]+ nil)++(mr/def ::table-index+ "One physical index from [[fetch-table-indexes]], normalized into a cross-driver shape."+ [:map+ {:closed true}+ ;; the physical index name, or nil for an unnamed inline key+ [:name [:maybe :string]]+ ;; cross-driver category: :btree / :skip-index / :order-by / :sortkey+ [:kind :keyword]+ ;; warehouse-native type/method: btree/gin/... (PG), minmax/set/... (CH skip-index), compound/interleaved+ ;; (Redshift sortkey); nil for a ClickHouse ORDER BY+ [:access-method [:maybe :string]]+ [:is-unique :boolean]+ [:is-primary :boolean]+ [:is-valid :boolean]+ ;; key columns in index order; an expression column carries its expression text (e.g. "lower(email)"). never nil:+ ;; drivers fall back to the catalog's expression text rather than emit a missing name.+ [:key-columns [:sequential :string]]+ ;; non-key INCLUDE / covering columns. nil-tolerant unlike :key-columns, since these aren't backfilled.+ [:include-columns [:sequential [:maybe :string]]]+ ;; the WHERE clause of a partial index, else nil+ [:partial-predicate [:maybe :string]]+ ;; the catalog's own DDL/clause, the most faithful representation+ [:definition [:maybe :string]]])++(mr/def ::fetch-table-indexes.result+ [:sequential [:ref ::table-index]])++(defmulti fetch-table-indexes+ "Fetch the physical indexes on `table` in `schema` of `database`, one normalized map per catalog index, matching+ `::fetch-table-indexes.result`. Inline sort keys (ClickHouse `ORDER BY`, Redshift `SORTKEY`) have `:name nil`.++ Distinct from the sync-side [[describe-table-indexes]]/[[describe-indexes]], which capture only single-column indexes+ to flag fields as indexed; this returns full physical detail (uniqueness, partial predicate, INCLUDE columns, key+ order, raw DDL)."+ {:added "0.63.0", :arglists '([driver database schema table])}+ dispatch-on-initialized-driver+ :hierarchy #'hierarchy)++(defmethod fetch-table-indexes :default+ [driver _database _schema _table]+ (throw (ex-info (format "fetch-table-indexes is not implemented for driver %s" driver)+ {:driver driver})))+(defmulti drop-table!"Drop a table named `table-name`. If the table doesn't exist it will not be dropped. `table-name` may be qualifiedby schema e.g.diff --git a/src/metabase/driver/common.clj b/src/metabase/driver/common.cljindex 9f4f1819b22..0c7263f497c 100644--- a/src/metabase/driver/common.clj+++ b/src/metabase/driver/common.clj@@ -147,6 +147,63 @@:type :hidden:default false})+;;; +----------------------------------------------------------------------------------------------------------------++;;; | Index field descriptors (Index Manager) |+;;; +----------------------------------------------------------------------------------------------------------------+++;; Field descriptors for `driver/supported-index-methods`: same shape as the connection-property descriptors above so+;; the FE renders them the same way, plus a `:columns` type for picking the indexed columns. Each `:name` (and each+;; select option `:value`) matches a key/enum in the kind's `::index-structured` branch (metabase.indexes.schema).++(def index-name-field+ "Descriptor for the index name."+ {:name "name" :display-name (deferred-tru "Give your index a name") :type :string :required true})++(def index-columns-field+ "Descriptor for the indexed columns."+ ;; :directions (per-column asc/desc) is off by default; only btree consumes it, so it opts in.+ {:name "columns" :display-name (deferred-tru "Columns")+ :description (deferred-tru "The column(s) the index will be built on. Usually the ones you filter or join by.")+ :type :columns :required true})++(def index-unique-field+ "Descriptor for the btree unique toggle."+ {:name "unique" :display-name (deferred-tru "Unique")+ :description (deferred-tru "Enforce uniqueness across rows for indexed columns.")+ :type :boolean})++(def index-granularity-field+ "Descriptor for a ClickHouse skip-index granularity."+ {:name "granularity" :display-name (deferred-tru "Granularity") :type :integer})++;; Helpers for parsing a warehouse's stored key/index column list (a `CLUSTER BY`, `ORDER BY`, sorting key, ...) back+;; into the bare column names the managed side stores.++(defn split-top-level-commas+ "Split `s` on commas that aren't nested in parens or inside a `` ` ``/`'`/`\"` quote span, so neither a function key+ like `toStartOfInterval(d, INTERVAL 1 DAY)` nor a quoted name like `\"weird,name\"` is torn at an inner comma."+ [^String s]+ (loop [i 0, depth 0, q nil, start 0, acc []]+ (if (< i (.length s))+ (let [c (nth s i)]+ (cond+ q (recur (inc i) depth (when-not (= c q) q) start acc)+ (or (= c \`) (= c \') (= c \")) (recur (inc i) depth c start acc)+ (= c \() (recur (inc i) (inc depth) q start acc)+ (= c \)) (recur (inc i) (dec depth) q start acc)+ (and (= c \,) (zero? depth)) (recur (inc i) depth q (inc i) (conj acc (subs s start i)))+ :else (recur (inc i) depth q start acc)))+ (conj acc (subs s start)))))++(defn unquote-ident+ "Strip a wrapping `quote-char` pair off a quoted identifier (doubled `quote-char` unescaped), so it matches the bare+ column name the managed side stores. Leaves bare names and expressions untouched."+ [^String s quote-char]+ (let [q (str quote-char)]+ (if (and (> (count s) 1) (str/starts-with? s q) (str/ends-with? s q))+ (str/replace (subs s 1 (dec (count s))) (str q q) q)+ s)))+(def advanced-options-start"Map representing the start of the advanced option section in a DB connection form. Fields in this section shouldhave their visibility controlled using the `visible-if` property."diff --git a/src/metabase/driver/mysql.clj b/src/metabase/driver/mysql.cljindex c04e33f869d..d9fecdf472d 100644--- a/src/metabase/driver/mysql.clj+++ b/src/metabase/driver/mysql.clj@@ -2,6 +2,7 @@"MySQL driver. Builds off of the SQL-JDBC driver."(:refer-clojure :exclude [get-in some not-empty])(:require+ [buddy.core.codecs :as codecs][clojure.java.io :as jio][clojure.java.jdbc :as jdbc][clojure.set :as set]@@ -35,7 +36,7 @@[metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.memoize :as memoize]- [metabase.util.performance :as perf :refer [get-in not-empty some]]+ [metabase.util.performance :as perf :refer [get-in mapv not-empty some]][next.jdbc :as next.jdbc])(:import(java.io File)@@ -69,6 +70,8 @@:full-join false;; Index sync is turned off across the application as it is not used ATM.:index-info false+ :index/fetch true+ :index/standalone-create true:now true:percentile-aggregations false:persist-models true@@ -91,8 +94,7 @@:metadata/table-existence-check true:transforms/python true:transforms/table true- ;; currently disabled as :describe-indexes is not supported- :transforms/index-ddl false+ :transforms/index-ddl true:describe-default-expr true:describe-is-nullable true:describe-is-generated true@@ -1448,5 +1450,102 @@(ex-message e)))]result))))))+;;; +----------------------------------------------------------------------------------------------------------------++;;; | Indexes (Index Manager) |+;;; +----------------------------------------------------------------------------------------------------------------+++(defmethod driver/supported-index-methods :mysql+ [_driver _database]+ ;; spatial is niche, and InnoDB silently rewrites USING HASH into btree, so neither is offered.+ (let [name+cols [driver.common/index-name-field driver.common/index-columns-field]]+ {:btree {:lifecycle :standalone+ :display-name (deferred-tru "B-Tree")+ :fields [driver.common/index-name-field+ driver.common/index-unique-field+ driver.common/index-columns-field]}+ :fulltext {:lifecycle :standalone+ :display-name (deferred-tru "Full-text")+ :fields name+cols}}))++(defn- mysql-index-column-sql+ "Quote an indexed column, appending `ASC`/`DESC` only for btree (fulltext has no per-column order)."+ [btree? {col-name :name :keys [direction]}]+ (cond-> (sql.u/quote-name :mysql :field col-name)+ (and btree? direction) (str " " (u/upper-case-en (name direction)))))++(defn- create-index-sql+ [schema table {index-name :name, :keys [kind columns unique]}]+ (let [fulltext? (= kind :fulltext)+ target (apply sql.u/quote-name :mysql :table (if (not-empty schema) [schema table] [table]))+ cols (str/join ", " (map #(mysql-index-column-sql (not fulltext?) %) columns))]+ (format "CREATE %sINDEX %s ON %s (%s)"+ (cond fulltext? "FULLTEXT "+ unique "UNIQUE "+ :else "")+ (sql.u/quote-name :mysql :field index-name)+ target+ cols)))++(defn- utf8-string-expr+ "A MySQL expression evaluating to the string `s`, hex-encoded so there is nothing to escape and SQL injection is+ impossible. Index names are unvalidated free-form user input and `sql.u/escape-sql` is explicitly not safe for that+ (a backslash defeats its quote-doubling, and its escaping is session-dependent), so we use the hex pattern instead."+ [^String s]+ (format "CONVERT(UNHEX('%s') USING utf8mb4)" (codecs/bytes->hex (.getBytes s "UTF-8"))))++(defmethod driver/compile-create-index :mysql+ [_driver schema table {index-name :name, :keys [if-not-exists] :as structured}]+ (let [create (create-index-sql schema table structured)]+ (if-not if-not-exists+ [[create]]+ ;; MySQL has no `CREATE INDEX IF NOT EXISTS`, and the apply path re-issues creates on full rebuilds, so guard+ ;; with dynamic SQL that runs the create only when no index of this name exists. Strings (including the whole+ ;; CREATE statement) are inlined as hex-encoded expressions rather than bound params because the MariaDB driver+ ;; rejects `?` placeholders inside `SET @var := (SELECT ...)`.+ [[(format "SET @mb_idx_exists := (SELECT COUNT(*) FROM information_schema.statistics+ WHERE table_schema = %s AND table_name = %s AND index_name = %s)"+ (if (not-empty schema) (utf8-string-expr schema) "DATABASE()")+ (utf8-string-expr table)+ (utf8-string-expr index-name))]+ [(format "SET @mb_idx_sql := IF(@mb_idx_exists > 0, 'DO 0', %s)"+ (utf8-string-expr create))]+ ["PREPARE mb_idx_stmt FROM @mb_idx_sql"]+ ["EXECUTE mb_idx_stmt"]+ ["DEALLOCATE PREPARE mb_idx_stmt"]])))++(defn- mysql-index-type->kind+ [index-type]+ (case (u/upper-case-en (or index-type ""))+ "FULLTEXT" :fulltext+ "SPATIAL" :spatial+ :btree))++(defn- mysql-index-rows->index+ "Collapse one index's per-column `information_schema.statistics` rows (ordered by `SEQ_IN_INDEX`) into an index map."+ [rows]+ (let [{:keys [index_name non_unique index_type]} (first rows)]+ {:name index_name+ :kind (mysql-index-type->kind index_type)+ :access-method (some-> index_type u/lower-case-en)+ :is-unique (zero? (long non_unique))+ :is-primary (= index_name "PRIMARY")+ :is-valid true+ :key-columns (mapv :column_name rows)+ :include-columns []+ :partial-predicate nil+ :definition nil}))++(defmethod driver/fetch-table-indexes :mysql+ [_driver database schema table]+ (->> (jdbc/query+ (sql-jdbc.conn/db->pooled-connection-spec database)+ ["SELECT index_name, seq_in_index, column_name, non_unique, index_type+ FROM information_schema.statistics+ WHERE table_schema = COALESCE(?, DATABASE()) AND table_name = ?+ ORDER BY index_name, seq_in_index"+ (not-empty schema) table])+ (partition-by :index_name)+ (mapv mysql-index-rows->index)))+(defmethod driver/llm-sql-dialect-resource :mysql [_]"metabot/prompts/dialects/mysql.md")diff --git a/src/metabase/driver/postgres.clj b/src/metabase/driver/postgres.cljindex 58e7ac39039..e35ffe26902 100644--- a/src/metabase/driver/postgres.clj+++ b/src/metabase/driver/postgres.clj@@ -32,7 +32,7 @@[metabase.util :as u][metabase.util.date-2 :as u.date][metabase.util.honey-sql-2 :as h2x]- [metabase.util.i18n :refer [trs tru]]+ [metabase.util.i18n :refer [deferred-tru trs tru]][metabase.util.log :as log][metabase.util.malli :as mu][metabase.util.memoize :as memoize]@@ -41,7 +41,7 @@[taoensso.nippy :as nippy])(:import(java.io DataInput DataOutput StringReader)- (java.sql Connection ResultSet ResultSetMetaData Statement Types)+ (java.sql Array Connection ResultSet ResultSetMetaData Statement Types)(java.time LocalDateTime OffsetDateTime OffsetTime)(org.apache.commons.codec.binary Hex)(org.postgresql.copy CopyManager)@@ -81,6 +81,8 @@:expressions/integer true:expressions/text true:identifiers-with-spaces true+ :index/fetch true+ :index/standalone-create true:metadata/table-existence-check true:now true:persist-models true@@ -1334,6 +1336,114 @@(let [sql [[(format "CREATE SCHEMA IF NOT EXISTS %s;" (quote-schema schema))]]](driver/execute-raw-queries! driver conn-spec sql))))+;;; +----------------------------------------------------------------------------------------------------------------++;;; | Indexes (Index Manager) |+;;; +----------------------------------------------------------------------------------------------------------------+++(defmethod driver/supported-index-methods :postgres+ [_driver _database]+ ;; btree is the only method that supports UNIQUE; gin/gist/brin are containment/range methods. The niche methods+ ;; (hash, spgist) and partial/expression indexes are intentionally left out.+ (let [name+cols [driver.common/index-name-field driver.common/index-columns-field]]+ ;; btree is the only method where column order direction matters, so it opts into the asc/desc picker.+ {:btree {:lifecycle :standalone+ :display-name (deferred-tru "B-Tree")+ :description (deferred-tru "Default. Best for equality and range queries on sortable data; use it for most columns you filter, sort, or join by.")+ :fields [driver.common/index-name-field+ driver.common/index-unique-field+ (assoc driver.common/index-columns-field :directions true)]}+ :gin {:lifecycle :standalone+ :display-name (deferred-tru "GIN")+ :description (deferred-tru "For values with multiple components. Best for full-text search, JSONB, and arrays—when you''re searching inside a value.")+ :fields name+cols}+ :gist {:lifecycle :standalone+ :display-name (deferred-tru "GiST")+ :description (deferred-tru "For geometric, spatial, and range data. Best for \"nearest neighbor\" and overlap queries, like geographic data (PostGIS) or range types.")+ :fields name+cols}+ :brin {:lifecycle :standalone+ :display-name (deferred-tru "BRIN")+ :description (deferred-tru "Tiny and low-overhead. Best for large tables where values correlate with physical row order, like timestamps in an append-only log.")+ :fields name+cols}}))++(defn- pg-index-column-sql+ "Quote one indexed column; append its `ASC`/`DESC` direction only for btree, the one method where ordering matters."+ [driver btree? {col-name :name :keys [direction]}]+ (cond-> (sql.u/quote-name driver :field col-name)+ (and btree? direction) (str " " (u/upper-case-en (name direction)))))++(defmethod driver/compile-create-index :postgres+ [driver schema table {index-name :name, :keys [kind columns unique if-not-exists]}]+ (let [btree? (= kind :btree)+ target (apply sql.u/quote-name driver :table (if (not-empty schema) [schema table] [table]))+ cols (str/join ", " (map #(pg-index-column-sql driver btree? %) columns))]+ ;; btree is the default access method, so we omit `USING btree` and emit `USING <method>` only for the others.+ ;; UNIQUE is btree-only.+ [[(format "CREATE %sINDEX %s%s ON %s %s(%s)"+ (if (and btree? unique) "UNIQUE " "")+ (if if-not-exists "IF NOT EXISTS " "")+ (sql.u/quote-name driver :field index-name)+ target+ (if btree? "" (format "USING %s " (name kind)))+ cols)]]))++(defmethod driver/refresh-table-stats! :postgres+ [driver database schema table _transform-type]+ (let [qtable (apply sql.u/quote-name driver :table (if (not-empty schema) [schema table] [table]))]+ (driver/execute-raw-queries! driver+ (driver/connection-spec driver database)+ [[(format "ANALYZE %s" qtable)]])))++(defn- index-array->vec+ [^Array a]+ (when a (vec (.getArray a))))++(defn- pg-index-row->index+ [{:keys [index_name access_method is_unique is_primary is_valid+ key_columns include_columns partial_predicate definition]}]+ {:name index_name+ ;; On Postgres the access method is the kind: a btree index is kind :btree.+ :kind (keyword access_method)+ :access-method access_method+ :is-unique is_unique+ :is-primary is_primary+ :is-valid is_valid+ :key-columns (index-array->vec key_columns)+ :include-columns (index-array->vec include_columns)+ :partial-predicate partial_predicate+ :definition definition})++;; `indkey` is a 0-based `int2vector`; `indnkeyatts` (PG 11+) splits the key columns from the trailing INCLUDE+;; columns. A blank schema falls back to the connection's `current_schema()`. The arrays are read into Clojure vectors+;; via `:row-fn` while the result set is still open, so we never touch a `PgArray` after the connection closes.+(defmethod driver/fetch-table-indexes :postgres+ [_driver database schema table]+ (jdbc/query+ (sql-jdbc.conn/db->pooled-connection-spec database)+ ["SELECT i.relname AS index_name,+ am.amname AS access_method,+ ix.indisunique AS is_unique,+ ix.indisprimary AS is_primary,+ ix.indisvalid AS is_valid,+ pg_get_expr(ix.indpred, ix.indrelid) AS partial_predicate,+ pg_get_indexdef(ix.indexrelid) AS definition,+ ARRAY(SELECT COALESCE(a.attname, pg_get_indexdef(ix.indexrelid, k.ord::int, true))+ FROM unnest(ix.indkey[0:ix.indnkeyatts - 1]) WITH ORDINALITY AS k(attnum, ord)+ LEFT JOIN pg_attribute a ON a.attrelid = ix.indrelid AND a.attnum = k.attnum+ ORDER BY k.ord) AS key_columns,+ ARRAY(SELECT a.attname+ FROM unnest(ix.indkey[ix.indnkeyatts : ix.indnatts - 1]) WITH ORDINALITY AS k(attnum, ord)+ LEFT JOIN pg_attribute a ON a.attrelid = ix.indrelid AND a.attnum = k.attnum+ ORDER BY k.ord) AS include_columns+ FROM pg_index ix+ JOIN pg_class c ON c.oid = ix.indrelid+ JOIN pg_class i ON i.oid = ix.indexrelid+ JOIN pg_namespace n ON n.oid = c.relnamespace+ JOIN pg_am am ON am.oid = i.relam+ WHERE n.nspname = COALESCE(?, current_schema()) AND c.relname = ?+ ORDER BY i.relname"+ (not-empty schema) table]+ {:row-fn pg-index-row->index}))+(defmethod driver/extra-info :postgres[_driver]{:providers [{:name "Aiven" :pattern "\\.aivencloud\\.com$"}diff --git a/src/metabase/driver/sql_jdbc.clj b/src/metabase/driver/sql_jdbc.cljindex 368a8d0bad0..5a0ae9500c9 100644--- a/src/metabase/driver/sql_jdbc.clj+++ b/src/metabase/driver/sql_jdbc.clj@@ -1,6 +1,6 @@(ns metabase.driver.sql-jdbc"Shared code for drivers for SQL databases using their respective JDBC drivers under the hood."- (:refer-clojure :exclude [mapv])+ (:refer-clojure :exclude [mapv select-keys])(:require[clojure.core.memoize :as memoize][clojure.java.jdbc :as jdbc]@@ -24,7 +24,7 @@[metabase.util.honey-sql-2 :as h2x][metabase.util.i18n :refer [tru]][metabase.util.malli :as mu]- [metabase.util.performance :refer [mapv]]+ [metabase.util.performance :refer [mapv select-keys]][next.jdbc])(:import(java.sql Connection SQLException SQLTimeoutException)))@@ -177,18 +177,24 @@:hierarchy #'driver/hierarchy)(defmethod create-index-sql :default- [driver schema table-name index-name column-names & _]- (with-quoting driver- (let [index-spec (into [(keyword (if schema (str (name schema) "." (name table-name)) table-name))]- (map keyword)- column-names)]- (first (sql/format {:create-index [(keyword index-name) index-spec]}- :quoted true- :dialect (sql.qp/quote-style driver))))))+ [driver schema table-name index-name column-names & {:keys [unique if-not-exists]}]+ (let [index-spec (into [(keyword (if schema (str (name schema) "." (name table-name)) table-name))]+ (map keyword)+ column-names)+ index-ref (cond-> (if unique+ [:unique (keyword index-name)]+ [(keyword index-name)])+ if-not-exists (conj :if-not-exists))]+ (first (sql.qp/format-honeysql driver {:create-index [index-ref index-spec]}))))++(defmethod driver/compile-create-index :sql-jdbc+ [driver schema table {index-name :name, :keys [columns] :as structured}]+ [[(create-index-sql driver schema table index-name (map :name columns)+ (select-keys structured [:kind :unique :if-not-exists]))]])(defmethod driver/create-index! :sql-jdbc- [driver database-id schema table-name index-name column-names & _]- (let [sql (create-index-sql driver schema table-name index-name column-names)]+ [driver database-id schema table-name index-name column-names & {:as opts}]+ (let [sql (create-index-sql driver schema table-name index-name column-names opts)](jdbc/with-db-transaction [conn (sql-jdbc.conn/db->pooled-connection-spec database-id)](jdbc/execute! conn sql))nil))@@ -201,11 +207,9 @@(defmethod drop-index-sql :default[driver schema _table-name index-name]- (first (sql/format {:drop-index [(keyword (if schema- (str (name schema) "." (name index-name))- (name index-name)))]}- :quoted true- :dialect (sql.qp/quote-style driver))))+ (first (sql.qp/format-honeysql driver {:drop-index [(keyword (if schema+ (str (name schema) "." (name index-name))+ (name index-name)))]})))(defmethod driver/drop-index! :sql-jdbc[driver database-id schema table-name index-name & _]diff --git a/src/metabase/indexes/models/table_index.clj b/src/metabase/indexes/models/table_index.cljnew file mode 100644index 00000000000..e22ac13544a--- /dev/null+++ b/src/metabase/indexes/models/table_index.clj@@ -0,0 +1,165 @@+(ns metabase.indexes.models.table-index+ "The `metabase_table_indexes` model: index/clustering hints for a table.++ Every row binds to a transform (`:transform_id`) whose target it indexes, carries a structured index definition+ (see [[metabase.indexes.schema]]), and tracks a lifecycle `:status` (defaulting to `:create-pending`). The target table is+ read off the transform's `:target_table_id`, not mirrored here. The table is named generically so it can hold+ indexes for non-transform tables later too.++ `:structured` and `:status` are validated at the transform layer (on read and write), so every writer is covered."+ (:require+ [metabase.indexes.schema :as schema]+ [metabase.models.interface :as mi]+ [metabase.models.serialization :as serdes]+ [metabase.util.malli :as mu]+ [methodical.core :as methodical]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++(methodical/defmethod t2/table-name :model/TableIndex [_model] :metabase_table_indexes)++(doto :model/TableIndex+ (derive :metabase/model)+ (derive :hook/timestamped?))++(def ^:private transform-structured+ "JSON in/out for `:structured`, re-keywordizing enum-valued fields (the `fixes`) and validating against the schema+ on both read and write."+ (mi/transform-validator-with-fixes+ {:in mi/json-in, :out mi/json-out-with-keywordization}+ #(mu/validate-throw ::schema/index-structured %)+ schema/keywordize-structured))++(t2/deftransforms :model/TableIndex+ {:structured transform-structured+ :status (mi/transform-validator mi/transform-keyword (partial mi/assert-enum schema/statuses))})++(def pending-statuses+ "Statuses that require a full incremental rebuild before an index request's physical state can be trusted."+ #{:create-pending :update-pending :delete-pending :running})++(def ^:private runnable-statuses+ #{:create-pending :update-pending :running :failed})++(def ^:private defaults+ {:status :create-pending})++(defn- pending-status-for-changes+ [changes]+ (cond+ (contains? changes :structured) :update-pending+ (contains? pending-statuses (:status changes)) (:status changes)))++(t2/define-before-insert :model/TableIndex+ [req]+ (merge defaults req))++(t2/define-before-update :model/TableIndex+ [idx]+ (let [changes (t2/changes idx)+ status (pending-status-for-changes changes)]+ (cond-> idx+ status (assoc :status status+ :error_message nil))))++(defn applicable?+ "True when an index request should be applied to a transform's target table."+ [idx]+ (not= :delete-pending (:status idx)))++(defn select-for-transform+ "All index request rows for `transform-id`, ordered for the index manager list."+ [transform-id]+ (t2/select :model/TableIndex+ :transform_id transform-id+ {:order-by [[:id :asc]]}))++(defn select-applicable-for-transform+ "Rows whose structured definitions should be applied to `transform-id`'s target table."+ [transform-id]+ (t2/select :model/TableIndex+ :transform_id transform-id+ :status [:not= :delete-pending]+ {:order-by [[:index_name :asc]]}))++(defn select-for-verification+ "Rows the current execution can update while verifying indexes.++ `index-request-ids` is the applicable request id set hydrated at execution start. Only rows still `:running` are+ settled; if a request is edited mid-run, its pending status is left for the next rebuild. Delete-pending rows are+ also included so a successful full rebuild can remove rows for physical indexes that disappeared."+ [transform-id index-request-ids]+ (concat+ (when (seq index-request-ids)+ (t2/select :model/TableIndex+ :transform_id transform-id+ :id [:in index-request-ids]+ :status :running+ {:order-by [[:id :asc]]}))+ (t2/select :model/TableIndex+ :transform_id transform-id+ :status :delete-pending+ {:order-by [[:id :asc]]})))++(defn select-applicable-by-id+ "Fetch a single applicable index request by id."+ [id]+ (t2/select-one :model/TableIndex :id id :status [:not= :delete-pending]))++(defn pending-changes-for-transform?+ "True when `transform-id` has index changes that require a full rebuild to apply."+ [transform-id]+ (boolean+ (when transform-id+ (t2/exists? :model/TableIndex :transform_id transform-id :status [:in pending-statuses]))))++(defn mark-runnable-indexes-running!+ "Mark hydrated index requests that this run will apply as running.++ Returns the ids so callers can fail rows that verification cannot move to `:succeeded` or `:failed`."+ [index-request-ids]+ (let [ids (set index-request-ids)]+ (when (seq ids)+ (t2/update! :model/TableIndex+ {:id [:in ids] :status [:in runnable-statuses]}+ {:status :running}))+ ids))++(defn mark-unverified-running-indexes-failed!+ "Mark rows from [[mark-runnable-indexes-running!]] that are still running as failed."+ [ids message]+ (when (seq ids)+ (t2/update! :model/TableIndex+ {:id [:in ids] :status :running}+ {:status :failed+ :error_message message+ :last_executed_at :%now})))++(defn mark-for-revalidation!+ "Flip `transform-id`'s applicable index requests to `:update-pending` and clear stale errors, so the next run+ re-applies them against the current schema. Skips `:delete-pending` rows so a pending deletion isn't revived."+ [transform-id]+ (when transform-id+ (when-let [ids (seq (map :id (select-applicable-for-transform transform-id)))]+ (t2/update! :model/TableIndex+ {:id [:in ids]}+ {:status :update-pending, :error_message nil}))))++(defn exists-for-transform?+ "True when `transform-id` already has a request for `index-name`."+ [transform-id index-name]+ (t2/exists? :model/TableIndex+ :transform_id transform-id+ :index_name index-name))++;; Inlined into the owning transform's serialization (see the Transform make-spec's `:indexes`). Only the index+;; definition travels; lifecycle is local, so an imported index starts fresh as `:create-pending`. `:structured` holds+;; physical column names (no portable refs), so it copies verbatim. `:created_by` is skipped: a nested child's own+;; FKs aren't declared in the transform's `dependencies`, so the user may not resolve on import.+(defmethod serdes/make-spec "TableIndex"+ [_model-name _opts]+ {:copy [:index_name :structured]+ :skip [:status :error_message :last_executed_at :created_by]+ :transform {:transform_id (serdes/parent-ref)+ :created_at (serdes/date)}})diff --git a/src/metabase/indexes/reconcile.clj b/src/metabase/indexes/reconcile.cljnew file mode 100644index 00000000000..0606582265b--- /dev/null+++ b/src/metabase/indexes/reconcile.clj@@ -0,0 +1,151 @@+(ns metabase.indexes.reconcile+ "Reconcile Metabase-managed index requests (TableIndex rows) with the indexes physically present in the warehouse.+ Shared by the read API and the transform-run status verification: we apply an index request, then match it against+ `driver/fetch-table-indexes` to confirm it landed."+ (:require+ [metabase.driver :as driver]+ [metabase.util :as u]+ [metabase.util.log :as log]+ [metabase.util.malli :as mu]+ [metabase.util.malli.registry :as mr]))++(set! *warn-on-reflection* true)++(def ^:private unnamed-inline-kinds+ "Index kinds with no physical name (warehouse `:name` is nil); matched by kind + key columns instead."+ #{:sortkey :order-by :distkey :clustering})++(mr/def ::match-key+ "Join key for reconciling a managed request with a warehouse index. `:kind` selects how it's matched: `:named` keys+ by `:name`; an unnamed-inline `:sortkey`/`:order-by` by `:kind` + `:key-columns`; `:distkey` also by `:style`, so the+ column-less `:even` and `:all` stay distinct."+ [:map+ [:kind :keyword]+ [:name {:optional true} [:maybe :string]]+ [:style {:optional true} [:maybe :string]]+ [:key-columns {:optional true} [:sequential [:maybe :string]]]])++(mu/defn match-key :- ::match-key+ "The [[::match-key]] for a warehouse index map (see the schema for how each kind is keyed)."+ [{:keys [kind key-columns] am :access-method nm :name} :- [:map+ [:kind :keyword]+ [:key-columns [:sequential [:maybe :string]]]+ [:access-method {:optional true} [:maybe :string]]+ [:name {:optional true} [:maybe :string]]]]+ (cond+ (= kind :distkey) {:kind :distkey :style am :key-columns key-columns}+ (contains? unnamed-inline-kinds kind) {:kind kind :key-columns key-columns}+ :else {:kind :named :name nm}))++(mu/defn index-name :- :string+ "Physical index name for a structured def: a named kind's `:name`, else its `:kind` as a string (one inline key per+ transform)."+ [structured :- [:map+ [:name {:optional true} [:maybe :string]]+ [:kind [:or :keyword :string]]]]+ (or (:name structured) (name (:kind structured))))++(mu/defn managed-match-key :- ::match-key+ "The [[match-key]] for an index request, from its stored structured definition and index name."+ [{:keys [index_name structured]} :- [:map+ [:index_name [:maybe :string]]+ [:structured :map]]]+ (let [{:keys [kind style columns]} structured+ ;; only a :key distkey has a meaningful column; :all/:even ignore any stray column the form sent+ key-columns (if (and (= kind :distkey) (not= style :key)) [] (mapv :name columns))]+ (match-key {:kind kind+ :name index_name+ :access-method (some-> style name)+ :key-columns key-columns})))++(defn warehouse-key-set+ "Set of [[match-key]]s for the warehouse indexes, to test managed requests against with [[present-in-warehouse?]]."+ [warehouse-maps]+ (into #{} (map match-key) warehouse-maps))++(defn present-in-warehouse?+ "Whether managed request `row`'s index is one of `present-keys` (a [[warehouse-key-set]])."+ [present-keys row]+ (contains? present-keys (managed-match-key row)))++(defn classify-index-outcomes+ "Group managed request `rows` by the lifecycle status a completed full run implies, given `present-keys`+ (a [[warehouse-key-set]] of what physically landed). An applicable request is `:succeeded` when its index is+ present, else `:failed`; a `:delete-pending` request is kept (`:delete-pending`) while its index is still present,+ and dropped (`:delete-row`) once it's gone."+ [rows present-keys]+ (group-by (fn [row]+ (let [applicable? (not= :delete-pending (:status row))+ present? (present-in-warehouse? present-keys row)]+ (cond+ (and applicable? present?) :succeeded+ applicable? :failed+ present? :delete-pending+ :else :delete-row)))+ rows))++(defn- observed-fields+ "The observation fields of a warehouse `::table-index` map, snake-cased for the API."+ [wh]+ {:name (:name wh)+ :kind (:kind wh)+ :key_columns (vec (:key-columns wh))+ :include_columns (vec (:include-columns wh))+ :is_unique (boolean (:is-unique wh))+ :is_primary (boolean (:is-primary wh))+ :is_valid (boolean (:is-valid wh))+ :partial_predicate (:partial-predicate wh)+ :access_method (:access-method wh)})++(defn- declared-fields+ "A request not (yet) in the warehouse, projected from its declared `:structured` into the observation fields."+ [{:keys [structured]}]+ {:name (:name structured)+ :kind (:kind structured)+ :key_columns (mapv :name (:columns structured))+ :include_columns (vec (:include structured))+ :is_unique (boolean (:unique structured))+ :is_primary false+ :is_valid false+ :partial_predicate nil+ :access_method nil})++(defn- request-fields+ "The managed `row` carried under `:request` on an observed index -- the full request resource."+ [row]+ {:request (select-keys row [:id :transform_id :index_name :status :structured :error_message+ :created_by :created_at :updated_at :last_executed_at])})++(mu/defn merge-indexes :- [:sequential :map]+ "Reality-first merged index list: every warehouse index, flagged `:metabase_managed` with its `:request` when a+ TableIndex `row` matches ([[match-key]]), plus any request not yet present, projected from its `:structured`."+ [rows :- [:sequential :map]+ warehouse-maps :- [:sequential :map]]+ (let [by-key (u/index-by managed-match-key rows)+ present-keys (warehouse-key-set warehouse-maps)+ present (for [wh warehouse-maps+ :let [row (get by-key (match-key wh))]]+ (merge (observed-fields wh)+ {:metabase_managed (some? row)+ :present_in_warehouse true}+ (when row (request-fields row))))+ absent (for [row rows+ :when (not (present-in-warehouse? present-keys row))]+ (merge (declared-fields row)+ {:metabase_managed true+ :present_in_warehouse false}+ (request-fields row)))]+ (into (vec present) absent)))++(mu/defn fetch-warehouse-indexes :- [:maybe [:sequential :map]]+ "Physical indexes on `table-name` (`schema`) in `database` via `driver/fetch-table-indexes`.+ Returns `nil` if the driver can't introspect indexes or the warehouse is unreachable, so callers can distinguish+ fetch failure from a successful empty index list."+ [database :- :map+ schema :- [:maybe :string]+ table-name :- :string]+ (try+ (vec (driver/fetch-table-indexes (:engine database) database schema table-name))+ (catch Throwable t+ (log/warnf t "fetch-table-indexes failed for %s.%s" schema table-name)+ nil)))diff --git a/src/metabase/indexes/schema.clj b/src/metabase/indexes/schema.cljnew file mode 100644index 00000000000..8de969782c3--- /dev/null+++ b/src/metabase/indexes/schema.clj@@ -0,0 +1,101 @@+(ns metabase.indexes.schema+ "Malli schemas and normalization for managed table indexes: the structured index definitions handed to the driver+ index multimethods, and the request lifecycle statuses.++ JSON storage flattens the structured map's keyword-valued fields (`:kind`, `:style`, `:type`, and each column's+ `:direction`) to strings; [[keywordize-structured]] turns them back into keywords so a driver can dispatch on+ `:kind`."+ (:require+ [metabase.util.malli.registry :as mr]))++(set! *warn-on-reflection* true)++(mr/def ::index-name+ "Free-form user input, inlined (quoted and escaped) into DDL. 63 is the Postgres identifier limit, the tightest+ engine we support."+ [:string {:min 1 :max 63}])++(mr/def ::column-name+ ;; looser than ::index-name: column names must match real warehouse columns, and some engines allow up to 255+ [:string {:min 1 :max 255}])++(mr/def ::column+ [:map+ [:name ::column-name]+ [:direction {:optional true} [:enum :asc :desc]]])++(mr/def ::classical-index+ "Postgres / MySQL / SQL Server secondary index."+ [:map+ [:kind [:enum :btree :hash :gin :gist :brin :spgist :fulltext :spatial+ :clustered :nonclustered :columnstore]]+ [:name ::index-name]+ [:columns [:vector {:min 1} ::column]]+ [:include {:optional true} [:vector ::column-name]]+ [:unique {:optional true} :boolean]])++(mr/def ::sortkey+ "Redshift sort key, inline."+ [:map+ [:kind [:= :sortkey]]+ [:style [:enum :compound :interleaved]]+ [:columns [:vector {:min 1} ::column]]])++(mr/def ::distkey+ "Redshift distribution, inline. Only `:key` uses a column (the one DISTKEY column); `:all`/`:even` take none."+ [:and+ [:map+ [:kind [:= :distkey]]+ [:style [:enum :key :all :even]]+ [:columns {:optional true} [:vector {:min 1 :max 1} ::column]]]+ [:fn {:error/message "a :key distkey requires its one column"}+ (fn [{:keys [style columns]}] (or (not= style :key) (= 1 (count columns))))]])++(mr/def ::clustering+ "Snowflake (standalone) / BigQuery (inline) clustering. `:name` is required for the standalone form."+ [:map+ [:kind [:= :clustering]]+ [:name {:optional true} ::index-name]+ [:columns [:vector {:min 1} ::column]]])++(mr/def ::order-by+ "ClickHouse ORDER BY, inline."+ [:map+ [:kind [:= :order-by]]+ [:columns [:vector {:min 1} ::column]]])++(mr/def ::skip-index+ "ClickHouse data-skipping index, standalone. Only arg-free types; the parameterized ones need type-args the form+ can't supply yet."+ [:map+ [:kind [:= :skip-index]]+ [:name ::index-name]+ [:columns [:vector {:min 1} ::column]]+ [:type [:enum :minmax :bloom_filter]]+ [:granularity {:optional true} pos-int?]])++(defn keywordize-structured+ "Re-keywordize the structured map's enum-valued fields after JSON storage flattened them to strings."+ [structured]+ (cond-> structured+ (:kind structured) (update :kind keyword)+ (:style structured) (update :style keyword)+ (:type structured) (update :type keyword)+ (:columns structured) (update :columns (fn [cols]+ (mapv #(cond-> % (:direction %) (update :direction keyword)) cols)))))++(mr/def ::index-structured+ "A single structured index definition, dispatched on `:kind`. The shape stored in+ `metabase_table_indexes.structured` and handed to the driver index multimethods."+ ;; :decode/normalize runs before the :multi dispatch, so API input with string-valued enum fields decodes cleanly.+ [:multi {:dispatch :kind, :decode/normalize keywordize-structured}+ [:btree ::classical-index] [:hash ::classical-index] [:gin ::classical-index]+ [:gist ::classical-index] [:brin ::classical-index] [:spgist ::classical-index]+ [:fulltext ::classical-index] [:spatial ::classical-index]+ [:clustered ::classical-index] [:nonclustered ::classical-index] [:columnstore ::classical-index]+ [:sortkey ::sortkey] [:distkey ::distkey] [:clustering ::clustering]+ [:order-by ::order-by] [:skip-index ::skip-index]])++(def statuses+ "Valid lifecycle states for a table index request."+ #{:create-pending :update-pending :delete-pending :running :succeeded :failed})diff --git a/src/metabase/indexes_rest/api.clj b/src/metabase/indexes_rest/api.cljnew file mode 100644index 00000000000..5e0f8a84d98--- /dev/null+++ b/src/metabase/indexes_rest/api.clj@@ -0,0 +1,139 @@+(ns metabase.indexes-rest.api+ "Table-index endpoints, mounted at `/api/index`. Two concepts: `GET /` is a transform's merged index reality+ (warehouse indexes plus managed requests); `/request/:id` is CRUD over a single index request. An index+ belongs to a transform's output, so reads require read access to that transform and mutations require write access+ -- the same permission editing the transform itself uses. Validation and the `:status` default live in the model's+ hooks."+ (:require+ [metabase.api.common :as api]+ [metabase.api.macros :as api.macros]+ [metabase.indexes.models.table-index :as table-index]+ [metabase.indexes.reconcile :as reconcile]+ [metabase.indexes.schema :as schema]+ [metabase.transforms-base.interface :as transforms-base.i]+ [metabase.util.i18n :refer [tru]]+ [metabase.util.malli.schema :as ms]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++(def ^:private RequestIndex+ "A single index request -- one `metabase_table_indexes` row, the `/request/:id` resource."+ [:map+ {:closed true}+ [:id ms/PositiveInt]+ [:transform_id ms/PositiveInt]+ [:index_name ms/NonBlankString]+ ;; The real structured schema (not a bare `:map`) so response coercion doesn't strip its keys.+ [:structured ::schema/index-structured]+ [:status [:enum :create-pending :update-pending :delete-pending :running :succeeded :failed]]+ [:error_message [:maybe :string]]+ [:created_by [:maybe ms/PositiveInt]]+ [:created_at :any]+ [:updated_at :any]+ [:last_executed_at [:maybe :any]]])++(def ^:private Index+ "An index on a transform's target: as observed in the warehouse, plus a `:request` when Metabase manages it. Built+ by [[metabase.indexes.reconcile/merge-indexes]]."+ [:map+ {:closed true}+ [:metabase_managed :boolean]+ [:present_in_warehouse :boolean]+ [:name [:maybe :string]]+ [:kind :keyword]+ [:key_columns [:sequential :string]]+ [:include_columns [:sequential [:maybe :string]]]+ [:is_unique :boolean]+ [:is_primary :boolean]+ [:is_valid :boolean]+ [:partial_predicate [:maybe :string]]+ [:access_method [:maybe :string]]+ [:request {:optional true} RequestIndex]])++(defn- read-check-owner!+ "Read-check the transform an index request belongs to -- the permission viewing that transform uses."+ [{:keys [transform_id]}]+ (api/read-check :model/Transform transform_id))++(defn- write-check-owner!+ "Write-check the transform an index request belongs to -- the permission editing that transform uses."+ [{:keys [transform_id]}]+ (api/write-check :model/Transform transform_id))++(api.macros/defendpoint :get "/" :- [:map [:data [:sequential Index]]]+ "A transform's indexes: those physically in the warehouse, merged with its managed requests. Each entry is flagged+ `:metabase_managed`; managed ones also carry `:request` (status + definition)."+ [_route-params+ {:keys [transform-id]} :- [:map [:transform-id ms/PositiveInt]]]+ (let [transform (api/read-check :model/Transform transform-id)+ database-id (transforms-base.i/target-db-id transform)+ {:keys [schema] table-name :name} (:target transform)+ managed (table-index/select-for-transform transform-id)+ warehouse (or (reconcile/fetch-warehouse-indexes (t2/select-one :model/Database database-id)+ schema table-name)+ [])]+ {:data (reconcile/merge-indexes managed warehouse)}))++(api.macros/defendpoint :get "/request/:id" :- RequestIndex+ "Fetch a single index request (e.g. to poll its status)."+ [{:keys [id]} :- [:map [:id ms/PositiveInt]]]+ (doto (api/check-404 (t2/select-one :model/TableIndex :id id))+ (read-check-owner!)))++(api.macros/defendpoint :post "/request" :- RequestIndex+ "Create an index request on a transform's target table. Requires write access to the transform. Listed via `GET /`,+ not under `/request`."+ [_route-params+ _query-params+ {:keys [transform_id structured]} :- [:map+ [:transform_id ms/PositiveInt]+ [:structured ::schema/index-structured]]]+ (api/write-check :model/Transform transform_id)+ (let [idx-name (reconcile/index-name structured)+ duplicate (tru "An index named \"{0}\" already exists for this transform." idx-name)]+ ;; (transform_id, index_name) is unique; reject a duplicate cleanly instead of hitting the constraint.+ (api/check-400 (not (table-index/exists-for-transform? transform_id idx-name)) duplicate)+ (try+ (t2/insert-returning-instance! :model/TableIndex+ {:transform_id transform_id+ :index_name idx-name+ :structured structured+ :created_by api/*current-user-id*})+ (catch Exception e+ ;; the pre-check races a concurrent create; if the row exists now, surface the same 400+ (api/check-400 (not (table-index/exists-for-transform? transform_id idx-name)) duplicate)+ (throw e)))))++(defn- assert-stable-key!+ [existing structured]+ (api/check-400 (= (reconcile/index-name (:structured existing))+ (reconcile/index-name structured))+ (tru "The index name cannot be changed. Delete and recreate the index instead."))+ (api/check-400 (= (:kind (:structured existing)) (:kind structured))+ (tru "The index type cannot be changed. Delete and recreate the index instead."))+ (api/check-400 (= (:type (:structured existing)) (:type structured))+ (tru "The index type cannot be changed. Delete and recreate the index instead.")))++(api.macros/defendpoint :put "/request/:id" :- RequestIndex+ "Replace the structured definition of an index request, marking it update-pending."+ [{:keys [id]} :- [:map [:id ms/PositiveInt]]+ _query-params+ {:keys [structured]} :- [:map [:structured ::schema/index-structured]]]+ (let [existing (api/check-404 (table-index/select-applicable-by-id id))]+ (write-check-owner! existing)+ (assert-stable-key! existing structured)+ ;; toucan2 has no instance-returning update, so re-select; in a tx so we return exactly what we wrote.+ (t2/with-transaction [_conn]+ (t2/update! :model/TableIndex id {:structured structured})+ (t2/select-one :model/TableIndex :id id))))++#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}+(api.macros/defendpoint :delete "/request/:id"+ "Mark an index request `delete-pending`. The physical index is only dropped when the target table is next rebuilt+ (pending changes force a full run), so the row stays visible in this state until that rebuild removes it."+ [{:keys [id]} :- [:map [:id ms/PositiveInt]]]+ (let [existing (api/check-404 (table-index/select-applicable-by-id id))]+ (write-check-owner! existing)+ (t2/update! :model/TableIndex id {:status :delete-pending}))+ api/generic-204-no-content)diff --git a/src/metabase/models/resolution.clj b/src/metabase/models/resolution.cljindex 1e20bc67f8c..983756040c3 100644--- a/src/metabase/models/resolution.clj+++ b/src/metabase/models/resolution.clj@@ -60,6 +60,7 @@:model/McpSessionLog metabase.mcp.models.mcp-session-log:model/McpToolCallLog metabase.mcp.models.mcp-tool-call-log:model/Measure metabase.measures.models.measure+ :model/TableIndex metabase.indexes.models.table-index:model/Metabot metabase.metabot.models.metabot:model/MetabotConversation metabase.metabot.models.metabot-conversation:model/MetabotFeedback metabase.metabot.models.metabot-feedbackdiff --git a/src/metabase/transforms/crud.clj b/src/metabase/transforms/crud.cljindex 1496843e6c9..f6db0aedcb9 100644--- a/src/metabase/transforms/crud.clj+++ b/src/metabase/transforms/crud.clj@@ -6,6 +6,7 @@[clojure.string :as str][metabase.api.common :as api][metabase.database-routing.core :as database-routing]+ [metabase.driver :as driver][metabase.driver.util :as driver.u][metabase.events.core :as events][metabase.models.interface :as mi]@@ -16,6 +17,7 @@[metabase.transforms.util :as transforms.u][metabase.util :as u][metabase.util.i18n :refer [deferred-tru]]+ [metabase.util.log :as log][toucan2.core :as t2]))(set! *warn-on-reflection* true)@@ -106,6 +108,18 @@(map #(update % :last_run transforms-base.u/present-run))(map transforms.u/add-source-readable)))))))+(defn- requestable-indexes+ "The index methods the target db's driver can create on `transform`'s target table, or nil when none are available."+ [transform]+ (when-let [db-id (transforms-base.i/target-db-id transform)]+ (when-let [database (t2/select-one :model/Database db-id)]+ (let [methods (try+ (driver/supported-index-methods (:engine database) database)+ (catch Throwable e+ (log/warn e "Failed to fetch supported index methods for transform" (:id transform))+ nil))]+ (not-empty methods)))))+(defn get-transform"Get a specific transform."[id]@@ -115,6 +129,7 @@(t2/hydrate :last_run :transform_tag_ids :creator :owner :can_read :can_write :can_execute)(u/update-some :last_run transforms-base.u/present-run)(assoc :table target-table)+ (assoc :requestable_indexes (requestable-indexes transform))transforms.u/add-source-readable)))(defn create-transform!diff --git a/src/metabase/transforms/execute.clj b/src/metabase/transforms/execute.cljindex fea4e5c78e4..6cb54633d6e 100644--- a/src/metabase/transforms/execute.clj+++ b/src/metabase/transforms/execute.clj@@ -1,6 +1,8 @@(ns metabase.transforms.execute(:require+ [metabase.indexes.models.table-index :as table-index][metabase.transforms-base.interface :as transforms-base.i]+ [metabase.transforms-base.util :as transforms-base.u][metabase.transforms.interface :as transforms.i][metabase.transforms.query-impl :as transforms.query-impl]))@@ -19,12 +21,20 @@When `target-db-id` returns nil (no per-type impl, or transform shape doesn'tidentify a target DB), the hook is skipped — workspace rewriting requires a- known DB id to look up `db-workspace-namespace`."+ known DB id to look up `db-workspace-namespace`.++ Also hydrates the declared indexes and their request ids onto the target so the base reads them off+ `(:indexes target)` and `(:index-request-ids target)` at every table-creation seam, and stashes+ `:full-incremental-run?` so that (DB-backed) decision is made once and stays stable for the whole run."[transform]- (if-let [db-id (transforms-base.i/target-db-id transform)]- (assoc transform :target- (transforms.query-impl/resolve-transform-target db-id (:target transform)))- transform))+ (let [requests (table-index/select-applicable-for-transform (:id transform))]+ (-> (if-let [db-id (transforms-base.i/target-db-id transform)]+ (assoc transform :target+ (transforms.query-impl/resolve-transform-target db-id (:target transform)))+ transform)+ (assoc-in [:target :indexes] (mapv :structured requests))+ (assoc-in [:target :index-request-ids] (into [] (keep :id) requests))+ (assoc :full-incremental-run? (transforms-base.u/full-incremental-run? transform)))))(defn execute!"Run `transform` and sync its target table.diff --git a/src/metabase/transforms/models/transform.clj b/src/metabase/transforms/models/transform.cljindex 5ad30e73ea8..a370d16d106 100644--- a/src/metabase/transforms/models/transform.clj+++ b/src/metabase/transforms/models/transform.clj@@ -5,6 +5,7 @@[metabase.api.common :as api][metabase.collections.models.collection :as collection][metabase.events.core :as events]+ [metabase.indexes.models.table-index :as table-index][metabase.lib-be.core :as lib-be][metabase.lib.core :as lib][metabase.models.interface :as mi]@@ -175,6 +176,10 @@;; No database existence check added here, unlike for insert.;; Just allow updates for an invalid target to fail.(transforms-base.i/target-db-id transform))]+ ;; A source or target edit may change the output columns, and we can't cheaply tell, so invalidate conservatively:+ ;; the next run re-applies the managed indexes against the new schema and fails if a column is gone.+ (when (and target-changed? (not mi/*deserializing?*))+ (table-index/mark-for-revalidation! (:id transform)))(cond-> transformsource(assoc :source_type (transforms-base.u/transform-source-type source)@@ -394,6 +399,20 @@(for [transform transforms](assoc transform :tags (get tag-mappings (u/the-id transform) []))))))+(mi/define-batched-hydration-method indexes+ :indexes+ "Fetch the table indexes that belong to each transform"+ [transforms]+ (when (seq transforms)+ (let [transform-ids (into #{} (map u/the-id) transforms)+ idx-mappings (group-by :transform_id+ (filter table-index/applicable?+ (t2/select :model/TableIndex+ :transform_id [:in transform-ids]+ {:order-by [[:index_name :asc]]})))]+ (for [transform transforms]+ (assoc transform :indexes (get idx-mappings (u/the-id transform) []))))))+(mi/define-batched-hydration-method table-with-db-and-fields:table-with-db-and-fields"Fetch tables with their fields. The tables show up under the `:table` property."@@ -468,7 +487,8 @@(m/update-existing :database_id import-maybe-int-database-fk))))))))))}:target {:export #(serdes/export-mbql (dissoc % :table_id)):import serdes/import-mbql}- :tags (serdes/nested :model/TransformTransformTag :transform_id (merge {:sort-by (juxt :position :created_at)} opts))}})+ :tags (serdes/nested :model/TransformTransformTag :transform_id (merge {:sort-by (juxt :position :created_at)} opts))+ :indexes (serdes/nested :model/TableIndex :transform_id (merge {:sort-by :index_name} opts))}})(defmethod serdes/deserialization-dependencies "Transform"[{:keys [collection_id source tags source_database_id]}]diff --git a/src/metabase/transforms/util.clj b/src/metabase/transforms/util.cljindex 58a1dc015db..08962eb05ba 100644--- a/src/metabase/transforms/util.clj+++ b/src/metabase/transforms/util.clj@@ -13,6 +13,7 @@[metabase.driver.settings :as driver.settings][metabase.driver.sql-jdbc :as sql-jdbc][metabase.driver.util :as driver.u]+ [metabase.indexes.models.table-index :as table-index][metabase.models.interface :as mi][metabase.premium-features.core :as premium-features][metabase.query-processor.pipeline :as qp.pipeline]@@ -147,6 +148,7 @@(try(let [source-range-params (transforms-base.u/get-source-range-params transform)full-incremental? (transforms-base.u/full-incremental-run? transform)+ full-create? (transforms-base.u/full-create-run? transform);; Efficiency metrics (rows-available / rows-processed) are only meaningful when this run's;; rows-affected count can be trusted. On drivers that declare;; `:transforms/accurate-rows-affected` false, a full-rebuild (CTAS) run reports a bogus@@ -172,8 +174,23 @@driver.settings/*query-timeout-ms* transform-timeout-ms;; Match the query timeout so a single slow socket read (or a driver that waits for;; the full server-side query) does not get killed before the transform's own deadline.- driver.settings/*network-timeout-ms* (max driver.settings/*network-timeout-ms* transform-timeout-ms)]+ driver.settings/*network-timeout-ms* (max driver.settings/*network-timeout-ms*+ transform-timeout-ms)](run-transform! cancel-chan source-range-params)))]+ (when full-create?+ ;; Before the watermark/succeed mark, so a failure hits the catch below and fails the run (and a retry+ ;; stays a full rebuild that re-attempts the index).+ (let [running-indexes (table-index/mark-runnable-indexes-running!+ (:index-request-ids (:target transform)))]+ (try+ (transforms-base.u/apply-target-indexes! transform)+ (transforms-base.u/verify-managed-indexes! transform)+ (finally+ ;; Fail any request verification couldn't settle -- whether apply/verify threw or just left it+ ;; running. On a throw the exception still propagates to the run-level catch.+ (table-index/mark-unverified-running-indexes-failed!+ running-indexes+ "Index status could not be verified after the transform completed.")))))(transforms-base.u/save-watermark! (:id transform) source-range-params)(transform-run/succeed-started-run! run-id);; Narrow try/catch so an emission throw doesn't trigger the outer catch'sdiff --git a/src/metabase/transforms_base/query.clj b/src/metabase/transforms_base/query.cljindex 23abb773d37..69290cc4b01 100644--- a/src/metabase/transforms_base/query.clj+++ b/src/metabase/transforms_base/query.clj@@ -41,7 +41,10 @@[:transform-type [:enum {:decode/normalize schema.common/normalize-keyword} :table :table-incremental]][:conn-spec :any][:query ::qp.compile/compiled]- [:output-table [:keyword {:decode/normalize schema.common/normalize-keyword}]]])+ [:output-table [:keyword {:decode/normalize schema.common/normalize-keyword}]]+ ;; Declared target indexes. `compile-transform` inlines the ones it can into the CTAS (e.g. Redshift SORTKEY,+ ;; ClickHouse ORDER BY); the rest are created standalone.+ [:indexes {:optional true} [:sequential :map]]])(mr/def ::transform-opts[:map@@ -128,7 +131,8 @@;; the CTAS table name. See;; `metabase.driver.sql.query-processor/compile-transform :sql`.:output-db (:db target)- :output-table (transforms-base.u/qualified-table-name driver target)}+ :output-table (transforms-base.u/qualified-table-name driver target)+ :indexes (:indexes target)}opts (transform-opts effective-transform-type transform)features (transforms-base.u/required-database-features transform)](when-not (every? (fn [feature] (driver.u/supports? (:engine database) feature database)) features)diff --git a/src/metabase/transforms_base/schema.clj b/src/metabase/transforms_base/schema.cljindex 71c598c7c21..2640d909971 100644--- a/src/metabase/transforms_base/schema.clj+++ b/src/metabase/transforms_base/schema.clj@@ -29,7 +29,8 @@[:type :string][:database {:optional true} :int][:schema {:optional true} [:maybe :string]]- [:name :string]])+ [:name :string]+ [:indexes {:optional true} [:sequential :map]]])(mr/def ::transform"A transform map as expected by execute-base! implementations."diff --git a/src/metabase/transforms_base/util.clj b/src/metabase/transforms_base/util.cljindex a68091a0f28..11aa87ea29f 100644--- a/src/metabase/transforms_base/util.clj+++ b/src/metabase/transforms_base/util.clj@@ -10,6 +10,8 @@[metabase.driver :as driver][metabase.driver.sql.normalize :as sql.normalize][metabase.events.core :as events]+ [metabase.indexes.models.table-index :as table-index]+ [metabase.indexes.reconcile :as reconcile][metabase.lib-be.core :as lib-be][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata]@@ -69,6 +71,11 @@[transform](type-is? (:source transform) :python))+(defn table-target?+ "True if `transform` writes to a plain table, recreated on every run."+ [transform]+ (type-is? (:target transform) :table))+(defn incremental-target?"True if `transform` writes to an incremental table."[transform]@@ -93,13 +100,26 @@(defn full-incremental-run?"True when an incremental transform should drop-and-recreate the target rather than append.- Fires whenever `last_checkpoint_value` is nil — covers the literal first run, and any run after the- `:model/Transform` before-update hook clears the watermark on a `checkpoint-filter-field-id`- change. Stays true across failed attempts since the predicate only inspects- `:last_checkpoint_value`."+ Fires when `last_checkpoint_value` is nil (first run, or after the before-update hook clears the watermark on+ a `checkpoint-filter-field-id` change), or when pending index changes require rebuilding the table to apply+ physical index state.++ The pending-changes check reads the app DB, so execution computes this once+ (see [[metabase.transforms.execute]]) and stashes it as `:full-incremental-run?` on the transform; when that+ key is present it is returned as-is, keeping the answer stable for the whole run."+ [{:keys [id] :as transform}]+ (if (contains? transform :full-incremental-run?)+ (:full-incremental-run? transform)+ (and (incremental-target? transform)+ (or (nil? (:last_checkpoint_value transform))+ (table-index/pending-changes-for-transform? id)))))++(defn full-create-run?+ "True when this run (re)creates the target table -- a plain `:table` run or a full-reset incremental run -- so+ index requests are applied and verified."[transform]- (and (incremental-target? transform)- (nil? (:last_checkpoint_value transform))))+ (or (table-target? transform)+ (full-incremental-run? transform)));;; ------------------------------------------------- Table Template Tags -------------------------------------------------@@ -343,7 +363,9 @@"Please select a checkpoint field in the transform settings."))](throw (ex-info msg {:transform-message msg}))))(when checkpoint-filter-field-id- (let [{:keys [last_checkpoint_value]} transform+ (let [{:keys [last_checkpoint_value]} (cond-> transform+ (full-incremental-run? transform)+ (assoc :last_checkpoint_value nil))db-id (transforms-base.i/target-db-id transform)metadata-provider (lib-be/application-database-metadata-provider db-id)column (lib.metadata/field metadata-provider checkpoint-filter-field-id)@@ -558,7 +580,10 @@[:map[:name :keyword][:columns [:sequential ::column-definition]]- [:primary-key {:optional true} [:sequential :string]]])+ [:primary-key {:optional true} [:sequential :string]]+ ;; Inline indexes to apply at table creation (e.g. a Redshift sortkey). Passed through to `create-table!`;+ ;; drivers that don't inline anything ignore it. Populated from a transform's declared indexes by the manager.+ [:indexes {:optional true} [:sequential :map]]])(mu/defn create-table-from-schema!"Create a table from a table-schema"@@ -576,9 +601,9 @@(driver/type->database-type driver :type/Text))))][name db-type]))columns)- primary-key-opts (select-keys table-schema [:primary-key])]+ opts (select-keys table-schema [:primary-key :indexes])](log/infof "Creating table %s with %d columns" table-name (count columns))- (driver/create-table! driver database-id table-name column-definitions primary-key-opts)))+ (driver/create-table! driver database-id table-name column-definitions opts)))(defn drop-table!"Drop a table in the database."@@ -595,6 +620,79 @@;;; ------------------------------------------------- Post-Execution Completion -------------------------------------------------+(defn- mark-index-failed!+ "Best-effort: flag the request for `index` (located by its canonical name) failed, with the error message."+ [transform-id index ^Throwable t]+ (when transform-id+ (t2/update! :model/TableIndex+ :transform_id transform-id :index_name (reconcile/index-name index)+ {:status :failed :error_message (ex-message t) :last_executed_at :%now})))++(defn- apply-standalone-indexes!+ "Create the target's `:standalone` indexes as separate DDL, now that the table exists. `:inline` kinds render at+ table creation, so they're filtered out here. Each create uses `:if-not-exists`, so re-applying is a no-op. On a+ per-index DDL throw, marks the request failed (when `:transform-id` is set) and re-throws."+ [database {:keys [indexes schema transform-id] table-name :name}]+ (let [driver (:engine database)+ methods (driver/supported-index-methods driver database)+ standalone (filter #(= :standalone (get-in methods [(:kind %) :lifecycle])) indexes)]+ (when (seq standalone)+ (let [conn-spec (driver/connection-spec driver database)]+ (doseq [index standalone]+ (try+ ;; Force the canonical name so the DDL matches the stored `index_name` / match key.+ (driver/execute-raw-queries! driver conn-spec+ (driver/compile-create-index driver schema table-name+ (assoc index+ :if-not-exists true+ :name (reconcile/index-name index))))+ (catch Throwable t+ (mark-index-failed! transform-id index t)+ (throw t))))))))++(defn apply-target-indexes!+ "Apply the target's standalone indexes, on full-create runs only (a `:table` run or a full-reset incremental run+ recreates the table; appends keep the live table and its indexes). Runs before the run is marked succeeded, so a+ failure fails the run record."+ [transform]+ (when (and (seq (:indexes (:target transform)))+ (full-create-run? transform))+ (let [database (t2/select-one :model/Database (transforms-base.i/target-db-id transform))]+ (apply-standalone-indexes! database (assoc (:target transform) :transform-id (:id transform))))))++(defn- apply-index-outcomes!+ "Write a [[reconcile/classify-index-outcomes]] result back: drop the removed rows, and move the rest to their new+ status (one update per outcome), keeping `error_message` in step with the transition."+ [by-outcome]+ (doseq [[status rows] by-outcome]+ (if (= :delete-row status)+ (t2/delete! :model/TableIndex :id [:in (map :id rows)])+ (t2/update! :model/TableIndex :id [:in (map :id rows)]+ (cond-> {:status status+ :last_executed_at :%now}+ (= status :succeeded)+ (assoc :error_message nil)+ (= status :failed)+ (assoc :error_message "Index was not found on the target table after the transform ran."))))))++(defn verify-managed-indexes!+ "Reconcile each index request against what's physically in the warehouse and set its `:status`.+ Only runs on full-create runs (same guard as [[apply-target-indexes!]])."+ [transform]+ (when (full-create-run? transform)+ (let [target (:target transform)+ managed (if (contains? target :index-request-ids)+ (table-index/select-for-verification (:id transform) (:index-request-ids target))+ (table-index/select-for-transform (:id transform)))]+ (when-let [managed (seq managed)]+ (let [database (t2/select-one :model/Database (transforms-base.i/target-db-id transform))+ {:keys [schema] table-name :name} (:target transform)]+ (if-some [warehouse-indexes (reconcile/fetch-warehouse-indexes database schema table-name)]+ (apply-index-outcomes!+ (reconcile/classify-index-outcomes managed (reconcile/warehouse-key-set warehouse-indexes)))+ (log/warnf "verify-managed-indexes!: could not read indexes for %s.%s; leaving %d request(s) unchanged"+ schema table-name (count managed))))))))+(defn complete-execution!"Post-processing steps after a transform has been executed successfully.@@ -602,11 +700,11 @@- Sync target table to AppDB- Set `transform_id` on the target table- Publish Metabase events (unless `:publish-events?` is false)- - Create/drop secondary indexesThis is called after the core execution completes. Callers that use`run-cancelable-transform!` should call this AFTER `succeed-started-run!`- to preserve the correct order of operations."+ to preserve the correct order of operations. (Standalone indexes are applied earlier, by+ `apply-target-indexes!`, so a failure there still fails the run.)"[transform opts](let [{:keys [target]} transform{:keys [publish-events?]@@ -617,6 +715,13 @@(when-let [table (sync-target! target database)](t2/update! :model/Transform (:id transform) {:target_table_id (:id table)})(t2/update! :model/Table (:id table) {:transform_id (:id transform)}))+ ;; ANALYZE the target before the run is observable, so dependents don't plan on stale stats.+ ;; Best-effort: a stats failure shouldn't fail an otherwise-successful run.+ (try+ (driver/refresh-table-stats! (:engine database) database (:schema target) (:name target)+ (keyword (:type target)))+ (catch Throwable t+ (log/warnf t "refresh-table-stats! failed for %s.%s" (:schema target) (:name target))));; Publish event after sync so the table exists in AppDB.(when publish-events?(events/publish-event! :event/transform-run-completediff --git a/src/metabase/transforms_rest/api/transform.clj b/src/metabase/transforms_rest/api/transform.cljindex 373b8da6ec0..6eea839638e 100644--- a/src/metabase/transforms_rest/api/transform.clj+++ b/src/metabase/transforms_rest/api/transform.clj@@ -102,7 +102,11 @@[:last_checkpoint_value {:optional true} [:maybe :string]][:can_read {:optional true} :boolean][:can_write {:optional true} :boolean]- [:can_execute {:optional true} :boolean]])+ [:can_execute {:optional true} :boolean]+ ;; Index methods requestable on the target table (driver capability); nil when unsupported. Set only by GET /:id.+ ;; Referenced by registry keyword (not a require) to avoid a transforms-rest -> driver module dependency; the schema+ ;; is registered by `metabase.driver`, which is loaded well before any response is coerced.+ [:requestable_indexes {:optional true} [:maybe :metabase.driver/supported-index-methods]]])(def ^:private TransformRunResponse[:map {:closed true}diff --git a/test/metabase/cmd/copy_test.clj b/test/metabase/cmd/copy_test.cljindex 6704cb3a74d..9fa960f0b95 100644--- a/test/metabase/cmd/copy_test.clj+++ b/test/metabase/cmd/copy_test.clj@@ -66,6 +66,7 @@:model/SourceSegmentDaily:model/SsoRelayState:model/SupportAccessGrantLog+ :model/TableIndex:model/TaskHistory:model/TaskRun;; TODO we should remove these models from here once serialization is supporteddiff --git a/test/metabase/driver/mysql_test.clj b/test/metabase/driver/mysql_test.cljindex ec8cf920827..edc4bd56949 100644--- a/test/metabase/driver/mysql_test.clj+++ b/test/metabase/driver/mysql_test.clj@@ -2,6 +2,7 @@{:clj-kondo/config '{:linters {:deprecated-var {:exclude {metabase.test.data/mbql-query {:namespaces [metabase.driver.mysql-test]}metabase.test.data/run-mbql-query {:namespaces [metabase.driver.mysql-test]}}}}}}(:require+ [buddy.core.codecs :as codecs][clojure.java.jdbc :as jdbc][clojure.set :as set][clojure.string :as str]@@ -1099,3 +1100,91 @@"query should throw rather than completing normally")(is (< elapsed 30000)(format "query should be cancelled well before SLEEP(60) completes naturally — took %.0f ms" elapsed)))))))++(deftest ^:parallel compile-create-index-test+ (testing "btree renders with backticks; UNIQUE only when asked, direction only on btree"+ (is (= [["CREATE INDEX `by_cat` ON `t` (`category`)"]]+ (driver/compile-create-index :mysql nil "t"+ {:kind :btree :name "by_cat" :columns [{:name "category"}]})))+ (is (= [["CREATE UNIQUE INDEX `by_cat` ON `s`.`t` (`category` DESC)"]]+ (driver/compile-create-index :mysql "s" "t"+ {:kind :btree :name "by_cat" :unique true+ :columns [{:name "category" :direction :desc}]}))))+ (testing "fulltext has no UNIQUE and no per-column direction"+ (is (= [["CREATE FULLTEXT INDEX `ft_cat` ON `t` (`category`)"]]+ (driver/compile-create-index :mysql nil "t"+ {:kind :fulltext :name "ft_cat" :unique true+ :columns [{:name "category" :direction :asc}]}))))+ (testing "MySQL has no CREATE INDEX IF NOT EXISTS, so :if-not-exists guards via dynamic SQL instead"+ (let [stmts (driver/compile-create-index :mysql nil "t"+ {:kind :btree :name "by_cat" :if-not-exists true+ :columns [{:name "category"}]})]+ (is (not-any? #(str/includes? (first %) "IF NOT EXISTS") stmts)+ "no literal IF NOT EXISTS clause")+ (is (str/includes? (first (last stmts)) "DEALLOCATE PREPARE")+ "ends by deallocating the prepared guard statement"))))++(deftest ^:parallel compile-create-index-hex-escaping-test+ (let [hex (fn [^String s] (codecs/bytes->hex (.getBytes s "UTF-8")))+ expr (fn [s] (format "CONVERT(UNHEX('%s') USING utf8mb4)" (hex s)))+ decode (fn [h] (String. ^bytes (codecs/hex->bytes h) "UTF-8"))+ compile (fn [schema table nm]+ (driver/compile-create-index+ :mysql schema table+ {:kind :btree :name nm :if-not-exists true :columns [{:name "category"}]}))+ joined (fn [stmts] (str/join "\n" (map first stmts)))]+ (testing ":if-not-exists true guards the create with dynamic SQL, inlining every string as hex"+ (let [stmts (compile nil "t" "by_cat")+ sql (joined stmts)+ plain-create (ffirst (driver/compile-create-index+ :mysql nil "t"+ {:kind :btree :name "by_cat" :columns [{:name "category"}]}))]+ (testing "shape: existence check, IF guard, then PREPARE/EXECUTE/DEALLOCATE"+ (is (= 5 (count stmts)))+ (is (str/includes? (ffirst stmts)+ "@mb_idx_exists := (SELECT COUNT(*) FROM information_schema.statistics"))+ (is (str/includes? (first (nth stmts 1)) "@mb_idx_sql := IF(@mb_idx_exists > 0, 'DO 0'"))+ (is (= ["PREPARE mb_idx_stmt FROM @mb_idx_sql"] (nth stmts 2)))+ (is (= ["EXECUTE mb_idx_stmt"] (nth stmts 3)))+ (is (= ["DEALLOCATE PREPARE mb_idx_stmt"] (nth stmts 4))))+ (testing "table and index name are compared as hex-encoded utf8mb4 expressions"+ (is (str/includes? sql (str "table_name = " (expr "t"))))+ (is (str/includes? sql (str "index_name = " (expr "by_cat")))))+ (testing "the embedded CREATE is exactly the plain create, hex-encoded"+ (is (str/includes? sql (expr plain-create)))+ (is (str/starts-with? (decode (hex plain-create)) "CREATE INDEX")))+ (testing "no schema compares against DATABASE(), not a hex literal"+ (is (str/includes? sql "table_schema = DATABASE()")))))+ (testing "an explicit schema is inlined as hex too"+ (is (str/includes? (joined (compile "s" "t" "by_cat"))+ (str "table_schema = " (expr "s")))))+ (testing "a backslash in the name (which defeats ansi quote-doubling) is hex-encoded, never literal"+ (let [nm "my\\index"+ sql (joined (compile nil "t" nm))]+ (is (str/includes? (hex nm) "5c")+ "sanity: the name's hex includes the backslash byte 5c")+ (is (str/includes? sql (hex nm))+ "the exact bytes (backslash included) are inlined as hex")+ (is (str/includes? sql (str "index_name = " (expr nm))))+ (is (not (str/includes? sql "\\"))+ "no raw backslash survives anywhere in the SQL, so it cannot escape a literal")+ (is (= nm (decode (hex nm)))+ "the hex round-trips back to the original name")))+ (testing "an injection-style name is hex-encoded and cannot break out of a literal"+ (let [nm "a' OR 1=1 -- "+ sql (joined (compile nil "t" nm))]+ (is (str/includes? sql (hex nm))+ "the payload is inlined as hex")+ (is (str/includes? sql (str "index_name = " (expr nm))))+ (is (not (str/includes? sql "1=1"))+ "the injection text never appears unencoded")+ (is (not (str/includes? sql "OR 1=1")))+ (is (= nm (decode (hex nm)))+ "the hex round-trips back to the original name")))+ (testing ":if-not-exists false emits the plain single-statement CREATE, no dynamic SQL"+ (let [stmts (driver/compile-create-index+ :mysql nil "t"+ {:kind :btree :name "by_cat" :if-not-exists false :columns [{:name "category"}]})]+ (is (= [["CREATE INDEX `by_cat` ON `t` (`category`)"]] stmts))+ (is (not (str/includes? (ffirst stmts) "PREPARE")))+ (is (not (str/includes? (ffirst stmts) "UNHEX")))))))diff --git a/test/metabase/driver/postgres/index_test.clj b/test/metabase/driver/postgres/index_test.cljnew file mode 100644index 00000000000..c9cca41a1ce--- /dev/null+++ b/test/metabase/driver/postgres/index_test.clj@@ -0,0 +1,193 @@+(ns ^:mb/driver-tests metabase.driver.postgres.index-test+ "Tests for the Postgres standalone index driver methods (Index Manager, milestone 0):+ `supported-index-methods`, `compile-create-index`, and `refresh-table-stats!`.++ The rendering and execution tests are driven by case tables (`render-cases` / `execute-cases`) so that+ covering a new index kind is a one-line addition rather than another copy-pasted assertion block."+ (:require+ [clojure.java.jdbc :as jdbc]+ [clojure.test :refer :all]+ [metabase.driver :as driver]+ [metabase.driver.sql-jdbc.connection :as sql-jdbc.conn]+ [metabase.driver.sql.util :as sql.u]+ [metabase.test :as mt]))++(deftest ^:parallel supports-standalone-create-test+ (testing "Postgres reports support for standalone index creation"+ (is (true? (driver/database-supports? :postgres :index/standalone-create nil)))))++(deftest ^:parallel supported-index-methods-test+ (testing "Postgres advertises btree (with unique) plus the gin/gist/brin access methods, all standalone"+ (let [methods (driver/supported-index-methods :postgres nil)]+ (is (= #{:btree :gin :gist :brin} (set (keys methods))))+ (is (= {:btree :standalone :gin :standalone :gist :standalone :brin :standalone}+ (update-vals methods :lifecycle)))+ (testing "only btree offers the unique toggle"+ (is (= ["name" "unique" "columns"] (map :name (get-in methods [:btree :fields]))))+ (is (= ["name" "columns"] (map :name (get-in methods [:gin :fields]))))))))++(deftest default-impls-test+ (testing "a driver without :index/standalone-create inherits safe defaults"+ (is (false? (driver/database-supports? :h2 :index/standalone-create nil)))+ (is (= {} (driver/supported-index-methods :h2 nil)))+ (is (nil? (driver/refresh-table-stats! :h2 nil "public" "t" :table)))))++;;; ------------------------------------------ DDL rendering ------------------------------------------++(def ^:private render-cases+ "Each case: inputs to `compile-create-index` and the single SQL string it should render. The index's `:name` is+ rendered verbatim as the physical index name. Add a row to cover a new index kind, column shape, or quoting+ wrinkle."+ [{:label "schema-qualified single-column btree"+ :schema "public" :table "events"+ :structured {:kind :btree :name "events_user_id" :columns [{:name "user_id"}] :if-not-exists true}+ :expected "CREATE INDEX IF NOT EXISTS \"events_user_id\" ON \"public\".\"events\" (\"user_id\")"}+ {:label "no schema qualifier"+ :schema nil :table "events"+ :structured {:kind :btree :name "events_user_id" :columns [{:name "user_id"}] :if-not-exists true}+ :expected "CREATE INDEX IF NOT EXISTS \"events_user_id\" ON \"events\" (\"user_id\")"}+ {:label "without :if-not-exists the create is not idempotent"+ :schema nil :table "events"+ :structured {:kind :btree :name "events_user_id" :columns [{:name "user_id"}]}+ :expected "CREATE INDEX \"events_user_id\" ON \"events\" (\"user_id\")"}+ {:label "renders all columns, not just the first"+ :schema nil :table "events"+ :structured {:kind :btree :name "multi" :columns [{:name "a"} {:name "b"}] :if-not-exists true}+ :expected "CREATE INDEX IF NOT EXISTS \"multi\" ON \"events\" (\"a\", \"b\")"}+ {:label "unique renders CREATE UNIQUE INDEX"+ :schema nil :table "events"+ :structured {:kind :btree :name "email" :columns [{:name "email"}] :unique true :if-not-exists true}+ :expected "CREATE UNIQUE INDEX IF NOT EXISTS \"email\" ON \"events\" (\"email\")"}+ {:label "identifiers that need quoting still get it"+ :schema nil :table "events"+ :structured {:kind :btree :name "weird idx" :columns [{:name "a\"b"}] :if-not-exists true}+ :expected "CREATE INDEX IF NOT EXISTS \"weird idx\" ON \"events\" (\"a\"\"b\")"}+ {:label "a SQL-injection payload in the name and column is quoted+escaped, so it can only ever be an identifier"+ :schema nil :table "events"+ :structured {:kind :btree :name "idx\"; DROP TABLE users; --" :columns [{:name "a\"; DROP TABLE x; --"}]}+ :expected "CREATE INDEX \"idx\"\"; DROP TABLE users; --\" ON \"events\" (\"a\"\"; DROP TABLE x; --\")"}+ {:label "gin renders USING gin"+ :schema "public" :table "events"+ :structured {:kind :gin :name "events_data" :columns [{:name "data"}] :if-not-exists true}+ :expected "CREATE INDEX IF NOT EXISTS \"events_data\" ON \"public\".\"events\" USING gin (\"data\")"}+ {:label "gist renders USING gist"+ :schema nil :table "shapes"+ :structured {:kind :gist :name "shapes_geom" :columns [{:name "geom"}]}+ :expected "CREATE INDEX \"shapes_geom\" ON \"shapes\" USING gist (\"geom\")"}+ {:label "brin renders USING brin"+ :schema nil :table "events"+ :structured {:kind :brin :name "events_ts" :columns [{:name "ts"}] :if-not-exists true}+ :expected "CREATE INDEX IF NOT EXISTS \"events_ts\" ON \"events\" USING brin (\"ts\")"}+ {:label "unique is btree-only; ignored for the other methods"+ :schema nil :table "events"+ :structured {:kind :gin :name "g" :columns [{:name "data"}] :unique true}+ :expected "CREATE INDEX \"g\" ON \"events\" USING gin (\"data\")"}+ {:label "btree renders per-column ASC/DESC direction"+ :schema nil :table "events"+ :structured {:kind :btree :name "by_ts" :columns [{:name "a" :direction :desc} {:name "b" :direction :asc}]}+ :expected "CREATE INDEX \"by_ts\" ON \"events\" (\"a\" DESC, \"b\" ASC)"}+ {:label "direction is btree-only; dropped for the other methods (gin rejects ASC/DESC)"+ :schema nil :table "events"+ :structured {:kind :gin :name "g" :columns [{:name "data" :direction :desc}]}+ :expected "CREATE INDEX \"g\" ON \"events\" USING gin (\"data\")"}])++(deftest ^:parallel compile-create-index-test+ (doseq [{:keys [label schema table structured expected]} render-cases]+ (testing label+ (is (= [[expected]] (driver/compile-create-index :postgres schema table structured))))))++;;; --------------------------------------- Live execute path ----------------------------------------++(defn- index-info+ "Access method and uniqueness of the index named `index-name` as `{:access-method ..., :unique? ...}`, or nil if it+ doesn't exist. Doubles as an existence check."+ [conn index-name]+ (when-let [row (first (jdbc/query conn+ [(str "SELECT am.amname AS access_method, i.indisunique AS is_unique "+ "FROM pg_class c "+ "JOIN pg_index i ON i.indexrelid = c.oid "+ "JOIN pg_am am ON am.oid = c.relam "+ "WHERE c.relkind = 'i' AND c.relname = ?")+ index-name]))]+ {:access-method (:access_method row), :unique? (:is_unique row)}))++(def ^:private execute-cases+ "Each case: a table to materialize (`columns` is the column DDL), the index to apply, and the `index-info` the+ resulting index must report. Add a row to exercise a new kind end-to-end against a real database (e.g. a gin+ index over a jsonb column)."+ [{:label "single-column btree"+ :table "perf_idx_btree"+ :columns "id INT, user_id INT"+ :structured {:kind :btree :name "btree_user_id" :columns [{:name "user_id"}] :if-not-exists true}+ :expected {:access-method "btree", :unique? false}}+ {:label "unique single-column btree"+ :table "perf_idx_unique"+ :columns "id INT, email TEXT"+ :structured {:kind :btree :name "unique_email" :columns [{:name "email"}] :unique true :if-not-exists true}+ :expected {:access-method "btree", :unique? true}}+ {:label "gin over a jsonb column"+ :table "perf_idx_gin"+ :columns "id INT, data JSONB"+ :structured {:kind :gin :name "gin_data" :columns [{:name "data"}] :if-not-exists true}+ :expected {:access-method "gin", :unique? false}}+ {:label "brin over a timestamp column"+ :table "perf_idx_brin"+ :columns "id INT, ts TIMESTAMP"+ :structured {:kind :brin :name "brin_ts" :columns [{:name "ts"}] :if-not-exists true}+ :expected {:access-method "brin", :unique? false}}+ {:label "gist over a point column (built-in point_ops opclass, no extension needed)"+ :table "perf_idx_gist"+ :columns "id INT, p POINT"+ :structured {:kind :gist :name "gist_p" :columns [{:name "p"}] :if-not-exists true}+ :expected {:access-method "gist", :unique? false}}])++(deftest standalone-create-path-test+ (testing "the standalone-create path runs the rendered DDL and then ANALYZE against a real table"+ (mt/test-driver :postgres+ (mt/with-empty-db+ (let [admin-spec (sql-jdbc.conn/db->pooled-connection-spec (mt/db))+ conn-spec (driver/connection-spec :postgres (mt/db))+ schema "public"]+ (doseq [{:keys [label table columns structured expected]} execute-cases]+ (testing label+ (let [index-name (:name structured)+ qtable (str (sql.u/quote-name :postgres :schema schema) "."+ (sql.u/quote-name :postgres :table table))]+ (jdbc/execute! admin-spec [(format "DROP TABLE IF EXISTS %s" qtable)])+ (jdbc/execute! admin-spec [(format "CREATE TABLE %s (%s)" qtable columns)])+ (try+ (is (nil? (index-info admin-spec index-name))+ "index absent before the standalone-create step")+ (testing "rendered DDL creates the index with the expected access method and uniqueness"+ (driver/execute-raw-queries! :postgres conn-spec+ (driver/compile-create-index :postgres schema table structured))+ (is (= expected (index-info admin-spec index-name))))+ (testing "re-running is idempotent (IF NOT EXISTS)"+ (driver/execute-raw-queries! :postgres conn-spec+ (driver/compile-create-index :postgres schema table structured))+ (is (= expected (index-info admin-spec index-name))))+ (testing "refresh-table-stats! runs ANALYZE without error"+ (is (some? (driver/refresh-table-stats! :postgres (mt/db) schema table :table))))+ (finally+ (jdbc/execute! admin-spec [(format "DROP TABLE IF EXISTS %s" qtable)])))))))))))++(deftest create-index!-shared-render-path-test+ (testing "driver/create-index! executes through the same per-driver rendering as compile-create-index"+ (mt/test-driver :postgres+ (mt/with-empty-db+ (let [admin-spec (sql-jdbc.conn/db->pooled-connection-spec (mt/db))+ db-id (:id (mt/db))]+ (jdbc/execute! admin-spec ["DROP TABLE IF EXISTS \"public\".\"perf_idx_legacy\""])+ (jdbc/execute! admin-spec ["CREATE TABLE \"public\".\"perf_idx_legacy\" (id INT, user_id INT)"])+ (try+ (driver/create-index! :postgres db-id "public" "perf_idx_legacy" "legacy_user_id" ["user_id"])+ (is (= {:access-method "btree", :unique? false} (index-info admin-spec "legacy_user_id")))+ (testing "without :if-not-exists a duplicate create throws"+ (is (thrown? Exception+ (driver/create-index! :postgres db-id "public" "perf_idx_legacy"+ "legacy_user_id" ["user_id"]))))+ (testing "with :if-not-exists a duplicate create is a no-op"+ (is (nil? (driver/create-index! :postgres db-id "public" "perf_idx_legacy"+ "legacy_user_id" ["user_id"] :if-not-exists true))))+ (finally+ (jdbc/execute! admin-spec ["DROP TABLE IF EXISTS \"public\".\"perf_idx_legacy\""]))))))))diff --git a/test/metabase/indexes/models/table_index_test.clj b/test/metabase/indexes/models/table_index_test.cljnew file mode 100644index 00000000000..cc87b7ba246--- /dev/null+++ b/test/metabase/indexes/models/table_index_test.clj@@ -0,0 +1,190 @@+(ns metabase.indexes.models.table-index-test+ (:require+ [clojure.test :refer :all]+ [metabase.indexes.models.table-index :as table-index]+ [metabase.test :as mt]+ [metabase.transforms.query-test-util :as query-test-util]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++(defn- temp-transform-spec []+ {:name (mt/random-name)+ :source {:type "query" :query (query-test-util/make-query :source-table "venues")}+ :target {:database (mt/id) :type "table" :schema "public" :name (mt/random-name)}})++(deftest roundtrip-and-defaults-test+ (testing "structured reads back with keyword-valued fields, and lifecycle defaults are set"+ (mt/with-temp [:model/Transform {transform-id :id} (temp-transform-spec)]+ (let [{:keys [id]} (t2/insert-returning-instance!+ :model/TableIndex+ {:transform_id transform-id+ :index_name "by_cat"+ :structured {:kind :btree :name "by_cat" :columns [{:name "category" :direction :asc}]}})+ back (t2/select-one :model/TableIndex :id id)]+ (is (= :create-pending (:status back)) "before-insert defaults status to :create-pending")+ (is (= :btree (get-in back [:structured :kind])) "kind re-keywordized on read")+ (is (= :asc (get-in back [:structured :columns 0 :direction])))))))++(deftest invalid-structured-rejected-test+ (testing "the :structured transform validates against the schema on write"+ (mt/with-temp [:model/Transform {transform-id :id} (temp-transform-spec)]+ (is (thrown?+ Exception+ (t2/insert! :model/TableIndex+ {:transform_id transform-id+ :index_name "bad"+ :structured {:kind :not-a-kind :columns [{:name "a"}]}}))))))++(deftest invalid-status-rejected-test+ (testing "the :status transform rejects values outside the enum"+ (mt/with-temp [:model/Transform {transform-id :id} (temp-transform-spec)]+ (is (thrown?+ Exception+ (t2/insert! :model/TableIndex+ {:transform_id transform-id+ :index_name "bad-status"+ :status :bogus+ :structured {:kind :btree :name "x" :columns [{:name "a"}]}}))))))++(deftest running-transition-helpers-test+ (mt/with-temp [:model/Transform {transform-id :id} (temp-transform-spec)+ :model/TableIndex {create-id :id} {:transform_id transform-id+ :index_name "create_idx"+ :structured {:kind :btree :name "create_idx"+ :columns [{:name "a"}]}}+ :model/TableIndex {update-id :id} {:transform_id transform-id+ :index_name "update_idx"+ :status :update-pending+ :structured {:kind :btree :name "update_idx"+ :columns [{:name "b"}]}}+ :model/TableIndex {failed-id :id} {:transform_id transform-id+ :index_name "failed_idx"+ :status :failed+ :error_message "old failure"+ :structured {:kind :btree :name "failed_idx"+ :columns [{:name "c"}]}}+ :model/TableIndex {running-id :id} {:transform_id transform-id+ :index_name "running_idx"+ :status :running+ :structured {:kind :btree :name "running_idx"+ :columns [{:name "e"}]}}+ :model/TableIndex {deleted-id :id} {:transform_id transform-id+ :index_name "deleted_idx"+ :status :delete-pending+ :structured {:kind :btree :name "deleted_idx"+ :columns [{:name "d"}]}}]+ (let [ids (table-index/mark-runnable-indexes-running! [create-id update-id failed-id running-id])]+ (is (= #{create-id update-id failed-id running-id} ids))+ (is (= :running (t2/select-one-fn :status :model/TableIndex create-id)))+ (is (= :running (t2/select-one-fn :status :model/TableIndex update-id)))+ (is (= :running (t2/select-one-fn :status :model/TableIndex failed-id)))+ (is (= :running (t2/select-one-fn :status :model/TableIndex running-id)))+ (is (= :delete-pending (t2/select-one-fn :status :model/TableIndex deleted-id)))+ (t2/update! :model/TableIndex create-id {:status :succeeded})+ (table-index/mark-unverified-running-indexes-failed! ids "not verified")+ (is (= :succeeded (t2/select-one-fn :status :model/TableIndex create-id)))+ (is (= :failed (t2/select-one-fn :status :model/TableIndex update-id)))+ (is (= :failed (t2/select-one-fn :status :model/TableIndex failed-id)))+ (is (= :failed (t2/select-one-fn :status :model/TableIndex running-id)))+ (is (= "not verified" (t2/select-one-fn :error_message :model/TableIndex update-id))))))++(deftest mark-for-revalidation-test+ (testing "every applicable request is flipped to :update-pending, clearing stale errors; delete-pending rows untouched"+ (mt/with-temp [:model/Transform {transform-id :id} (temp-transform-spec)+ :model/TableIndex {create-id :id} {:transform_id transform-id+ :index_name "create_idx"+ :structured {:kind :btree :name "create_idx"+ :columns [{:name "a"}]}}+ :model/TableIndex {succeeded-id :id} {:transform_id transform-id+ :index_name "succeeded_idx"+ :status :succeeded+ :structured {:kind :btree :name "succeeded_idx"+ :columns [{:name "b"}]}}+ :model/TableIndex {failed-id :id} {:transform_id transform-id+ :index_name "failed_idx"+ :status :failed+ :error_message "old failure"+ :structured {:kind :btree :name "failed_idx"+ :columns [{:name "c"}]}}+ :model/TableIndex {deleted-id :id} {:transform_id transform-id+ :index_name "deleted_idx"+ :status :delete-pending+ :structured {:kind :btree :name "deleted_idx"+ :columns [{:name "d"}]}}]+ (table-index/mark-for-revalidation! transform-id)+ (is (= :update-pending (t2/select-one-fn :status :model/TableIndex create-id)))+ (is (= :update-pending (t2/select-one-fn :status :model/TableIndex succeeded-id)))+ (is (= :update-pending (t2/select-one-fn :status :model/TableIndex failed-id)))+ (is (nil? (t2/select-one-fn :error_message :model/TableIndex failed-id)) "stale error cleared")+ (is (= :delete-pending (t2/select-one-fn :status :model/TableIndex deleted-id)) "pending deletion not revived")))+ (testing "a nil transform-id is a no-op"+ (is (nil? (table-index/mark-for-revalidation! nil)))))++(deftest select-for-verification-test+ (mt/with-temp [:model/Transform {transform-id :id} (temp-transform-spec)+ :model/TableIndex {running-id :id} {:transform_id transform-id+ :index_name "running_idx"+ :status :running+ :structured {:kind :btree :name "running_idx"+ :columns [{:name "a"}]}}+ :model/TableIndex {pending-id :id} {:transform_id transform-id+ :index_name "pending_idx"+ :status :update-pending+ :structured {:kind :btree :name "pending_idx"+ :columns [{:name "b"}]}}+ :model/TableIndex {deleted-id :id} {:transform_id transform-id+ :index_name "deleted_idx"+ :status :delete-pending+ :structured {:kind :btree :name "deleted_idx"+ :columns [{:name "c"}]}}]+ (is (= #{running-id deleted-id}+ (set (map :id (table-index/select-for-verification transform-id [running-id pending-id])))))))++(deftest select-applicable-for-transform-test+ (testing "returns the transform's rows ordered by name, excluding delete-pending"+ (mt/with-temp [:model/Transform {transform-id :id} (temp-transform-spec)+ :model/TableIndex {b-id :id} {:transform_id transform-id+ :index_name "b_idx"+ :structured {:kind :btree :name "b_idx" :columns [{:name "x"}]}}+ :model/TableIndex {a-id :id} {:transform_id transform-id+ :index_name "a_idx"+ :structured {:kind :btree :name "a_idx" :columns [{:name "y"}]}}+ :model/TableIndex _ {:transform_id transform-id+ :index_name "deleted_idx"+ :status :delete-pending+ :structured {:kind :btree :name "deleted_idx" :columns [{:name "z"}]}}]+ (is (= [a-id b-id]+ (map :id (table-index/select-applicable-for-transform transform-id)))))))++(deftest transform-edit-marks-indexes-for-revalidation-test+ (testing "editing a transform's target flips its applicable indexes to :update-pending; delete-pending untouched"+ (mt/with-temp [:model/Transform {transform-id :id :as transform} (temp-transform-spec)+ :model/TableIndex {create-id :id} {:transform_id transform-id+ :index_name "create_idx"+ :structured {:kind :btree :name "create_idx"+ :columns [{:name "a"}]}}+ :model/TableIndex {succeeded-id :id} {:transform_id transform-id+ :index_name "succeeded_idx"+ :status :succeeded+ :structured {:kind :btree :name "succeeded_idx"+ :columns [{:name "b"}]}}+ :model/TableIndex {deleted-id :id} {:transform_id transform-id+ :index_name "deleted_idx"+ :status :delete-pending+ :structured {:kind :btree :name "deleted_idx"+ :columns [{:name "c"}]}}]+ (t2/update! :model/Transform transform-id {:target (assoc (:target transform) :name (mt/random-name))})+ (is (= :update-pending (t2/select-one-fn :status :model/TableIndex create-id)))+ (is (= :update-pending (t2/select-one-fn :status :model/TableIndex succeeded-id)))+ (is (= :delete-pending (t2/select-one-fn :status :model/TableIndex deleted-id))))))++(deftest deleting-transform-removes-its-indexes-test+ (testing "the transform_id FK cascades, so deleting a transform drops its index requests"+ (mt/with-temp [:model/Transform {transform-id :id} (temp-transform-spec)]+ (t2/insert! :model/TableIndex {:transform_id transform-id+ :index_name "idx"+ :structured {:kind :btree :name "idx" :columns [{:name "a"}]}})+ (is (t2/exists? :model/TableIndex :transform_id transform-id))+ (t2/delete! :model/Transform transform-id)+ (is (not (t2/exists? :model/TableIndex :transform_id transform-id))))))diff --git a/test/metabase/indexes/reconcile_test.clj b/test/metabase/indexes/reconcile_test.cljnew file mode 100644index 00000000000..169254c221f--- /dev/null+++ b/test/metabase/indexes/reconcile_test.clj@@ -0,0 +1,139 @@+(ns metabase.indexes.reconcile-test+ (:require+ [clojure.test :refer :all]+ [metabase.driver]+ [metabase.indexes.reconcile :as reconcile]))++(def ^:private managed-btree+ {:id 1 :transform_id 7 :index_name "by_cat"+ :structured {:kind :btree :name "by_cat" :columns [{:name "name"}] :unique true}+ :status :create-pending :error_message nil :created_by 3 :last_executed_at nil})++(def ^:private managed-sortkey+ {:id 2 :transform_id 7 :index_name "sortkey"+ :structured {:kind :sortkey :style :compound :columns [{:name "a"} {:name "b"}]}+ :status :create-pending :error_message nil :created_by 3 :last_executed_at nil})++(def ^:private wh-btree+ {:name "by_cat" :kind :btree :access-method "btree" :is-unique true :is-primary false+ :is-valid true :key-columns ["name"] :include-columns [] :partial-predicate nil :definition "CREATE INDEX by_cat ..."})++(def ^:private wh-sortkey+ {:name nil :kind :sortkey :access-method "compound" :is-unique false :is-primary false+ :is-valid true :key-columns ["a" "b"] :include-columns [] :partial-predicate nil :definition nil})++(def ^:private managed-distkey+ {:id 3 :transform_id 7 :index_name "distkey"+ :structured {:kind :distkey :style :key :columns [{:name "category"}]}+ :status :create-pending :error_message nil :created_by 3 :last_executed_at nil})++(def ^:private wh-distkey+ {:name nil :kind :distkey :access-method "key" :is-unique false :is-primary false+ :is-valid true :key-columns ["category"] :include-columns [] :partial-predicate nil :definition nil})++(def ^:private managed-even-distkey+ {:id 4 :transform_id 7 :index_name "distkey"+ :structured {:kind :distkey :style :even}+ :status :pending :error_message nil :created_by 3 :last_executed_at nil})++(def ^:private wh-even-distkey+ {:name nil :kind :distkey :access-method "even" :is-unique false :is-primary false+ :is-valid true :key-columns [] :include-columns [] :partial-predicate nil :definition "DISTSTYLE EVEN"})++(def ^:private wh-dba+ {:name "dba_made" :kind :btree :access-method "btree" :is-unique false :is-primary false+ :is-valid true :key-columns ["price"] :include-columns [] :partial-predicate nil :definition "CREATE INDEX dba_made ..."})++(deftest match-key-test+ (testing "named kinds key by name; managed and warehouse agree"+ (is (= {:kind :named :name "by_cat"} (reconcile/managed-match-key managed-btree)))+ (is (= {:kind :named :name "by_cat"} (reconcile/match-key wh-btree))))+ (testing "unnamed inline kinds key by kind+columns, so managed and warehouse agree"+ (is (= {:kind :sortkey :key-columns ["a" "b"]} (reconcile/managed-match-key managed-sortkey)))+ (is (= {:kind :sortkey :key-columns ["a" "b"]} (reconcile/match-key wh-sortkey))))+ (testing "a key distkey is keyed by its style + column, so managed and warehouse agree (#76331)"+ (is (= {:kind :distkey :style "key" :key-columns ["category"]} (reconcile/managed-match-key managed-distkey)))+ (is (= {:kind :distkey :style "key" :key-columns ["category"]} (reconcile/match-key wh-distkey))))+ (testing "distkey keys are style-aware: column-less even and all don't collapse onto the same key"+ (is (= {:kind :distkey :style "even" :key-columns []} (reconcile/managed-match-key managed-even-distkey)))+ (is (= {:kind :distkey :style "even" :key-columns []} (reconcile/match-key wh-even-distkey)))+ (is (not= (reconcile/managed-match-key managed-even-distkey)+ (reconcile/managed-match-key (assoc-in managed-even-distkey [:structured :style] :all))))+ (testing "a stray column on a non-key request is ignored, so it still matches the column-less warehouse distkey"+ (is (= {:kind :distkey :style "even" :key-columns []}+ (reconcile/managed-match-key (assoc-in managed-even-distkey [:structured :columns] [{:name "x"}])))))))++(deftest merge-indexes-test+ (testing "managed + present: observed from the warehouse, flagged managed, request carries lifecycle + structured"+ (let [[e] (reconcile/merge-indexes [managed-btree] [wh-btree])]+ (is (true? (:metabase_managed e)))+ (is (true? (:present_in_warehouse e)))+ (is (= "by_cat" (:name e)))+ (is (true? (:is_unique e)))+ (is (= 1 (-> e :request :id)))+ (is (= :create-pending (-> e :request :status)))+ (is (= (:structured managed-btree) (-> e :request :structured)))))+ (testing "DBA (warehouse-only): observed, unmanaged, no request bookkeeping"+ (let [[e] (reconcile/merge-indexes [] [wh-dba])]+ (is (false? (:metabase_managed e)))+ (is (true? (:present_in_warehouse e)))+ (is (= "dba_made" (:name e)))+ (is (= ["price"] (:key_columns e)))+ (is (nil? (:request e)))))+ (testing "managed + absent: projected from its declared structured, present_in_warehouse false"+ (let [[e] (reconcile/merge-indexes [managed-btree] [])]+ (is (true? (:metabase_managed e)))+ (is (false? (:present_in_warehouse e)))+ (is (= "by_cat" (:name e)))+ (is (true? (:is_unique e)))+ (is (= :create-pending (-> e :request :status)))))+ (testing "a managed inline sortkey matches the warehouse sortkey by kind+columns, listed once as managed"+ (let [merged (reconcile/merge-indexes [managed-sortkey] [wh-sortkey])]+ (is (= 1 (count merged)))+ (is (true? (:metabase_managed (first merged))))+ (is (true? (:present_in_warehouse (first merged))))))+ (testing "a managed inline distkey matches the warehouse distkey by style+columns, listed once as managed"+ (let [merged (reconcile/merge-indexes [managed-distkey] [wh-distkey])]+ (is (= 1 (count merged)))+ (is (true? (:metabase_managed (first merged))))+ (is (true? (:present_in_warehouse (first merged))))))+ (testing "a managed even distkey matches an even warehouse distkey, but not an all one"+ (is (true? (:present_in_warehouse (first (reconcile/merge-indexes [managed-even-distkey] [wh-even-distkey])))))+ (let [merged (reconcile/merge-indexes [managed-even-distkey]+ [(assoc wh-even-distkey :access-method "all")])+ managed (first (filter :metabase_managed merged))]+ (is (false? (:present_in_warehouse managed)))))+ (testing "mix: a matched managed index, plus a DBA index alongside it"+ (let [merged (reconcile/merge-indexes [managed-btree] [wh-btree wh-dba])+ by-flag (group-by :metabase_managed merged)]+ (is (= 2 (count merged)))+ (is (= 1 (count (get by-flag true))))+ (is (= 1 (count (get by-flag false))))+ (is (= "dba_made" (-> (get by-flag false) first :name))))))++(deftest classify-index-outcomes-test+ (testing "each managed request lands in the bucket its warehouse presence + applicability imply"+ (let [present (reconcile/warehouse-key-set [wh-btree]) ; only the named by_cat index physically present+ succ-row managed-btree ; applicable + present -> succeeded+ fail-row managed-sortkey ; applicable + absent -> failed+ kept-row (assoc managed-btree :id 8 :status :delete-pending) ; delete-pending + present -> kept+ dropped-row (assoc managed-sortkey :id 9 :status :delete-pending) ; delete-pending + absent -> row dropped+ out (reconcile/classify-index-outcomes [succ-row fail-row kept-row dropped-row] present)]+ (is (= [1] (map :id (:succeeded out))))+ (is (= [2] (map :id (:failed out))))+ (is (= [8] (map :id (:delete-pending out))))+ (is (= [9] (map :id (:delete-row out))))+ (testing "every row is classified into exactly one bucket"+ (is (= 4 (reduce + (map count (vals out)))))))))++(deftest fetch-warehouse-indexes-test+ (testing "delegates to the driver method"+ (with-redefs [metabase.driver/fetch-table-indexes (fn [_driver _db _schema _table] [wh-btree])]+ (is (= [wh-btree]+ (reconcile/fetch-warehouse-indexes {:engine :postgres} "public" "t")))))+ (testing "preserves a successful empty warehouse response"+ (with-redefs [metabase.driver/fetch-table-indexes (fn [& _] [])]+ (is (= [] (reconcile/fetch-warehouse-indexes {:engine :postgres} "public" "t")))))+ (testing "swallows driver/connection errors and returns nil"+ (with-redefs [metabase.driver/fetch-table-indexes (fn [& _] (throw (ex-info "boom" {})))]+ (is (nil? (reconcile/fetch-warehouse-indexes {:engine :postgres} "public" "t"))))))diff --git a/test/metabase/indexes/requestable_test.clj b/test/metabase/indexes/requestable_test.cljnew file mode 100644index 00000000000..1df4fce4ce4--- /dev/null+++ b/test/metabase/indexes/requestable_test.clj@@ -0,0 +1,42 @@+(ns metabase.indexes.requestable-test+ "Checks that the form descriptors `driver/supported-index-methods` returns stay in sync with `::index-structured`, the+ schema `POST /api/index/request` validates request bodies against."+ (:require+ [clojure.test :refer :all]+ [metabase.driver :as driver]+ [metabase.driver.postgres]+ [metabase.indexes.schema :as schema]+ [metabase.util.malli.registry :as mr]))++(comment metabase.driver.postgres/keep-me)++(deftest return-conforms-to-schema-test+ (testing "the supported-index-methods return validates against ::driver/supported-index-methods"+ (is (mr/validate ::driver/supported-index-methods (driver/supported-index-methods :postgres nil)))+ (testing "including the empty default for a driver with no index support"+ (is (mr/validate ::driver/supported-index-methods (driver/supported-index-methods :h2 nil))))))++(deftest postgres-lifecycle-matches-feature-flag-test+ (testing ":standalone <=> :index/standalone-create, :inline <=> :index/inline-create"+ (doseq [[kind {:keys [lifecycle]}] (driver/supported-index-methods :postgres nil)]+ (is (true? (case lifecycle+ :standalone (driver/database-supports? :postgres :index/standalone-create nil)+ :inline (driver/database-supports? :postgres :index/inline-create nil)))+ (str kind " lifecycle " lifecycle " should match its feature flag")))))++(deftest schema-accepts-inline-kinds-test+ (testing "::index-structured accepts the body shape the FE builds for the inline/ClickHouse kinds"+ (are [body] (mr/validate ::schema/index-structured (schema/keywordize-structured body))+ {:kind :order-by :columns [{:name "a"}]}+ {:kind :sortkey :style "compound" :columns [{:name "a"}]}+ {:kind :sortkey :style "interleaved" :columns [{:name "a"}]}+ {:kind :skip-index :name "s" :columns [{:name "a"}] :type "minmax"}+ {:kind :skip-index :name "s" :columns [{:name "a"}] :type "bloom_filter" :granularity 4}+ {:kind :distkey :style "key" :columns [{:name "a"}]}+ {:kind :distkey :style "all"}+ {:kind :distkey :style "even"})))++(deftest distkey-key-requires-a-column-test+ (testing "a :key distkey without a column is rejected; the column-less styles are fine"+ (is (not (mr/validate ::schema/index-structured (schema/keywordize-structured {:kind :distkey :style "key"}))))+ (is (mr/validate ::schema/index-structured (schema/keywordize-structured {:kind :distkey :style "all"})))))diff --git a/test/metabase/indexes/serdes_test.clj b/test/metabase/indexes/serdes_test.cljnew file mode 100644index 00000000000..8e7df2dfc58--- /dev/null+++ b/test/metabase/indexes/serdes_test.clj@@ -0,0 +1,35 @@+(ns metabase.indexes.serdes-test+ (:require+ [clojure.test :refer :all]+ [metabase.models.serialization :as serdes]+ [metabase.test :as mt]+ [metabase.transforms.query-test-util :as query-test-util]+ [metabase.util :as u]))++(set! *warn-on-reflection* true)++(defn- temp-transform-spec []+ {:name (mt/random-name)+ :source {:type "query" :query (query-test-util/make-query :source-table "venues")}+ :target {:database (mt/id) :type "table" :schema "public" :name (mt/random-name)}})++(deftest transform-indexes-inlined-test+ (testing "a transform's managed indexes are inlined into its serialization, definition only"+ (mt/with-temp [:model/Transform {transform-id :id} (temp-transform-spec)+ :model/TableIndex {idx-id :id} {:transform_id transform-id+ :index_name "by_cat"+ :structured {:kind :btree :name "by_cat"+ :columns [{:name "category" :direction :asc}]}+ :status :succeeded+ :error_message "boom"}]+ (let [hydrated (u/rfirst (serdes/extract-query "Transform" {:where [:= :id transform-id]}))]+ (testing "extract-query hydrates the index under :indexes"+ (is (= [idx-id] (map :id (:indexes hydrated)))))+ (testing "the serialized index keeps its definition and drops runtime/local state"+ (let [idx (-> (serdes/extract-one "Transform" {} hydrated) :indexes first)]+ (is (= "by_cat" (:index_name idx)))+ (is (= :btree (get-in idx [:structured :kind])))+ (is (not (contains? idx :status)))+ (is (not (contains? idx :error_message)))+ (is (not (contains? idx :table_id)))+ (is (not (contains? idx :id)))))))))diff --git a/test/metabase/indexes_rest/api_test.clj b/test/metabase/indexes_rest/api_test.cljnew file mode 100644index 00000000000..3b88bd2c4d9--- /dev/null+++ b/test/metabase/indexes_rest/api_test.clj@@ -0,0 +1,197 @@+(ns ^:synchronous metabase.indexes-rest.api-test+ (:require+ [clojure.test :refer :all]+ [metabase.driver]+ [metabase.test :as mt]+ [metabase.transforms-base.util :as transforms-base.u]+ [metabase.transforms.query-test-util :as query-test-util]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++;; `transforms-enabled` is false unless explicitly set off-cloud, and every index endpoint inherits the transform's+;; permission checks, which fail when transforms are disabled.+(use-fixtures :each (fn [thunk]+ (mt/with-temporary-raw-setting-values [transforms-enabled "true"]+ (thunk))))++(defn- temp-transform-spec+ "A real query transform over a test-data table. Query transforms are available without a premium feature on+ non-hosted instances, so a superuser passes the transform read/write checks the index endpoints rely on."+ []+ {:name (mt/random-name)+ :source {:type "query" :query (query-test-util/make-query :source-table "venues")}+ :target {:database (mt/id) :type "table" :schema "public" :name (mt/random-name)}})++(defn- temp-incremental-transform-spec []+ (assoc-in (temp-transform-spec) [:target :type] "table-incremental"))++(def ^:private btree {:kind "btree" :name "by_cat" :columns [{:name "name"}]})++(deftest crud-happy-path-test+ (mt/with-temp [:model/Transform {transform-id :id} (temp-transform-spec)]+ (testing "POST creates a create-pending index"+ (let [created (mt/user-http-request :crowberto :post 200 "index/request"+ {:transform_id transform-id :structured btree})]+ (is (= "create-pending" (:status created)))+ (is (= transform-id (:transform_id created)))+ (is (= "by_cat" (:index_name created)))+ (with-redefs [metabase.driver/fetch-table-indexes (fn [& _] [])]+ (testing "GET lists it for the transform (managed hint, not yet in the warehouse)"+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200+ (str "index?transform-id=" transform-id))]+ (is (= [(:id created)] (map #(get-in % [:request :id]) data)))+ (is (false? (:present_in_warehouse (first data))))))+ (testing "the listed index carries no mirrored table_id"+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200+ (str "index?transform-id=" transform-id))]+ (is (not (contains? (first data) :table_id))))))+ (testing "GET /request/:id fetches one (status poll)"+ (is (= "by_cat" (:index_name (mt/user-http-request :crowberto :get 200+ (str "index/request/" (:id created)))))))+ (testing "PUT replaces the structured definition"+ (let [updated (mt/user-http-request :crowberto :put 200 (str "index/request/" (:id created))+ {:structured (assoc btree :columns [{:name "price"}])})]+ (is (= "update-pending" (:status updated)))+ (is (= "price" (-> updated :structured :columns first :name)))))+ (testing "DELETE marks it delete-pending until a rebuild drops the warehouse index"+ (mt/user-http-request :crowberto :delete 204 (str "index/request/" (:id created)))+ (with-redefs [metabase.driver/fetch-table-indexes+ (fn [& _] [{:name "by_cat" :kind :btree :access-method "btree" :is-unique false+ :is-primary false :is-valid true :key-columns ["name"] :include-columns []+ :partial-predicate nil :definition "..."}])]+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200+ (str "index?transform-id=" transform-id))]+ (is (= [(:id created)] (map #(get-in % [:request :id]) data)))+ (is (= "delete-pending" (-> data first :request :status)))+ (is (true? (:present_in_warehouse (first data)))))))))))++(deftest merged-list-test+ (mt/with-temp [:model/Transform {transform-id :id} (temp-transform-spec)]+ (let [created (mt/user-http-request :crowberto :post 200 "index/request"+ {:transform_id transform-id :structured btree})+ ;; one warehouse index matching the managed one by name, plus a DBA-made one+ wh [{:name "by_cat" :kind :btree :access-method "btree" :is-unique false :is-primary false+ :is-valid true :key-columns ["name"] :include-columns [] :partial-predicate nil :definition "..."}+ {:name "dba_made" :kind :btree :access-method "btree" :is-unique false :is-primary false+ :is-valid true :key-columns ["price"] :include-columns [] :partial-predicate nil :definition "..."}]]+ (with-redefs [metabase.driver/fetch-table-indexes (fn [& _] wh)]+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200+ (str "index?transform-id=" transform-id))+ by-name (group-by :name data)]+ (testing "the managed index is observed from the warehouse, flagged managed, request carries its id"+ (let [e (first (get by-name "by_cat"))]+ (is (true? (:metabase_managed e)))+ (is (true? (:present_in_warehouse e)))+ (is (= (:id created) (-> e :request :id)))))+ (testing "the DBA index appears, unmanaged, observed, with no request bookkeeping"+ (let [e (first (get by-name "dba_made"))]+ (is (false? (:metabase_managed e)))+ (is (true? (:present_in_warehouse e)))+ (is (= ["price"] (:key_columns e)))+ (is (nil? (:request e)))))+ (testing "nothing unmanaged was persisted"+ (is (= 1 (count (t2/select :model/TableIndex :transform_id transform-id))))))))))++(deftest index-endpoints-require-transform-permission-test+ (testing "every index endpoint inherits the transform's permission: a user without access is blocked from all of them"+ (mt/with-temp [:model/Transform {transform-id :id} (temp-transform-spec)]+ (let [req-id (:id (mt/user-http-request :crowberto :post 200 "index/request"+ {:transform_id transform-id :structured btree}))]+ (testing "reads require transform read access"+ (mt/user-http-request :rasta :get 403 (str "index?transform-id=" transform-id))+ (mt/user-http-request :rasta :get 403 (str "index/request/" req-id)))+ (testing "mutations require transform write access"+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :post 403 "index/request"+ {:transform_id transform-id :structured btree})))+ (mt/user-http-request :rasta :put 403 (str "index/request/" req-id)+ {:structured (assoc btree :columns [{:name "price"}])})+ (mt/user-http-request :rasta :delete 403 (str "index/request/" req-id)))))))++(deftest list-requires-transform-id-test+ (testing "GET requires transform-id"+ (is (re-find #"transform-id"+ (str (mt/user-http-request :crowberto :get 400 "index"))))))++(deftest unknown-transform-404s-test+ (testing "creating an index for a non-existent transform 404s"+ (mt/user-http-request :crowberto :post 404 "index/request"+ {:transform_id Integer/MAX_VALUE :structured btree})))++(deftest duplicate-index-name-rejected-test+ (testing "you can't create two indexes with the same name on one transform"+ (mt/with-temp [:model/Transform {transform-id :id} (temp-transform-spec)]+ (mt/user-http-request :crowberto :post 200 "index/request"+ {:transform_id transform-id :structured btree})+ (is (re-find #"already exists"+ (mt/user-http-request :crowberto :post 400 "index/request"+ {:transform_id transform-id :structured btree}))))))++(deftest malformed-structured-rejected-test+ (mt/with-temp [:model/Transform {transform-id :id} (temp-transform-spec)]+ (testing "an unknown :kind is rejected before it can reach the DB"+ (mt/user-http-request :crowberto :post 400 "index/request"+ {:transform_id transform-id :structured (assoc btree :kind "not_a_kind")}))+ (testing "a name over the 63-char limit is rejected"+ (mt/user-http-request :crowberto :post 400 "index/request"+ {:transform_id transform-id+ :structured (assoc btree :name (apply str (repeat 64 "a")))}))+ (testing "a 63-char name is accepted (boundary)"+ (mt/user-http-request :crowberto :post 200 "index/request"+ {:transform_id transform-id+ :structured (assoc btree :name (apply str (repeat 63 "a")))}))))++(deftest put-cannot-change-index-key-test+ (mt/with-temp [:model/Transform {transform-id :id} (temp-transform-spec)]+ (let [created (mt/user-http-request :crowberto :post 200 "index/request"+ {:transform_id transform-id :structured btree})]+ (testing "name is stable"+ (is (re-find #"name cannot be changed"+ (mt/user-http-request :crowberto :put 400 (str "index/request/" (:id created))+ {:structured (assoc btree :name "by_price")}))))+ (testing "kind is stable"+ (is (re-find #"type cannot be changed"+ (mt/user-http-request :crowberto :put 400 (str "index/request/" (:id created))+ {:structured (assoc btree :kind "hash")})))))))++(deftest soft-deleted-index-cannot-be-recreated-test+ (mt/with-temp [:model/Transform {transform-id :id} (temp-transform-spec)]+ (let [created (mt/user-http-request :crowberto :post 200 "index/request"+ {:transform_id transform-id :structured btree})]+ (mt/user-http-request :crowberto :delete 204 (str "index/request/" (:id created)))+ (is (re-find #"already exists"+ (mt/user-http-request :crowberto :post 400 "index/request"+ {:transform_id transform-id :structured btree})))+ (is (= 1 (count (t2/select :model/TableIndex :transform_id transform-id)))))))++(deftest incremental-mutations-force-next-run-to-rebuild-test+ (mt/with-temp [:model/Transform {transform-id :id} (assoc (temp-incremental-transform-spec)+ :last_checkpoint_value "100")]+ (letfn [(full-run? []+ (transforms-base.u/full-incremental-run? (t2/select-one :model/Transform transform-id)))]+ (testing "no index changes: the watermark alone decides, so the next run appends"+ (is (not (full-run?))))+ (testing "POST leaves the watermark alone; the pending row forces the rebuild"+ (let [created (mt/user-http-request :crowberto :post 200 "index/request"+ {:transform_id transform-id :structured btree})]+ (is (= "100" (t2/select-one-fn :last_checkpoint_value :model/Transform transform-id)))+ (is (full-run?))+ (testing "PUT keeps forcing it (update-pending)"+ (mt/user-http-request :crowberto :put 200 (str "index/request/" (:id created))+ {:structured (assoc btree :columns [{:name "price"}])})+ (is (full-run?)))+ (testing "DELETE keeps forcing it (delete-pending), so the rebuild can drop the old index"+ (mt/user-http-request :crowberto :delete 204 (str "index/request/" (:id created)))+ (is (full-run?)))+ (testing "once the request settles, runs go back to appending"+ (t2/update! (t2/table-name :model/TableIndex) (:id created) {:status "succeeded"})+ (is (not (full-run?)))))))))++(deftest inline-kind-index-name-test+ (testing "an inline kind with no :name gets its index_name from :kind"+ (mt/with-temp [:model/Transform {transform-id :id} (temp-transform-spec)]+ (let [created (mt/user-http-request :crowberto :post 200 "index/request"+ {:transform_id transform-id+ :structured {:kind "sortkey" :style "compound" :columns [{:name "name"}]}})]+ (is (= "sortkey" (:index_name created)))))))diff --git a/test/metabase/transforms/execute_test.clj b/test/metabase/transforms/execute_test.cljindex 7be77cfb861..21c1461aa87 100644--- a/test/metabase/transforms/execute_test.clj+++ b/test/metabase/transforms/execute_test.clj@@ -1,5 +1,6 @@(ns ^:mb/driver-tests metabase.transforms.execute-test(:require+ [clojure.java.jdbc :as jdbc][clojure.string :as str][clojure.test :refer :all][metabase.config.core :as config]@@ -542,3 +543,41 @@(finally(t2/update! :model/Database db-id {:write_data_details old-write-details})(sql-jdbc.conn/invalidate-pool-for-db! (mt/db))))))))))++(deftest transform-run-refreshes-target-stats-test+ (testing "completing a transform run leaves its target table analyzed, so a dependent transform plans+ against real stats instead of the empty estimate a freshly CTAS'd table starts with"+ ;; The ANALYZE effect is observable on Postgres (Redshift inherits the same impl); assert it here.+ (mt/test-driver :postgres+ (mt/dataset transforms-dataset/transforms-test+ (let [schema (t2/select-one-fn :schema :model/Table (mt/id :transforms_products))+ source-name (t2/select-one-fn :name :model/Table (mt/id :transforms_products))+ admin-spec (sql-jdbc.conn/db->pooled-connection-spec (mt/db))+ ;; A table has one pg_statistic row per analyzed column; a never-analyzed CTAS table has none.+ analyzed-column-count+ (fn [table-name]+ (-> (jdbc/query admin-spec+ ["SELECT count(*) AS n FROM pg_stats WHERE schemaname = ? AND tablename = ?"+ schema table-name])+ first :n))+ run-and-wait! (fn [transform]+ (transforms.execute/execute! transform {:run-method :manual})+ (transforms.tu/wait-for-table (-> transform :target :name) 10000))]+ (testing "real lifecycle: the target ends up with planner stats"+ (with-transform-cleanup! [target {:type "table" :schema schema :name "products_analyzed"}]+ (mt/with-temp [:model/Transform t {:name "analyzed"+ :source {:type :query :query (make-query source-name)}+ :target target}]+ (run-and-wait! t)+ (is (pos? (analyzed-column-count (:name target)))+ "complete-execution! should have run ANALYZE, populating pg_statistic for the target"))))+ (testing "control: with the refresh hook stubbed out, the same run leaves no stats — so the rows+ above come from our refresh, not from Postgres analyzing on its own"+ (with-transform-cleanup! [target {:type "table" :schema schema :name "products_unanalyzed"}]+ (mt/with-temp [:model/Transform t {:name "unanalyzed"+ :source {:type :query :query (make-query source-name)}+ :target target}]+ (with-redefs [driver/refresh-table-stats! (fn [& _] nil)]+ (run-and-wait! t))+ (is (zero? (analyzed-column-count (:name target)))+ "a freshly materialized table has no planner stats until something analyzes it")))))))))diff --git a/test/metabase/transforms/index_test.clj b/test/metabase/transforms/index_test.cljnew file mode 100644index 00000000000..b898fb3c9d4--- /dev/null+++ b/test/metabase/transforms/index_test.clj@@ -0,0 +1,298 @@+(ns ^:mb/driver-tests metabase.transforms.index-test+ "End-to-end: indexes declared on a transform target reach the physical table when the transform runs, across+ re-runs and failures, for both transform kinds (SQL builds the table with a CTAS, Python with `create-table!`).+ Per-driver cases and helpers live in [[metabase.transforms.index-test-util]]. Each test persists real+ `:model/TableIndex` rows for its case, so the run reads them exactly like user-created requests."+ (:require+ [clojure.string :as str]+ [clojure.test :refer :all]+ [metabase.driver :as driver]+ [metabase.test :as mt]+ [metabase.test.data.sql :as sql.tx]+ [metabase.transforms-base.util :as transforms-base.u]+ [metabase.transforms.execute :as transforms.execute]+ [metabase.transforms.index-test-util :as index-util]+ [metabase.transforms.query-test-util :as query-test-util]+ [metabase.transforms.test-dataset :as transforms-dataset]+ [metabase.transforms.test-util :as transforms.tu :refer [with-transform-cleanup!]]+ [metabase.util.malli.registry :as mr]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++(defn- query-source+ "A SQL transform source that selects the whole `transforms_products` table (built via a CTAS)."+ []+ {:type :query+ :query (query-test-util/make-query+ {:source-table (t2/select-one-fn :name :model/Table (mt/id :transforms_products))})})++(defn- python-source+ "A Python transform source that returns `transforms_products` unchanged (built via `create-table!`)."+ []+ {:type "python"+ :source-database (mt/id)+ :source-tables [(transforms.tu/source-table-entry "transforms_products" (mt/id :transforms_products))]+ :body "def transform(transforms_products):\n return transforms_products"})++(defn- create-index-requests!+ "Persist `indexes` as `:model/TableIndex` rows for `transform-id`, so the run picks them up like real user-created+ requests. Cleaned up with the transform (FK cascade)."+ [transform-id indexes]+ (when (seq indexes)+ (t2/insert! :model/TableIndex (for [index indexes]+ {:transform_id transform-id+ :index_name (or (:name index) (name (:kind index)))+ :structured index}))))++(defn- test-declared-indexes!+ "Run a transform (source from the 0-arg `make-source`) with the driver's `:indexes` persisted as its index requests,+ then assert `:physical-indexes` reads `:expected` from the catalog. Runs twice to check they survive a rebuild."+ [{:keys [indexes expected physical-indexes]} make-source]+ (let [schema (t2/select-one-fn :schema :model/Table (mt/id :transforms_products))]+ (with-transform-cleanup! [{table-name :name :as target}+ {:type "table"+ :schema schema+ :name "idx_products"+ :database (mt/id)}]+ (mt/with-temp [:model/Transform transform {:name "index-transform"+ :source (make-source)+ :target target}]+ (create-index-requests! (:id transform) indexes)+ (testing "a full run applies the declared indexes to the physical table"+ (transforms.execute/execute! transform {:run-method :manual})+ (transforms.tu/wait-for-table table-name 10000)+ (is (= expected (physical-indexes (mt/db) schema table-name))))+ (testing "a re-run rebuilds the table and the indexes come back the same"+ (transforms.execute/execute! transform {:run-method :manual})+ (is (= expected (physical-indexes (mt/db) schema table-name))))))))++(deftest ^:synchronized declared-indexes-applied-and-replayed-test+ (mt/test-drivers (index-util/index-test-drivers)+ (mt/dataset transforms-dataset/transforms-test+ (let [test-case (index-util/driver-cases driver/*driver*)]+ (is (some? test-case) (index-util/missing-case-message driver/*driver*))+ (when test-case+ (test-declared-indexes! test-case query-source))))))++(deftest ^:synchronized ^:mb/transforms-python-test declared-indexes-applied-on-python-transform-test+ (mt/test-drivers (index-util/python-index-test-drivers)+ (mt/with-premium-features #{:transforms-basic :transforms-python}+ (mt/dataset transforms-dataset/transforms-test+ (let [test-case (index-util/driver-cases driver/*driver*)]+ (is (some? test-case) (index-util/missing-case-message driver/*driver*))+ (when test-case+ (test-declared-indexes! test-case python-source)))))))++(deftest ^:synchronized managed-indexes-verified-against-warehouse-after-run-test+ (testing "real managed index rows are created by the run and then verified :succeeded against the warehouse"+ ;; Reuses the driver create-index cases, but instead of stubbing select-applicable-for-transform it persists real+ ;; :model/TableIndex rows. The run reads them (real hydrate), applies them, and verify-managed-indexes! confirms+ ;; each landed via fetch-table-indexes -- the whole create-then-verify loop on a live warehouse.+ (mt/test-drivers (index-util/index-test-drivers)+ (mt/dataset transforms-dataset/transforms-test+ (let [{:keys [indexes]} (index-util/driver-cases driver/*driver*)+ schema (t2/select-one-fn :schema :model/Table (mt/id :transforms_products))]+ (with-transform-cleanup! [{table-name :name :as target}+ {:type "table" :schema schema :name "idx_verify_products" :database (mt/id)}]+ (mt/with-temp [:model/Transform {tid :id :as transform} {:name "index-verify-transform"+ :source (query-source)+ :target target}]+ (create-index-requests! tid indexes)+ (transforms.execute/execute! transform {:run-method :manual})+ (transforms.tu/wait-for-table table-name 10000)+ (testing "every managed row is verified succeeded"+ (is (= #{:succeeded} (t2/select-fn-set :status :model/TableIndex :transform_id tid))))+ ;; the index endpoints inherit the transform's permission checks, which fail when transforms are disabled+ (testing "GET /index lists them, flagged metabase_managed"+ (mt/with-temporary-raw-setting-values [transforms-enabled "true"]+ (let [{:keys [data]} (mt/user-http-request :crowberto :get 200 (str "index?transform-id=" tid))]+ (is (= (count indexes) (count (filter :metabase_managed data))))))))))))))++(deftest ^:synchronized declared-index-failure-fails-the-run-test+ (testing "a bad index declaration fails the whole run instead of being silently skipped"+ ;; The index points at a missing column, so creation fails (inline: the CTAS; standalone: the CREATE INDEX).+ ;; Either way it runs before the run is marked succeeded, so the throw surfaces and the run is recorded :failed.+ (mt/test-drivers (index-util/index-test-drivers)+ (mt/dataset transforms-dataset/transforms-test+ (let [test-case (index-util/driver-cases driver/*driver*)]+ (is (some? test-case) (index-util/missing-case-message driver/*driver*))+ (when test-case+ (let [bogus (index-util/bogus-indexes (:indexes test-case))+ schema (t2/select-one-fn :schema :model/Table (mt/id :transforms_products))]+ (with-transform-cleanup! [target {:type "table"+ :schema schema+ :name "idx_fail_products"+ :database (mt/id)}]+ (mt/with-temp [:model/Transform transform {:name "index-fail-transform"+ :source (query-source)+ :target target}]+ (create-index-requests! (:id transform) bogus)+ (testing "execute! throws"+ (is (thrown? Throwable+ (transforms.execute/execute! transform {:run-method :manual}))))+ (testing "and the run is recorded as failed"+ (is (= :failed+ (t2/select-one-fn :status :model/TransformRun+ :transform_id (:id transform)+ {:order-by [[:id :desc]]})))))))))))))++(deftest ^:synchronized declared-index-creation-is-idempotent-test+ (testing "re-applying a target's indexes is a no-op (CREATE INDEX IF NOT EXISTS), not an error"+ ;; The standalone path normally meets a fresh table; this pins that re-running it against the live table (index+ ;; already there) doesn't throw. No-op for inline-only drivers (covered by the replay test above).+ (mt/test-drivers (index-util/index-test-drivers)+ (mt/dataset transforms-dataset/transforms-test+ (let [{:keys [indexes expected physical-indexes] :as test-case} (index-util/driver-cases driver/*driver*)]+ (is (some? test-case) (index-util/missing-case-message driver/*driver*))+ (when test-case+ (let [db (mt/db)+ schema (t2/select-one-fn :schema :model/Table (mt/id :transforms_products))]+ (with-transform-cleanup! [{table-name :name :as target}+ {:type "table"+ :schema schema+ :name "idx_idempotent_products"+ :database (mt/id)}]+ (mt/with-temp [:model/Transform transform {:name "index-idempotent-transform"+ :source (query-source)+ :target target}]+ (create-index-requests! (:id transform) indexes)+ (transforms.execute/execute! transform {:run-method :manual})+ (transforms.tu/wait-for-table table-name 10000)+ (is (= expected (physical-indexes db schema table-name)) "indexes present after the run")+ (testing "re-applying the same indexes leaves the catalog unchanged and does not throw"+ (transforms-base.u/apply-target-indexes!+ (assoc-in transform [:target :indexes] indexes))+ (is (= expected (physical-indexes db schema table-name)))))))))))))++(defn- fetch-schema+ "Schema the fetch-correctness suite creates its table in and passes to fetch-table-indexes. nil when the connection+ has a default schema to fall back on; bigquery has no schema concept and snowflake's test connection sets none, so+ both qualify the DDL with their session schema."+ [driver]+ (when (or (= driver :snowflake)+ (not (isa? driver/hierarchy driver :sql-jdbc)))+ (sql.tx/session-schema driver)))++(defn- qualify-fetch-table+ "`schema`.`table` in the driver's own identifier quoting. Snowflake needs the double quotes: unquoted identifiers+ upper-case, and the fetch-case columns are asserted lower-case."+ [driver schema table]+ (if (= driver :snowflake)+ (format "\"%s\".\"%s\"" schema table)+ (format "`%s`.%s" schema table)))++(defn- run-fetch-ddl!+ "Run raw fetch-case DDL through execute-raw-queries! (both sql-jdbc and bigquery implement it). Each statement is+ wrapped as `[sql]` because the seam expects `[sql & params]` vectors, not bare strings."+ [driver db stmts]+ (driver/execute-raw-queries! driver (driver/connection-spec driver db) (mapv vector stmts)))++(deftest ^:synchronized fetch-table-indexes-correctness-test+ (testing "fetch-table-indexes reports each driver's popular index kinds in the normalized cross-driver shape"+ ;; The e2e tests above prove indexes Metabase *applies* land on the table; this proves the driver method the+ ;; GET /indexes API consumes reads them back correctly, including catalog shapes the apply path can't produce+ ;; (e.g. a Postgres gin or partial index). Tables are created directly from raw DDL.+ (mt/test-drivers (index-util/index-test-drivers)+ (let [db (mt/db)+ schema (fetch-schema driver/*driver*)+ cases (index-util/fetch-cases driver/*driver*)]+ (is (driver/database-supports? driver/*driver* :index/fetch db)+ "a driver that implements fetch-table-indexes declares :index/fetch")+ (is (some? cases) (index-util/missing-case-message driver/*driver*))+ (doseq [{:keys [label table create expected definition-contains]} cases]+ (testing label+ ;; most sql-jdbc drivers create in the connection default (schema nil, bare name); the rest qualify.+ (let [qualified (if schema (qualify-fetch-table driver/*driver* schema table) table)+ drop-sql (str "DROP TABLE IF EXISTS " qualified)+ creates (cond->> create schema (mapv #(str/replace-first % table qualified)))]+ (run-fetch-ddl! driver/*driver* db [drop-sql])+ (try+ (run-fetch-ddl! driver/*driver* db creates)+ (let [indexes (driver/fetch-table-indexes driver/*driver* db schema table)]+ (is (nil? (mr/explain :metabase.driver/fetch-table-indexes.result indexes))+ "result conforms to ::fetch-table-indexes.result")+ (is (= expected (into #{} (map #(dissoc % :definition)) indexes)))+ ;; `:definition` is dropped from the equality check above (it's driver-verbatim), so a case that hinges+ ;; on it (e.g. Redshift INTERLEAVED vs COMPOUND, identical except for this word) asserts it explicitly.+ (when definition-contains+ (is (some #(str/includes? (:definition %) definition-contains) indexes)+ (str "an index definition contains " (pr-str definition-contains)))))+ (finally+ (run-fetch-ddl! driver/*driver* db [drop-sql]))))))+ (testing "a table that does not exist returns [] rather than throwing"+ (is (= [] (driver/fetch-table-indexes driver/*driver* db schema "mb_fetch_does_not_exist"))))))))++(deftest ^:parallel fetch-table-indexes-unsupported-driver-test+ (testing "a driver that can't introspect indexes doesn't declare :index/fetch"+ (is (not (driver/database-supports? :h2 :index/fetch nil))))+ (testing "fetch-table-indexes has no safe default: its method throws for such a driver"+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"fetch-table-indexes is not implemented for driver :h2"+ (driver/fetch-table-indexes :h2 nil "public" "t")))))++;; The reconcile logic that decides each request's outcome from the warehouse read is unit-tested purely in+;; metabase.indexes.reconcile-test/classify-index-outcomes-test (no warehouse, no stubbing). Here we cover the+;; write-back on real rows, and the whole create-then-verify loop against a live warehouse+;; (managed-indexes-verified-against-warehouse-after-run-test above).+(deftest ^:synchronized apply-index-outcomes!-writes-each-bucket-test+ (testing "each classified outcome is written back: status, error message, last_executed_at, and row removal"+ (mt/with-temp [:model/Transform {tid :id} {:name (mt/random-name)+ :source {:type "query"}+ :source_database_id (mt/id)+ :target {:database (mt/id) :type "table"+ :schema "public" :name "t"}}+ :model/TableIndex {succeeded-id :id} {:transform_id tid :index_name "succeeded_idx"+ :status :running :error_message "stale"+ :structured {:kind :btree :name "succeeded_idx"+ :columns [{:name "a"}]}}+ :model/TableIndex {failed-id :id} {:transform_id tid :index_name "failed_idx"+ :status :running+ :structured {:kind :btree :name "failed_idx"+ :columns [{:name "b"}]}}+ :model/TableIndex {kept-id :id} {:transform_id tid :index_name "kept_idx"+ :status :delete-pending+ :structured {:kind :btree :name "kept_idx"+ :columns [{:name "c"}]}}+ :model/TableIndex {dropped-id :id} {:transform_id tid :index_name "dropped_idx"+ :status :delete-pending+ :structured {:kind :btree :name "dropped_idx"+ :columns [{:name "d"}]}}]+ (#'transforms-base.u/apply-index-outcomes! {:succeeded [{:id succeeded-id}]+ :failed [{:id failed-id}]+ :delete-pending [{:id kept-id}]+ :delete-row [{:id dropped-id}]})+ (testing "succeeded: status set, stale error cleared, execution stamped"+ (is (= :succeeded (t2/select-one-fn :status :model/TableIndex succeeded-id)))+ (is (nil? (t2/select-one-fn :error_message :model/TableIndex succeeded-id)))+ (is (some? (t2/select-one-fn :last_executed_at :model/TableIndex succeeded-id))))+ (testing "failed: status set with the not-found message"+ (is (= :failed (t2/select-one-fn :status :model/TableIndex failed-id)))+ (is (re-find #"not.*found" (t2/select-one-fn :error_message :model/TableIndex failed-id))))+ (testing "a still-present delete-pending row is kept and stamped"+ (is (= :delete-pending (t2/select-one-fn :status :model/TableIndex kept-id)))+ (is (some? (t2/select-one-fn :last_executed_at :model/TableIndex kept-id))))+ (testing "a vanished delete-pending row is removed, freeing its (transform, name) for re-create"+ (is (not (t2/exists? :model/TableIndex :id dropped-id)))+ (is (some? (t2/insert-returning-pk! :model/TableIndex+ {:transform_id tid :index_name "dropped_idx"+ :structured {:kind :btree :name "dropped_idx"+ :columns [{:name "e"}]}})))))))++(deftest ^:synchronized ddl-failure-marks-row-failed-test+ (mt/with-temp [:model/Transform {tid :id} {:name (mt/random-name)+ :source {:type "query"}+ :source_database_id (mt/id)+ :target {:database (mt/id) :type "table" :schema "public" :name "t"}}+ :model/TableIndex {idx-id :id} {:transform_id tid :index_name "boom_idx"+ :structured {:kind :btree :name "boom_idx" :columns [{:name "x"}]}}]+ (let [transform {:id tid :target {:database (mt/id) :schema "public" :name "t"+ :indexes [{:kind :btree :name "boom_idx" :columns [{:name "x"}]}]}}]+ (with-redefs [driver/supported-index-methods (fn [& _] {:btree {:lifecycle :standalone}})+ driver/connection-spec (fn [& _] {})+ driver/compile-create-index (fn [& _] "CREATE INDEX boom_idx ...")+ driver/execute-raw-queries! (fn [& _] (throw (ex-info "ddl boom" {})))]+ (is (thrown? Throwable+ (#'transforms-base.u/apply-standalone-indexes!+ {:engine :postgres :id (mt/id)} (assoc (:target transform) :transform-id tid))))+ (is (= :failed (t2/select-one-fn :status :model/TableIndex idx-id)))+ (is (re-find #"ddl boom" (t2/select-one-fn :error_message :model/TableIndex idx-id)))))))diff --git a/test/metabase/transforms/index_test_util.clj b/test/metabase/transforms/index_test_util.cljnew file mode 100644index 00000000000..cfc7c9b9c1e--- /dev/null+++ b/test/metabase/transforms/index_test_util.clj@@ -0,0 +1,325 @@+(ns metabase.transforms.index-test-util+ "Shared per-driver cases and driver selectors for the transform-index e2e tests, used by both the `:table` suite+ ([[metabase.transforms.index-test]]) and the incremental suite ([[metabase-enterprise.transforms.incremental-test]])."+ (:require+ [clojure.java.jdbc :as jdbc]+ [clojure.set :as set]+ [clojure.string :as str]+ [metabase.driver.sql-jdbc.connection :as sql-jdbc.conn]+ [metabase.test :as mt]))++(set! *warn-on-reflection* true)++(defn- postgres-indexes+ [database schema table]+ (->> (jdbc/query (sql-jdbc.conn/db->pooled-connection-spec database)+ ["SELECT indexname FROM pg_indexes WHERE schemaname = ? AND tablename = ?" schema table])+ (map :indexname)+ set))++(defn- redshift-table-attributes+ "Read a Redshift table's inline attributes back as `{:sortkey {:columns .. :style ..} :distkey <col-or-nil>}`.+ `sortkey` is the column's 1-based position in the key; an interleaved key alternates the sign, so a negative value+ anywhere means interleaved while `abs` still gives the position. `distkey` is true on the single KEY-dist column."+ [database schema table]+ (let [rows (jdbc/query (sql-jdbc.conn/db->pooled-connection-spec database)+ [(str "SELECT column_name, sortkey, distkey FROM svv_redshift_columns "+ "WHERE schema_name = ? AND table_name = ? ORDER BY abs(sortkey)")+ schema table])+ sort-rows (filter (comp (complement zero?) :sortkey) rows)]+ {:sortkey (when (seq sort-rows)+ {:columns (mapv :column_name sort-rows)+ :style (if (some (comp neg? :sortkey) sort-rows) :interleaved :compound)})+ :distkey (:column_name (first (filter :distkey rows)))}))++(defn- mysql-indexes+ [database schema table]+ ;; MySQL has no schemas, so `schema` is nil; fall back to the connection's database.+ (->> (jdbc/query (sql-jdbc.conn/db->pooled-connection-spec database)+ [(str "SELECT DISTINCT index_name FROM information_schema.statistics "+ "WHERE table_schema = COALESCE(?, DATABASE()) AND table_name = ?")+ schema table])+ (map :index_name)+ (remove #{"PRIMARY"})+ set))++(defn- clickhouse-indexes+ [database schema table]+ (let [spec (sql-jdbc.conn/db->pooled-connection-spec database)]+ {:sorting-key (-> (jdbc/query spec ["SELECT sorting_key FROM system.tables WHERE database = ? AND name = ?"+ schema table])+ first :sorting_key)+ :skip-indexes (->> (jdbc/query spec [(str "SELECT name, type, expr, granularity FROM"+ " system.data_skipping_indices WHERE database = ? AND table = ?")+ schema table])+ (mapv #(update % :granularity long)))}))++(defn- bigquery-clustering+ "Clustering columns of `table` in dataset `schema`, in clustering order, read from INFORMATION_SCHEMA. BigQuery has no+ JDBC, so this runs through the QP as a native query rather than `jdbc/query`."+ [database schema table]+ (mapv first+ (mt/rows+ (mt/process-query+ {:database (:id database)+ :type :native+ :native {:query (format (str "SELECT column_name FROM `%s`.INFORMATION_SCHEMA.COLUMNS "+ "WHERE table_name = ? AND clustering_ordinal_position IS NOT NULL "+ "ORDER BY clustering_ordinal_position")+ schema)+ :params [table]}}))))++(defn- snowflake-clustering+ "Read a Snowflake table's clustering key back as an ordered vector of column names, or [] when unclustered.+ `CLUSTERING_KEY` comes back as a string like `LINEAR(category, price)`."+ [database schema table]+ (let [clustering-key (-> (jdbc/query (sql-jdbc.conn/db->pooled-connection-spec database)+ [(str "SELECT clustering_key FROM information_schema.tables "+ "WHERE table_schema = ? AND table_name = ?")+ schema table])+ first :clustering_key)]+ (if-let [s (some-> clustering-key str/trim not-empty)]+ (let [inner (or (second (re-matches #"(?is)\s*LINEAR\s*\((.*)\)\s*" s)) s)]+ (->> (str/split inner #",")+ (map str/trim)+ (map #(str/replace % #"^\"|\"$" ""))+ (remove str/blank?)+ vec))+ [])))++(defn- sqlserver-indexes+ [database schema table]+ (->> (jdbc/query (sql-jdbc.conn/db->pooled-connection-spec database)+ [(str "SELECT i.name AS index_name FROM sys.indexes i "+ "WHERE i.object_id = OBJECT_ID(?) AND i.type IN (1, 2) AND i.name IS NOT NULL")+ (format "[%s].[%s]" schema table)])+ (map :index_name)+ set))++(def driver-cases+ "Driver -> test case: `:indexes` to declare (every method whose column types `transforms_products` can satisfy; the+ rest, e.g. Postgres gin/gist, live in the driver-level and fetch suites), `:physical-indexes` a+ `(fn [database schema table])` reading them back from the system catalog, and `:expected` what it should return.+ Target columns come from the transforms-test `transforms_products` (`category` text, `price` float)."+ {;; Postgres: standalone btree + brin (gin/gist need column types transforms_products doesn't have, so they're+ ;; exercised in the driver-level and fetch suites instead).+ :postgres {:indexes [{:kind :btree :name "by_category" :columns [{:name "category"}]}+ {:kind :brin :name "by_price_brin" :columns [{:name "price"}]}]+ :expected #{"by_category" "by_price_brin"}+ :physical-indexes postgres-indexes}+ ;; Redshift: inline distkey + compound sortkey (the realistic combo). Interleaved is covered in fetch-cases.+ :redshift {:indexes [{:kind :distkey :style :key :columns [{:name "category"}]}+ {:kind :sortkey :style :compound :columns [{:name "price"}]}]+ :expected {:sortkey {:columns ["price"] :style :compound} :distkey "category"}+ :physical-indexes redshift-table-attributes}+ ;; ClickHouse: inline order-by + standalone skip-index in one target. It echoes a single-column key/expr back in+ ;; parens, hence "(category)" and "(price)" (a multi-column key would read as a bare "a, b").+ :clickhouse {:indexes [{:kind :order-by :columns [{:name "category"}]}+ {:kind :skip-index :name "by_price" :type :minmax+ :columns [{:name "price"}] :granularity 1}]+ :expected {:sorting-key "(category)"+ :skip-indexes [{:name "by_price" :type "minmax" :expr "(price)" :granularity 1}]}+ :physical-indexes clickhouse-indexes}+ ;; btree goes on `price` because a TEXT column needs a prefix length to be btree-indexed; fulltext needs text,+ ;; so it goes on `category`.+ :mysql {:indexes [{:kind :btree :name "by_price" :columns [{:name "price"}]}+ {:kind :fulltext :name "ft_category" :columns [{:name "category"}]}]+ :expected #{"by_price" "ft_category"}+ :physical-indexes mysql-indexes}+ ;; BigQuery: inline, unnamed clustering (`CLUSTER BY`), its only index-equivalent.+ :bigquery-cloud-sdk {:indexes [{:kind :clustering :columns [{:name "category"}]}]+ :expected ["category"]+ :physical-indexes bigquery-clustering}+ ;; Snowflake: a single standalone clustering key, reported unnamed, so we read back just the clustered columns.+ :snowflake {:indexes [{:kind :clustering :name "by_category" :columns [{:name "category"}]}]+ :expected ["category"]+ :physical-indexes snowflake-clustering}+ ;; SQL Server: standalone clustered + nonclustered, both on `price` (FLOAT). The CTAS path types the text `category`+ ;; as VARCHAR(1024), but the Python create-table! path makes it NVARCHAR(MAX), which can't be an index key, so only+ ;; `price` is indexable through both transform paths.+ :sqlserver {:indexes [{:kind :clustered :name "by_price" :columns [{:name "price"}]}+ {:kind :nonclustered :name "by_price_nc" :columns [{:name "price"}]}]+ :expected #{"by_price" "by_price_nc"}+ :physical-indexes sqlserver-indexes}})++(defn index-test-drivers+ "Drivers that run transforms and declare any index support."+ []+ (set/union (mt/normal-driver-select {:+features [:transforms/table :index/inline-create]})+ (mt/normal-driver-select {:+features [:transforms/table :index/standalone-create]})))++(defn python-index-test-drivers+ "Index-supporting drivers that also run Python transforms."+ []+ (set/intersection (index-test-drivers) (mt/normal-drivers-with-feature :transforms/python)))++(defn missing-case-message [driver]+ (str driver " declares index support (`:index/inline-create` or `:index/standalone-create`) but has no test "+ "coverage here. Add an entry for it to `driver-cases`."))++(defn bogus-indexes+ "`indexes` rewritten to reference a non-existent column, so applying them must fail."+ [indexes]+ (mapv #(assoc % :columns [{:name "definitely_not_a_real_column"}]) indexes))++(defn- idx+ "A normalized [[metabase.driver/fetch-table-indexes]] entry (sans `:definition`) with defaults, for terse `:expected`."+ [nm kind access-method key-columns & {:keys [unique primary include partial]+ :or {unique false primary false include [] partial nil}}]+ {:name nm :kind kind :access-method access-method :is-unique unique :is-primary primary :is-valid true+ :key-columns key-columns :include-columns include :partial-predicate partial})++(def fetch-cases+ "Driver -> fetch-correctness cases. Each case creates `:table` via the literal `:create` statements (popular index+ kinds, made directly so we cover catalog shapes the apply path never produces, e.g. Postgres gin/partial), and+ `:expected` is the set of normalized [[metabase.driver/fetch-table-indexes]] maps (sans `:definition`) it must return.+ Index models differ, so a case carries however many indexes that driver puts on one table."+ {:postgres+ [{:label "btree, unique, composite, INCLUDE, partial, gin, gist, brin, hash, expression, and the primary key"+ :table "mb_fetch_pg"+ :create ["CREATE TABLE mb_fetch_pg (id INT PRIMARY KEY, user_id INT, email TEXT, a INT, b INT, data JSONB, created_at TIMESTAMP, p POINT)"+ "CREATE INDEX fc_btree ON mb_fetch_pg (user_id)"+ "CREATE UNIQUE INDEX fc_unique ON mb_fetch_pg (email)"+ "CREATE INDEX fc_ab ON mb_fetch_pg (a, b)"+ "CREATE INDEX fc_include ON mb_fetch_pg (a) INCLUDE (b, email)"+ "CREATE INDEX fc_partial ON mb_fetch_pg (user_id) WHERE user_id IS NOT NULL"+ "CREATE INDEX fc_gin ON mb_fetch_pg USING gin (data)"+ "CREATE INDEX fc_gist ON mb_fetch_pg USING gist (p)"+ "CREATE INDEX fc_brin ON mb_fetch_pg USING brin (created_at)"+ "CREATE INDEX fc_hash ON mb_fetch_pg USING hash (email)"+ "CREATE INDEX fc_expr ON mb_fetch_pg (lower(email))"+ "CREATE INDEX fc_mixed ON mb_fetch_pg (user_id, lower(email))"]+ :expected #{(idx "mb_fetch_pg_pkey" :btree "btree" ["id"] :unique true :primary true)+ (idx "fc_btree" :btree "btree" ["user_id"])+ (idx "fc_unique" :btree "btree" ["email"] :unique true)+ (idx "fc_ab" :btree "btree" ["a" "b"])+ (idx "fc_include" :btree "btree" ["a"] :include ["b" "email"])+ (idx "fc_partial" :btree "btree" ["user_id"] :partial "(user_id IS NOT NULL)")+ (idx "fc_gin" :gin "gin" ["data"])+ (idx "fc_gist" :gist "gist" ["p"])+ (idx "fc_brin" :brin "brin" ["created_at"])+ (idx "fc_hash" :hash "hash" ["email"])+ (idx "fc_expr" :btree "btree" ["lower(email)"])+ ;; mixed column + expression: order preserved, the expression carries its text+ (idx "fc_mixed" :btree "btree" ["user_id" "lower(email)"])}}+ {:label "a table with no indexes returns []"+ :table "mb_fetch_pg_empty"+ :create ["CREATE TABLE mb_fetch_pg_empty (a INT, b INT)"]+ :expected #{}}]++ :redshift+ [{:label "the inline compound sortkey, unnamed, reconciled by kind + columns"+ :table "mb_fetch_rs"+ :create ["CREATE TABLE mb_fetch_rs (a INT, b INT) COMPOUND SORTKEY (a, b)"]+ :expected #{(idx nil :sortkey nil ["a" "b"])}}+ {:label "an interleaved sortkey, whose sortkey positions are negative, still orders by abs() position"+ :table "mb_fetch_rs_interleaved"+ :create ["CREATE TABLE mb_fetch_rs_interleaved (a INT, b INT) INTERLEAVED SORTKEY (a, b)"]+ ;; same normalized shape as the compound case, so `:definition` is the only signal it's interleaved.+ ;; interleaved can't use AUTO distribution, so Redshift assigns EVEN; it surfaces as an unmanaged distkey.+ :definition-contains "INTERLEAVED"+ :expected #{(idx nil :sortkey nil ["a" "b"])+ (idx nil :distkey "even" [])}}+ {:label "a KEY distkey alongside a compound sortkey, both reported as unnamed inline rows"+ :table "mb_fetch_rs_dist"+ :create ["CREATE TABLE mb_fetch_rs_dist (a INT, b INT) DISTSTYLE KEY DISTKEY (a) COMPOUND SORTKEY (b)"]+ :expected #{(idx nil :sortkey nil ["b"])+ (idx nil :distkey "key" ["a"])}}+ {:label "an EVEN distribution is reported as a column-less distkey, keyed by style"+ :table "mb_fetch_rs_even"+ :create ["CREATE TABLE mb_fetch_rs_even (a INT, b INT) DISTSTYLE EVEN"]+ :expected #{(idx nil :distkey "even" [])}}+ {:label "an ALL distribution is reported as a column-less distkey, distinct from EVEN"+ :table "mb_fetch_rs_all"+ :create ["CREATE TABLE mb_fetch_rs_all (a INT, b INT) DISTSTYLE ALL"]+ :expected #{(idx nil :distkey "all" [])}}+ {:label "a table with no explicit sortkey or distribution (AUTO) returns []"+ :table "mb_fetch_rs_empty"+ :create ["CREATE TABLE mb_fetch_rs_empty (a INT, b INT)"]+ :expected #{}}]++ :clickhouse+ [{:label "the inline ORDER BY (unnamed) and named skip-indexes (minmax, set)"+ :table "mb_fetch_ch"+ :create ["CREATE TABLE mb_fetch_ch (a Int64, b Int64) ENGINE = MergeTree ORDER BY (a, b)"+ "ALTER TABLE mb_fetch_ch ADD INDEX by_minmax (a) TYPE minmax GRANULARITY 1"+ "ALTER TABLE mb_fetch_ch MATERIALIZE INDEX by_minmax"+ "ALTER TABLE mb_fetch_ch ADD INDEX by_set (b) TYPE set(100) GRANULARITY 1"+ "ALTER TABLE mb_fetch_ch MATERIALIZE INDEX by_set"]+ :expected #{(idx "by_minmax" :skip-index "minmax" ["a"])+ (idx "by_set" :skip-index "set" ["b"])+ (idx nil :order-by nil ["a" "b"])}}+ {:label "expression keys: a wrapped single-expr skip-index and an ORDER BY whose function key has an inner comma"+ :table "mb_fetch_ch_expr"+ :create ["CREATE TABLE mb_fetch_ch_expr (a Int64, b Int64, s String) ENGINE = MergeTree ORDER BY (a, cityHash64(s, b))"+ "ALTER TABLE mb_fetch_ch_expr ADD INDEX ix_lower (lower(s)) TYPE set(100) GRANULARITY 1"+ "ALTER TABLE mb_fetch_ch_expr MATERIALIZE INDEX ix_lower"]+ ;; ClickHouse stores these verbatim: skip-index `expr` = `(lower(s))`, `sorting_key` = `a, cityHash64(s, b)`.+ :expected #{(idx "ix_lower" :skip-index "set" ["lower(s)"])+ (idx nil :order-by nil ["a" "cityHash64(s, b)"])}}+ {:label "an unsorted table returns []"+ :table "mb_fetch_ch_empty"+ :create ["CREATE TABLE mb_fetch_ch_empty (a Int64) ENGINE = MergeTree ORDER BY ()"]+ :expected #{}}]++ :mysql+ [{:label "btree, unique, composite, fulltext, and the auto PRIMARY KEY index"+ :table "mb_fetch_mysql"+ :create ["CREATE TABLE mb_fetch_mysql (id INT PRIMARY KEY, user_id INT, email VARCHAR(255), a INT, b INT, body TEXT)"+ "CREATE INDEX fc_btree ON mb_fetch_mysql (user_id)"+ "CREATE UNIQUE INDEX fc_unique ON mb_fetch_mysql (email)"+ "CREATE INDEX fc_ab ON mb_fetch_mysql (a, b)"+ "CREATE FULLTEXT INDEX fc_ft ON mb_fetch_mysql (body)"]+ ;; the PRIMARY KEY surfaces as a unique btree index named 'PRIMARY'.+ :expected #{(idx "PRIMARY" :btree "btree" ["id"] :unique true :primary true)+ (idx "fc_btree" :btree "btree" ["user_id"])+ (idx "fc_unique" :btree "btree" ["email"] :unique true)+ (idx "fc_ab" :btree "btree" ["a" "b"])+ (idx "fc_ft" :fulltext "fulltext" ["body"])}}+ {:label "a table with no secondary indexes returns just the primary key"+ :table "mb_fetch_mysql_empty"+ :create ["CREATE TABLE mb_fetch_mysql_empty (id INT PRIMARY KEY, a INT)"]+ :expected #{(idx "PRIMARY" :btree "btree" ["id"] :unique true :primary true)}}]++ :bigquery-cloud-sdk+ [{:label "the inline clustering, unnamed, reconciled by kind + columns"+ :table "mb_fetch_bq"+ :create ["CREATE TABLE mb_fetch_bq (category STRING, price FLOAT64) CLUSTER BY category"]+ :expected #{(idx nil :clustering nil ["category"])}}+ {:label "a table with no clustering returns []"+ :table "mb_fetch_bq_empty"+ :create ["CREATE TABLE mb_fetch_bq_empty (a INT64, b INT64)"]+ :expected #{}}]++ ;; columns are quoted so snowflake keeps them lower-case; unquoted, the clustering key reads back as `CATEGORY`.+ :snowflake+ [{:label "the clustering key, unnamed, reconciled by kind + columns"+ :table "mb_fetch_sf"+ :create ["CREATE TABLE mb_fetch_sf (\"category\" TEXT, \"price\" FLOAT) CLUSTER BY (\"category\")"]+ :expected #{(idx nil :clustering nil ["category"])}}+ {:label "a table with no clustering key returns []"+ :table "mb_fetch_sf_empty"+ :create ["CREATE TABLE mb_fetch_sf_empty (\"a\" INT, \"b\" INT)"]+ :expected #{}}]++ :sqlserver+ [{:label "clustered PK, nonclustered, unique, composite, INCLUDE, and a filtered index"+ :table "mb_fetch_ss"+ ;; a named PK constraint so the clustered index has a deterministic name (the default is PK__mb_fetc__<hash>).+ :create ["CREATE TABLE mb_fetch_ss (id INT NOT NULL, user_id INT, email NVARCHAR(255), a INT, b INT, CONSTRAINT pk_fetch_ss PRIMARY KEY (id))"+ "CREATE INDEX fc_nc ON mb_fetch_ss (user_id)"+ "CREATE UNIQUE INDEX fc_unique ON mb_fetch_ss (email)"+ "CREATE INDEX fc_ab ON mb_fetch_ss (a, b)"+ "CREATE INDEX fc_include ON mb_fetch_ss (a) INCLUDE (b, email)"+ "CREATE INDEX fc_filtered ON mb_fetch_ss (user_id) WHERE user_id IS NOT NULL"]+ ;; a PRIMARY KEY surfaces as a unique CLUSTERED index; SQL Server normalizes the filter to bracketed parens.+ :expected #{(idx "pk_fetch_ss" :clustered "clustered" ["id"] :unique true :primary true)+ (idx "fc_nc" :nonclustered "nonclustered" ["user_id"])+ (idx "fc_unique" :nonclustered "nonclustered" ["email"] :unique true)+ (idx "fc_ab" :nonclustered "nonclustered" ["a" "b"])+ (idx "fc_include" :nonclustered "nonclustered" ["a"] :include ["b" "email"])+ (idx "fc_filtered" :nonclustered "nonclustered" ["user_id"] :partial "([user_id] IS NOT NULL)")}}+ {:label "a heap with no indexes returns []"+ :table "mb_fetch_ss_empty"+ :create ["CREATE TABLE mb_fetch_ss_empty (a INT, b INT)"]+ :expected #{}}]})diff --git a/test/metabase/transforms/models/transform_test.clj b/test/metabase/transforms/models/transform_test.cljindex 20a00a1beb1..1f239bd3347 100644--- a/test/metabase/transforms/models/transform_test.clj+++ b/test/metabase/transforms/models/transform_test.clj@@ -5,6 +5,7 @@[metabase.models.interface :as mi][metabase.test :as mt][metabase.transforms-base.query :as transforms-base.query]+ [metabase.transforms.query-test-util :as query-test-util][toucan2.core :as t2]))(deftest source-database-id-set-test@@ -49,6 +50,37 @@;; transform itself still exists(is (some? (t2/select-one :model/Transform (:id transform)))))))+(defn- temp-transform-with-index! [thunk]+ (mt/with-temp [:model/Transform {transform-id :id}+ {:name (mt/random-name)+ :source {:type "query" :query (query-test-util/make-query :source-table "venues")}+ :target {:database (mt/id) :type "table" :schema "public" :name (mt/random-name)}}+ :model/TableIndex {index-id :id}+ {:transform_id transform-id+ :index_name "by_cat"+ :status :succeeded+ :structured {:kind :btree :name "by_cat" :columns [{:name "category"}]}}]+ (thunk transform-id index-id)))++(deftest revalidate-indexes-on-schema-change-test+ (testing "editing the source query (output schema may change) marks the transform's managed indexes for revalidation"+ (temp-transform-with-index!+ (fn [transform-id index-id]+ (t2/update! :model/Transform transform-id+ {:source {:type "query" :query (query-test-util/make-query :source-table "checkins")}})+ (is (= :update-pending (t2/select-one-fn :status :model/TableIndex index-id))))))+ (testing "retargeting to a different table marks the transform's managed indexes for revalidation"+ (temp-transform-with-index!+ (fn [transform-id index-id]+ (t2/update! :model/Transform transform-id+ {:target {:database (mt/id) :type "table" :schema "public" :name (mt/random-name)}})+ (is (= :update-pending (t2/select-one-fn :status :model/TableIndex index-id))))))+ (testing "an unrelated edit (renaming the transform) leaves the indexes alone"+ (temp-transform-with-index!+ (fn [transform-id index-id]+ (t2/update! :model/Transform transform-id {:name "renamed"})+ (is (= :succeeded (t2/select-one-fn :status :model/TableIndex index-id)))))))+(deftest can-read-write-on-orphaned-transform-test(testing "superusers can read/write a transform whose source database has been deleted, data analysts cannot"(mt/with-premium-features #{:transforms-basic :hosting}diff --git a/test/metabase/transforms_rest/api/transform_test.clj b/test/metabase/transforms_rest/api/transform_test.cljindex a2bd6b2a911..7d0230ff9f0 100644--- a/test/metabase/transforms_rest/api/transform_test.clj+++ b/test/metabase/transforms_rest/api/transform_test.clj@@ -635,6 +635,33 @@(is (map? (:creator get-resp)))(is (= lucky-id (get-in get-resp [:creator :id]))))))))))))+(deftest requestable-indexes-field-test+ ;; `#{}` keeps this on the OSS path: query transforms need no token off-cloud, just the `transforms-enabled` setting.+ (mt/with-premium-features #{}+ (mt/with-temporary-raw-setting-values [transforms-enabled "true"]+ (testing "GET /transform/:id surfaces the target driver's requestable index methods"+ (mt/test-drivers (mt/normal-drivers-with-feature :transforms/table)+ (mt/dataset transforms-dataset/transforms-test+ (mt/with-data-analyst-role! (mt/user->id :lucky)+ (mt/with-db-perm-for-group! (perms-group/all-users) (mt/id) :perms/transforms :yes+ (with-transform-cleanup! [table-name "reqidx_products"]+ (let [body {:name "Reqidx Products"+ :source {:type "query" :query (make-query "Gadget")}+ :target {:type "table" :schema (get-test-schema) :name table-name}}+ created (mt/user-http-request :lucky :post 200 "transform" body)+ get-resp (mt/user-http-request :lucky :get 200 (format "transform/%s" (:id created)))+ kinds (set (keys (driver/supported-index-methods driver/*driver* (mt/db))))]+ (testing "the key is always present"+ (is (contains? get-resp :requestable_indexes)))+ (if (seq kinds)+ (testing "each advertised kind appears with a lifecycle and non-empty fields"+ (is (= kinds (set (keys (:requestable_indexes get-resp)))))+ (doseq [[_kind v] (:requestable_indexes get-resp)]+ (is (contains? #{"standalone" "inline"} (:lifecycle v)))+ (is (seq (:fields v)))))+ (testing "drivers with no index support report nil"+ (is (nil? (:requestable_indexes get-resp)))))))))))))))+(deftest source-readable-field-test(mt/with-premium-features #{:transforms-basic :hosting}(testing "Transforms API includes source_readable field"diff --git a/test_resources/serialization_baseline/collections/transforms/daily_order_summary.yaml b/test_resources/serialization_baseline/collections/transforms/daily_order_summary.yamlindex e1fdb371470..d4ac5434eca 100644--- a/test_resources/serialization_baseline/collections/transforms/daily_order_summary.yaml+++ b/test_resources/serialization_baseline/collections/transforms/daily_order_summary.yaml@@ -1,6 +1,7 @@created_at: '2026-04-02T02:59:02.778668Z'creator_id: [email protected]entity_id: 7XqqzlsonSq4KFyOvtrAm+indexes: []name: Daily Order Summarysource:query:diff --git a/test_resources/serialization_baseline/collections/transforms/hourly_product_stats.yaml b/test_resources/serialization_baseline/collections/transforms/hourly_product_stats.yamlindex 3159454566e..042aaa602a3 100644--- a/test_resources/serialization_baseline/collections/transforms/hourly_product_stats.yaml+++ b/test_resources/serialization_baseline/collections/transforms/hourly_product_stats.yaml@@ -1,6 +1,7 @@created_at: '2026-04-02T02:59:02.778668Z'creator_id: [email protected]entity_id: aWiR53tfmHEibiFGuIQeP+indexes: []name: Hourly Product Statssource:query:diff --git a/test_resources/serialization_baseline/collections/transforms/monthly_order_summary.yaml b/test_resources/serialization_baseline/collections/transforms/monthly_order_summary.yamlindex 61987f94a5b..c3164427ab2 100644--- a/test_resources/serialization_baseline/collections/transforms/monthly_order_summary.yaml+++ b/test_resources/serialization_baseline/collections/transforms/monthly_order_summary.yaml@@ -1,6 +1,7 @@created_at: '2026-04-02T02:59:02.778668Z'creator_id: [email protected]entity_id: 1fNzUt_CgppinjPk7pGKH+indexes: []name: Monthly Order Summarysource:query:diff --git a/test_resources/serialization_baseline/collections/transforms/monthly_sales_summary.yaml b/test_resources/serialization_baseline/collections/transforms/monthly_sales_summary.yamlindex 362d9e6134b..20f1c63b9dc 100644--- a/test_resources/serialization_baseline/collections/transforms/monthly_sales_summary.yaml+++ b/test_resources/serialization_baseline/collections/transforms/monthly_sales_summary.yaml@@ -1,6 +1,7 @@created_at: '2026-04-02T02:59:02.778668Z'creator_id: [email protected]entity_id: w7EfUbsxLA7kXBHVXgeaZ+indexes: []name: Monthly Sales Summarysource:query:diff --git a/test_resources/serialization_baseline/collections/transforms/product_revenue_report.yaml b/test_resources/serialization_baseline/collections/transforms/product_revenue_report.yamlindex 4251f83b361..a6c537ed25f 100644--- a/test_resources/serialization_baseline/collections/transforms/product_revenue_report.yaml+++ b/test_resources/serialization_baseline/collections/transforms/product_revenue_report.yaml@@ -1,6 +1,7 @@created_at: '2026-04-02T02:59:02.778668Z'creator_id: [email protected]entity_id: 7JwIkkAG-06-nsl4jzsaq+indexes: []name: Product Revenue Reportsource:query:diff --git a/test_resources/serialization_baseline/collections/transforms/product_summary.yaml b/test_resources/serialization_baseline/collections/transforms/product_summary.yamlindex 13f6c63be95..b70365f248e 100644--- a/test_resources/serialization_baseline/collections/transforms/product_summary.yaml+++ b/test_resources/serialization_baseline/collections/transforms/product_summary.yaml@@ -1,6 +1,7 @@created_at: '2026-04-02T02:59:02.778668Z'creator_id: [email protected]entity_id: rT5vWxYz1aBcDeFgHiJkL+indexes: []name: Product Summarysource:query:diff --git a/test_resources/serialization_baseline/collections/transforms/python_hello_world.yaml b/test_resources/serialization_baseline/collections/transforms/python_hello_world.yamlindex a3e41fb7b2a..834a466680f 100644--- a/test_resources/serialization_baseline/collections/transforms/python_hello_world.yaml+++ b/test_resources/serialization_baseline/collections/transforms/python_hello_world.yaml@@ -1,6 +1,7 @@created_at: '2026-04-02T02:59:02.778668Z'creator_id: [email protected]entity_id: g2cRYwopfoL1BW9Y4n3wb+indexes: []name: Python Hello Worldsource:body: |-