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
Sync table and column descriptions from BigQuery (#74226)
Alvin Lau12a1dfc779ce
diff --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 f9bf40b43cd..c5e549a94d3 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@@ -306,19 +306,34 @@:where [:and[:= :o.table_name :t.table_name][:= :o.option_name "require_partition_filter"]]}- :require_partition_filter]]+ :require_partition_filter]+ ;; TABLE_OPTIONS stores the description as a GoogleSQL string literal, e.g. `"it's \"x\""`.+ ;; That is not always valid JSON (control characters come out as `\xHH`), but the STRING+ ;; overload of JSON_VALUE decodes BigQuery's escapes, and returns NULL rather than throwing+ ;; on anything it can't parse. (BigQuery rejects `SAFE.JSON_VALUE` on a STRING argument.)+ [{:select [[[:json_value :o.option_value]]]+ :from [[(information-schema-table project-id dataset-id "TABLE_OPTIONS") :o]]+ :where [:and+ [:= :o.table_name :t.table_name]+ [:= :o.option_name "description"]]}+ :description]]:from [[(information-schema-table project-id dataset-id "TABLES") :t]]}))- table-info (fn [dataset-id {table-name :table_name table-type :table_type require-partition-filter :require_partition_filter}]- {:schema dataset-id- :name table-name- :database_require_filter- (boolean (and- ;; Materialized views can be partitioned, and whether the view require a filter or not is based- ;; on the base table it selects from, without parsing the view query we can't find out the base table,- ;; thus we can't know whether the view require a filter or not.- ;; Maybe this is something we can do once we can parse sql- (= "BASE TABLE" table-type)- require-partition-filter))})]+ table-info (fn [dataset-id {table-name :table_name+ table-type :table_type+ require-partition-filter :require_partition_filter+ description :description}]+ (cond-> {:schema dataset-id+ :name table-name+ :database_require_filter+ (boolean (and+ ;; Materialized views can be partitioned, and whether the view require a filter or not is based+ ;; on the base table it selects from, without parsing the view query we can't find out the base table,+ ;; thus we can't know whether the view require a filter or not.+ ;; Maybe this is something we can do once we can parse sql+ (= "BASE TABLE" table-type)+ require-partition-filter))}+ (not (str/blank? description))+ (assoc :description description)))](->> (list-datasets details :logging-schema-exclusions? true)(eduction (mapcat (fn [dataset-id] (eduction (map #(table-info dataset-id %)) (query-dataset dataset-id))))))))@@ -416,16 +431,17 @@(defn- column-field-path-row->nested-col"Map a `COLUMN_FIELD_PATHS` row to a nested-column map (later keyed by its `:nfc-path`), or `nil` for a top-level(non-nested) field."- [dataset-id {data-type :data_type field-path-str :field_path table-name :table_name}]+ [dataset-id {data-type :data_type field-path-str :field_path table-name :table_name description :description}](let [field-path (str/split field-path-str #"\.")[database-type base-type] (raw-type->database+base-type data-type)](when-let [nfc-path (perf/not-empty (pop field-path))]- {:name (peek field-path)- :table-name table-name- :table-schema dataset-id- :database-type database-type- :base-type base-type- :nfc-path nfc-path})))+ (cond-> {:name (peek field-path)+ :table-name table-name+ :table-schema dataset-id+ :database-type database-type+ :base-type base-type+ :nfc-path nfc-path}+ (not (str/blank? description)) (assoc :field-comment description)))))(defn- nested-rows->table-lookup"Build a single table's nested-column lookup `{nfc-path [cols]}` from that table's `COLUMN_FIELD_PATHS` rows.@@ -455,18 +471,20 @@(fn [{column-name :column_namedata-type :data_typedatabase-position :ordinal_position- partitioned? :partitioned}]+ partitioned? :partitioned+ description :description}](let [database-position (or (some-> database-position dec) max-position)[database-type base-type] (raw-type->database+base-type data-type)](cond-> [(maybe-add-nested-fieldsnested-column-lookup- {:name column-name- :table-name table-name- :table-schema dataset-id- :database-type database-type- :base-type base-type- :database-partitioned partitioned?- :database-position database-position}+ (cond-> {:name column-name+ :table-name table-name+ :table-schema dataset-id+ :database-type database-type+ :base-type base-type+ :database-partitioned partitioned?+ :database-position database-position}+ (not (str/blank? description)) (assoc :field-comment description))nildatabase-position)];; _PARTITIONDATE does not appear so add it in if we see _PARTITIONTIME@@ -482,9 +500,10 @@(defn- describe-dataset-table"Build the field descriptions for a single table from its joined `COLUMNS`/`COLUMN_FIELD_PATHS` rows (see- [[describe-dataset-fields-reducible]]). Each top-level column appears once per nested leaf, or once with a `nil`- `:field_path` when it has none, so de-dup the columns by `:column_name` and build the nested-field lookup from- the rows that carry a `:field_path` (whose leaf type is in `:nested_data_type`)."+ [[describe-dataset-fields-reducible]]). Each top-level column appears once per field path -- its own entry+ (`:field_path` = `:column_name`) plus one per nested field -- or once with a `nil` `:field_path` when it has none, so+ de-dup the columns by `:column_name`, take each column's `:description` from its own entry, and build the+ nested-field lookup from the rows that carry a `:field_path` (whose type is in `:nested_data_type`)."[dataset-id table-rows](let [table-name (:table_name (first table-rows))nested-lookup (nested-rows->table-lookup@@ -492,10 +511,19 @@(eduction (filter :field_path)(map #(assoc % :data_type (:nested_data_type %)))table-rows))+ ;; the row kept by the de-dup below may belong to a nested field, so look up the column's own description+ descriptions (into {}+ (keep (fn [{column-name :column_name field-path :field_path description :description}]+ (when (= column-name field-path)+ [column-name description])))+ table-rows);; de-dup by `:column_name`, not `:ordinal_position`: BigQuery reports a NULL `ordinal_position` for;; pseudo-columns (e.g. `_PARTITIONTIME`), and a table can carry more than one, so keying on position would;; collapse distinct columns into one.- columns (into [] (m/distinct-by :column_name) table-rows)]+ columns (into []+ (comp (m/distinct-by :column_name)+ (map #(assoc % :description (get descriptions (:column_name %)))))+ table-rows)](sort-by (juxt :table-name :database-position :name)(describe-dataset-rows nested-lookup dataset-id table-name columns))))@@ -511,9 +539,10 @@(defn- describe-dataset-fields-reducible"Reducibly describe the fields (including nested STRUCT fields) of `table-names` within `dataset-id`.- Runs a single `INFORMATION_SCHEMA` query that LEFT JOINs `COLUMNS` (top-level fields) to `COLUMN_FIELD_PATHS` (nested- STRUCT leaves) on `(table_name, column_name)`. A non-nested column yields one row with a `nil` `:field_path`; a STRUCT- column yields one row per nested leaf. Ordering by `table_name` keeps each table's rows contiguous, so we consume the+ Runs a single `INFORMATION_SCHEMA` query that LEFT JOINs `COLUMNS` (top-level fields) to `COLUMN_FIELD_PATHS` (every+ field path, which is also where descriptions live) on `(table_name, column_name)`. A column yields one row for its own+ entry plus one per nested STRUCT field, or a single row with a `nil` `:field_path` when it has no entry (e.g.+ pseudo-columns). Ordering by `table_name` keeps each table's rows contiguous, so we consume thelive result with a `partition-by` transducer and reconstruct one table at a time (see [[describe-dataset-table]]) --never realizing more than a single table's rows. This matters for wide and/or deeply-nested datasets (e.g.GA4/Firebase exports, or schemas with thousands of columns per table) where realizing a whole batch's columns would@@ -532,15 +561,15 @@[:c.ordinal_position :ordinal_position][[:= :c.is_partitioning_column "YES"] :partitioned][[:substr :p.data_type 1 max-data-type-length] :nested_data_type]- [:p.field_path :field_path]]+ [:p.field_path :field_path]+ ;; `COLUMNS` has no description column, so a top-level column's comes from+ ;; its own `COLUMN_FIELD_PATHS` entry (field_path = column_name)+ [:p.description :description]]:from [[(information-schema-table project-id dataset-id "COLUMNS") :c]]:left-join [[(information-schema-table project-id dataset-id "COLUMN_FIELD_PATHS") :p][:and[:= :c.table_name :p.table_name]- [:= :c.column_name :p.column_name]- ;; only nested leaves -- the top-level entry (field_path = column_name) has- ;; no `.` and is described from the `COLUMNS` side- [:> [:strpos :p.field_path "."] 0]]]+ [:= :c.column_name :p.column_name]]]:where [:in :c.table_name table-names]:order-by [:c.table_name]})(catch Throwable ediff --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 5da320fa1a4..ca4cb53faea 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@@ -501,6 +501,27 @@;; the "YES" between the pairs is the is_partitioning_column comparison(is (= [1 200 "YES" 1 200] (take 5 @captured-params)))))))))+(deftest ^:parallel describe-dataset-table-descriptions-test+ (mt/test-driver :bigquery-cloud-sdk+ (testing "a column's description comes from its own COLUMN_FIELD_PATHS entry, even when a row for one of its nested+ fields comes first (#18872)"+ (let [row {:table_name "t" :column_name "r" :data_type "STRUCT<a STRING>" :ordinal_position 1}+ [record scalar] (#'bigquery/describe-dataset-table+ "ds"+ [(assoc row :nested_data_type "STRING" :field_path "r.a" :description "nested description")+ (assoc row :nested_data_type "STRUCT<a STRING>" :field_path "r" :description "record description")+ {:table_name "t"+ :column_name "s"+ :data_type "STRING"+ :ordinal_position 2+ :nested_data_type "STRING"+ :field_path "s"+ :description nil}])]+ (is (= "record description" (:field-comment record)))+ (is (= ["nested description"] (map :field-comment (:nested-fields record))))+ (is (= "s" (:name scalar)))+ (is (not (contains? scalar :field-comment)))))))+(def ^:private native-dataset(tx/native-dataset-definition"native-dataset"@@ -655,6 +676,92 @@{:source-table (mt/id view-name):order-by [[:asc (mt/id view-name :id)]]})))))))))+;;; +----------------------------------------------------------------------------------------------------------------++;;; | Description sync (#18872) |+;;; +----------------------------------------------------------------------------------------------------------------+++(def ^:private escaped-description+ "TABLE_OPTIONS stores table descriptions as GoogleSQL string literals: quotes and backslashes are escaped, control+ characters come out as `\\xHH` (not valid JSON), and non-ASCII is kept verbatim. Exercise all of those."+ "it's a \"quoted\" C:\\temp path,\ttab, new\nline, bell\u0007, 學生, 🚀")++(def ^:private descriptions-dataset+ "Dataset for the #18872 sync test: table-level, top-level column, RECORD column and nested subfield descriptions."+ (tx/map->DatabaseDefinition+ {:database-name "descriptions-dataset"+ :options {}+ :table-definitions+ [(tx/map->TableDefinition+ {:table-name "described_table"+ :table-comment "Top-level table description for sync test (#18872)."+ :rows []+ :field-definitions+ [(tx/map->FieldDefinition+ {:field-name "described_text"+ :base-type :type/Text+ :field-comment "Top-level column description for sync test (#18872)."})+ (tx/map->FieldDefinition+ {:field-name "undescribed_text"+ :base-type :type/Text})+ (tx/map->FieldDefinition+ {:field-name "described_record"+ :base-type :type/Dictionary+ :field-comment "Record column description for sync test (#18872)."+ :nested-fields [(tx/map->FieldDefinition+ {:field-name "described_nested"+ :base-type :type/Text+ :field-comment "Nested column description for sync test (#18872)."})+ (tx/map->FieldDefinition+ {:field-name "undescribed_nested"+ :base-type :type/Text})]})]})+ (tx/map->TableDefinition+ {:table-name "escaped_table"+ :table-comment escaped-description+ :rows []+ :field-definitions [(tx/map->FieldDefinition+ {:field-name "escaped_text"+ :base-type :type/Text+ :field-comment escaped-description})]})]}))++(deftest sync-descriptions-test+ (testing "BigQuery driver propagates table and column descriptions during sync (#18872)"+ (mt/test-driver+ :bigquery-cloud-sdk+ (mt/dataset+ descriptions-dataset+ (testing "describe-database carries table-level descriptions"+ (let [descriptions (into {}+ (map (juxt :name :description))+ (:tables (driver/describe-database :bigquery-cloud-sdk (mt/db))))]+ (is (= "Top-level table description for sync test (#18872)."+ (descriptions "described_table")))+ (testing "including the escape sequences BigQuery writes into TABLE_OPTIONS"+ (is (= escaped-description (descriptions "escaped_table"))))))+ (testing "describe-fields carries column descriptions"+ (let [fields (into [] (driver/describe-fields :bigquery-cloud-sdk (mt/db)+ {:table-names ["described_table" "escaped_table"]+ :schema-names [(get-test-data-name)]}))+ by-name (into {} (map (juxt :name identity)) fields)]+ (is (= "Top-level column description for sync test (#18872)."+ (:field-comment (by-name "described_text"))))+ (is (= escaped-description+ (:field-comment (by-name "escaped_text"))))+ (testing "columns without a BigQuery description are emitted without :field-comment"+ (is (not (contains? (by-name "undescribed_text") :field-comment))))+ (testing "RECORD columns and their subfields carry their own descriptions"+ (let [record (by-name "described_record")+ nested-by-name (into {} (map (juxt :name identity)) (:nested-fields record))]+ (is (= "Record column description for sync test (#18872)."+ (:field-comment record)))+ (is (= "Nested column description for sync test (#18872)."+ (:field-comment (nested-by-name "described_nested"))))+ (is (not (contains? (nested-by-name "undescribed_nested") :field-comment)))))))+ (testing "sync writes the descriptions to the app DB"+ (is (= "Top-level table description for sync test (#18872)."+ (t2/select-one-fn :description :model/Table :id (mt/id :described_table))))+ (is (= "Top-level column description for sync test (#18872)."+ (t2/select-one-fn :description :model/Field :id (mt/id :described_table :described_text)))))))))+(deftest sync-materialized-view-test(mt/test-driver:bigquery-cloud-sdkdiff --git a/modules/drivers/bigquery-cloud-sdk/test/metabase/test/data/bigquery_cloud_sdk.clj b/modules/drivers/bigquery-cloud-sdk/test/metabase/test/data/bigquery_cloud_sdk.cljindex e0c8464986c..8c70972f298 100644--- a/modules/drivers/bigquery-cloud-sdk/test/metabase/test/data/bigquery_cloud_sdk.clj+++ b/modules/drivers/bigquery-cloud-sdk/test/metabase/test/data/bigquery_cloud_sdk.clj@@ -201,7 +201,7 @@(defn- field-definitions->Fields [field-definitions](into[]- (map (fn [{:keys [field-name base-type nested-fields collection-type]}]+ (map (fn [{:keys [field-name base-type nested-fields collection-type field-comment]}](let [field-type (or (some-> collection-type base-type->bigquery-type)(base-type->bigquery-type base-type)(let [message (format "Don't know what BigQuery type to use for base type: %s" base-type)]@@ -213,23 +213,27 @@^"[Lcom.google.cloud.bigquery.Field;" (into-array Field (field-definitions->Fields nested-fields)))](cond-> builder(isa? :type/Collection base-type) (.setMode Field$Mode/REPEATED)+ (not (str/blank? field-comment)) (.setDescription ^String field-comment):always (.build)))))field-definitions))(defn- create-table*!- [dataset-id table-id field-definitions]- (let [tbl-id (TableId/of dataset-id table-id)- schema (Schema/of (u/varargs Field (field-definitions->Fields (cons {:field-name "id"- :base-type :type/Integer}- field-definitions))))- tbl (TableInfo/of tbl-id (StandardTableDefinition/of schema))]+ [dataset-id table-id field-definitions table-comment]+ (let [tbl-id (TableId/of dataset-id table-id)+ schema (Schema/of (u/varargs Field (field-definitions->Fields (cons {:field-name "id"+ :base-type :type/Integer}+ field-definitions))))+ ^TableInfo tbl (cond-> (TableInfo/newBuilder tbl-id (StandardTableDefinition/of schema))+ (not (str/blank? table-comment)) (.setDescription ^String table-comment)+ :always (.build))](.create (bigquery) tbl (u/varargs BigQuery$TableOption))))(mu/defn- create-table![^String dataset-id :- ::lib.schema.common/non-blank-string^String table-id :- ::lib.schema.common/non-blank-string- field-definitions :- [:sequential (ms/InstanceOfClass metabase.test.data.interface.FieldDefinition)]]- (create-table*! dataset-id table-id field-definitions)+ field-definitions :- [:sequential (ms/InstanceOfClass metabase.test.data.interface.FieldDefinition)]+ table-comment :- [:maybe ::lib.schema.common/non-blank-string]]+ (create-table*! dataset-id table-id field-definitions table-comment);; now verify that the Table was created(.listTables (bigquery) dataset-id (u/varargs BigQuery$TableListOption))(log/info (u/format-color 'blue "Created BigQuery table `%s.%s.%s`." (project-id) dataset-id table-id)))@@ -340,9 +344,9 @@(assoc (zipmap field-names row):id (inc i)))))-(defn- load-tabledef! [dataset-id {:keys [table-name field-definitions], :as tabledef}]+(defn- load-tabledef! [dataset-id {:keys [table-name field-definitions table-comment], :as tabledef}](let [table-name (normalize-name table-name)]- (create-table! dataset-id table-name field-definitions)+ (create-table! dataset-id table-name field-definitions table-comment)(when (seq (:rows tabledef));; retry the `insert-data!` step up to 5 times because it seems to fail silently a lot. Since each row is given a;; unique key it shouldn't result in duplicates.