Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

15.2 KB
Raw Blame
(ns metabase-enterprise.transforms-inspector.context
  "Context building for Transform Inspector."
  (:require
   [clojure.string :as str]
   [metabase-enterprise.transforms-inspector.db :as transforms-inspector.db]
   [metabase-enterprise.transforms-inspector.query-analysis :as query-analysis]
   [metabase-enterprise.transforms-inspector.schema :as transforms-inspector.schema]
   [metabase.driver :as driver]
   [metabase.lib.core :as lib]
   [metabase.lib.schema :as lib.schema]
   [metabase.lib.schema.id :as lib.schema.id]
   [metabase.lib.schema.join :as lib.schema.join]
   [metabase.lib.schema.metadata.fingerprint :as lib.schema.metadata.fingerprint]
   [metabase.query-processor.preprocess :as qp.preprocess]
   [metabase.transforms-base.interface :as transforms-base.i]
   [metabase.transforms-base.util :as transforms-base.u]
   [metabase.transforms.schema :as transforms.schema]
   [metabase.util :as u]
   [metabase.util.honey-sql-2 :as h2x]
   [metabase.util.log :as log]
   [metabase.util.malli :as mu]
   [metabase.util.malli.registry :as mr]))

(set! *warn-on-reflection* true)

;;; -------------------------------------------------- Source Extraction --------------------------------------------------

(defn- table-ids->source-info
  "Fetch tables by ID and build source info maps."
  [table-ids]
  (when (seq table-ids)
    (transforms-inspector.db/table-source-rows table-ids)))

(defmulti extract-sources
  "Extract source table information for a transform.
   Returns a seq of maps with :table-id, :table-name, :schema, and :db-id."
  {:arglists '([transform])}
  (fn [transform] (transforms-base.u/transform-source-type (:source transform))))

(defmethod extract-sources :mbql
  [{:keys [source]}]
  (try
    (let [query (-> (:query source)
                    transforms-base.u/massage-sql-query
                    qp.preprocess/preprocess)
          table-ids (lib/all-source-table-ids query)]
      (table-ids->source-info table-ids))
    (catch Exception e
      (log/warnf "Failed to extract sources from MBQL transform: %s" (ex-message e))
      nil)))

(defmethod extract-sources :native
  [{:keys [source] :as transform}]
  (try
    (let [query (-> (:query source)
                    transforms-base.u/massage-sql-query
                    qp.preprocess/preprocess)
          db-id (transforms-base.u/transform-source-database transform)
          driver (keyword (transforms-inspector.db/database-engine db-id))
          deps (driver/native-query-deps driver query)
          table-ids (keep :table deps)]
      (table-ids->source-info table-ids))
    (catch Exception e
      (log/warnf "Failed to extract sources from native transform: %s" (ex-message e))
      nil)))

(defmethod extract-sources :python
  [transform]
  (try
    (let [source-tables (get-in transform [:source :source-tables])
          normalized (transforms-base.u/normalize-source-tables source-tables)
          table-ids (keep :table_id normalized)]
      (table-ids->source-info table-ids))
    (catch Exception e
      (log/warnf "Failed to extract sources from Python transform: %s" (ex-message e))
      nil)))

(defmethod extract-sources :default
  [_transform]
  nil)

;;; -------------------------------------------------- Target Table --------------------------------------------------

(defn- get-target-table
  "Get the target table for a transform. Returns nil if the target doesn't exist or hasn't been materialized yet.
   Provisional tables (inactive, never deactivated) created by the after-insert hook are excluded."
  [{:keys [target] :as transform}]
  (let [db-id (transforms-base.i/target-db-id transform)
        table (transforms-base.u/target-table db-id target)]
    ;; A provisional table for a transform that was never run has active=false and deactivated_at=nil
    ;; Having a table with active=false but a non-nil deactivated_at is a strong indication it ran before.
    ;; That said even an active table is not proof that is has run, as targets may have been swiveled around.
    (when (or (:active table) (:deactivated_at table))
      table)))

;;; -------------------------------------------------- Field Metadata --------------------------------------------------

(mu/defn- get-field-stats :- [:maybe ::transforms-inspector.schema/field-stats]
  "Extract fingerprint stats for a field's fingerprint."
  [fingerprint :- [:maybe ::lib.schema.metadata.fingerprint/fingerprint]]
  (not-empty
   (into {}
         (remove (comp nil? val))
         (cond-> (merge (when-let [dc (get-in fingerprint [:global :distinct-count])]
                          {:distinct_count dc})
                        (select-keys (get-in fingerprint [:type :type/Number]) [:min :max :avg :q1 :q3])
                        (select-keys (get-in fingerprint [:type :type/DateTime]) [:earliest :latest]))
           (some? (get-in fingerprint [:global :nil%]))
           (assoc :nil_percent (get-in fingerprint [:global :nil%]))))))

(mu/defn- collect-field-metadata :- [:sequential ::transforms-inspector.schema/field]
  "Collect metadata for fields in a table."
  [table-id :- ::lib.schema.id/table]
  (let [fields (transforms-inspector.db/active-fields-for-table table-id)]
    (mapv (fn [field]
            (let [stats (get-field-stats (:fingerprint field))]
              (cond-> (select-keys field [:id :name :display_name :base_type :semantic_type])
                stats (assoc :stats stats))))
          fields)))

(def ^:private TableRef
  "A table reference: table, name, schema, and owning database, keyed for lookups."
  [:map {:closed true}
   [:table-id ::lib.schema.id/table]
   [:table-name :string]
   [:schema [:maybe :string]]
   [:db-id ::lib.schema.id/database]])

(mu/defn- build-table-info :- ::transforms-inspector.schema/table
  "Build table info map with fields."
  [{:keys [table-id table-name schema db-id]} :- TableRef]
  (let [fields (collect-field-metadata table-id)]
    {:table_id     table-id
     :table_name   table-name
     :schema       schema
     :db_id        db-id
     :column_count (count fields)
     :fields       fields}))

;;; -------------------------------------------------- Column Matching --------------------------------------------------

(mr/def ::input-column
  "A matched input column reference."
  [:map
   [:source-table-id {:optional true} [:maybe pos-int?]]
   [:source-table-name {:optional true} [:maybe :string]]
   [:name :string]
   [:id {:optional true} [:maybe pos-int?]]])

(mr/def ::column-match
  "A match between output and input columns."
  [:map
   [:output-field ::transforms-inspector.schema/field]
   [:input-columns [:sequential ::input-column]]])

(defn- normalize-column-name
  "Normalize a column name for comparison."
  [name]
  (some-> name u/lower-case-en (str/replace #"[-_]" "")))

(defn- parse-joined-column-name
  "Parse a joined column name like 'Table__field_name'."
  [name]
  (when name
    (when-let [[_ alias field-name] (re-find #"^(.+)__(.+)$" name)]
      {:alias alias :field-name field-name})))

(defn- match-columns-by-name
  "Find columns that relate between input and output tables using name-based matching.
   Used for native queries where we don't have field IDs."
  [sources target join-structure]
  (let [alias->source-table (into {} (map (juxt :alias :source-table) join-structure))
        source-fields (for [{:keys [table_id table_name fields]} sources
                            field fields]
                        (assoc field :source-table-id table_id :source-table-name table_name))]
    (for [target-field (:fields target)
          :let [col-name (:name target-field)
                parsed (parse-joined-column-name col-name)
                matching (if-let [src-table (some-> parsed :alias alias->source-table)]
                           (filter #(and (= (:source-table-id %) src-table)
                                         (= (normalize-column-name (:field-name parsed))
                                            (normalize-column-name (:name %))))
                                   source-fields)
                           (filter #(= (normalize-column-name (or (:field-name parsed) col-name))
                                       (normalize-column-name (:name %)))
                                   source-fields))]
          :when (seq matching)]
      {:output-field  target-field
       :input-columns (mapv #(select-keys % [:source-table-id :source-table-name :name :id])
                            matching)})))

(defn- match-columns-mbql
  "Match columns using lib/returned-columns from the preprocessed MBQL query."
  [preprocessed-query sources target]
  (let [table-id->name (into {} (map (juxt :table_id :table_name) sources))
        target-field-by-name (into {} (map (juxt :name identity) (:fields target)))]
    (for [returned-col (lib/returned-columns preprocessed-query)
          :let [col-name (or (:lib/desired-column-alias returned-col)
                             (:name returned-col))
                target-field (target-field-by-name col-name)
                source-table-id (:table-id returned-col)
                source-table-name (table-id->name source-table-id)]
          :when (and target-field source-table-id)]
      {:output-field  target-field
       :input-columns [{:source-table-id   source-table-id
                        :source-table-name source-table-name
                        :name              (:name returned-col)
                        :id                (:id returned-col)}]})))

(mr/def ::honeysql-value
  "A HoneySQL scalar value from a parsed native join clause: an identifier or a lifted SQL literal."
  [:or h2x/Identifier [:tuple [:= :lift] [:maybe [:or :string number? :boolean]]]])

(mr/def ::honeysql-condition
  "A single HoneySQL boolean condition from a parsed native join clause's ON expression."
  [:or
   [:tuple :keyword [:ref ::honeysql-condition] [:ref ::honeysql-condition]]
   [:tuple :keyword ::honeysql-value ::honeysql-value]])

(mr/def ::honeysql-table-ref
  "A HoneySQL FROM/JOIN table reference: an identifier, optionally aliased."
  [:or [:tuple h2x/Identifier] [:tuple h2x/Identifier :keyword]])

(mr/def ::join-structure-entry
  [:map {:closed true}
   [:strategy       {:optional true} [:maybe [:or :keyword :string]]]
   [:alias          {:optional true} [:maybe :string]]
   [:source-table   {:optional true} [:maybe ::lib.schema.id/table]]
   [:conditions     {:optional true} ::lib.schema.join/conditions]
   [:join-table     {:optional true} ::honeysql-table-ref]
   [:join-condition {:optional true} [:maybe [:or ::honeysql-condition
                                              [:and
                                               [:fn {:error/message "an :and of conditions"} #(= :and (first %))]
                                               [:sequential [:or [:= :and] [:ref ::honeysql-condition]]]]]]]])

(def ^:private QueryInfo
  [:map {:closed true}
   [:preprocessed-query {:optional true} [:maybe ::lib.schema/query]]
   [:driver             {:optional true} [:maybe :keyword]]
   [:from-table-id      {:optional true} [:maybe ::lib.schema.id/table]]
   [:from-table         {:optional true} [:maybe ::honeysql-table-ref]]
   [:join-structure     {:optional true} [:maybe [:sequential ::join-structure-entry]]]
   [:visited-fields     {:optional true} [:maybe [:map {:closed true} [:all {:optional true} [:maybe [:set ::lib.schema.id/field]]]]]]])

(mu/defn- match-columns :- [:maybe [:sequential ::column-match]]
  "Find columns that relate between input and output tables.
   Uses field ID-based matching for MBQL queries (more accurate),
   falls back to name-based matching for native queries."
  [sources :- [:sequential ::transforms-inspector.schema/table]
   target :- ::transforms-inspector.schema/table
   {:keys [preprocessed-query join-structure]} :- [:maybe QueryInfo]]
  (if preprocessed-query
    (match-columns-mbql preprocessed-query sources target)
    (match-columns-by-name sources target join-structure)))

;;; -------------------------------------------------- Context Building --------------------------------------------------

(mr/def ::mbql-join-structure-entry
  "A single join in an MBQL query structure."
  [:map
   [:strategy :keyword]
   [:alias [:maybe :string]]
   [:source-table {:optional true} [:maybe pos-int?]]
   [:conditions :any]])

(mr/def ::native-join-structure-entry
  "A single join in a native query structure (HoneySQL forms)."
  [:map
   [:strategy :keyword]
   [:alias [:maybe :string]]
   [:source-table {:optional true} [:maybe pos-int?]]
   [:join-table :any]
   [:join-condition :any]])

(mr/def ::mbql-context
  "MBQL-specific context."
  [:map
   [:preprocessed-query :map]
   [:join-structure [:maybe [:sequential ::mbql-join-structure-entry]]]])

(mr/def ::native-context
  "Native-specific context."
  [:map
   [:from-table :any]
   [:join-structure [:maybe [:sequential ::native-join-structure-entry]]]])

(mr/def ::context
  "Context built for lens discovery and generation."
  [:map
   [:source-type [:enum :mbql :native :python]]
   [:sources [:sequential ::transforms-inspector.schema/table]]
   [:target [:maybe ::transforms-inspector.schema/table]]
   [:db-id pos-int?]
   [:driver :keyword]
   [:from-table-id [:maybe pos-int?]]
   [:has-joins? :boolean]
   [:mbql-context {:optional true} [:maybe ::mbql-context]]
   [:native-context {:optional true} [:maybe ::native-context]]
   [:visited-fields [:maybe ::transforms-inspector.schema/visited-fields]]
   [:has-column-matches? :boolean]
   [:column-matches [:maybe [:sequential ::column-match]]]])

(mu/defn build-context :- ::context
  "Build context for lens discovery and generation."
  [transform :- ::transforms.schema/transform]
  (let [source-type (transforms-base.u/transform-source-type (:source transform))
        sources-info (mapv build-table-info (extract-sources transform))
        target-table (get-target-table transform)
        target-info (when target-table
                      (build-table-info {:table-id   (:id target-table)
                                         :table-name (:name target-table)
                                         :schema     (:schema target-table)
                                         :db-id      (:db_id target-table)}))
        query-info (query-analysis/analyze-query transform source-type sources-info)
        join-structure (:join-structure query-info)
        column-matches (when (and (seq sources-info) target-info)
                         (seq (match-columns sources-info target-info query-info)))
        db-id (transforms-base.u/transform-source-database transform)]
    (cond-> {:source-type         source-type
             :sources             sources-info
             :target              target-info
             :db-id               db-id
             :driver              (or (:driver query-info)
                                      (keyword (transforms-inspector.db/database-engine db-id)))
             :from-table-id       (:from-table-id query-info)
             :has-joins?          (boolean (seq join-structure))
             :visited-fields      (:visited-fields query-info)
             :has-column-matches? (boolean column-matches)
             :column-matches      column-matches}
      (= source-type :mbql)
      (assoc :mbql-context {:preprocessed-query (:preprocessed-query query-info)
                            :join-structure     join-structure})
      (= source-type :native)
      (assoc :native-context {:from-table     (:from-table query-info)
                              :join-structure join-structure}))))