Skip to content

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

Use macaw options, add parsed-query wrapped (#68466)

lbrdnk16042f45c72c
diff --git a/.clj-kondo/config.edn b/.clj-kondo/config.edn
index 67d94215356..b56f31f573a 100644
--- a/.clj-kondo/config.edn
+++ b/.clj-kondo/config.edn
@@ -65,6 +65,7 @@
:metabase/missing-test-expr-requires-in-cljs {:level :warning}
:metabase/modules {:level :warning} ; more config in `.clj-kondo/config/modules/config.edn`
:metabase/namespace-name {:level :warning}
+ :metabase/no-jsqlparser-imports {:level :warning}
:metabase/require-shape-checker {:level :warning}
:metabase/test-helpers-use-non-thread-safe-functions {:level :warning} ; more config in `.clj-kondo/config/test-helpers/config.edn`
:metabase/tests-must-live-in-known-modules {:level :warning}
@@ -299,7 +300,8 @@
metabase-enterprise.transforms.interface/execute! {:message "Use metabase-enterprise.transforms.execute/execute! instead of metabase-enterprise.transforms.interface/execute!"}
next.jdbc/active-tx? {:message "Use metabase.app-db.core/in-transaction? to see if we are in a transaction"}
toucan2.core/debug {:message "Don't commit code using t2/debug"}
- toucan2.tools.debug/debug {:message "Don't commit code using t2/debug"}}
+ toucan2.tools.debug/debug {:message "Don't commit code using t2/debug"}
+ macaw.core/parsed-query {:message "Use metabase.driver.util/parsed-query instead of macaw.core/parsed-query"}}
:discouraged-namespace
{camel-snake-kebab.core {:message "CSK is not Turkish-safe, use the versions in metabase.util instead."}
diff --git a/.clj-kondo/src/hooks/clojure/core/ns.clj b/.clj-kondo/src/hooks/clojure/core/ns.clj
index 395b7e60f59..ef54cf0fb9a 100644
--- a/.clj-kondo/src/hooks/clojure/core/ns.clj
+++ b/.clj-kondo/src/hooks/clojure/core/ns.clj
@@ -99,12 +99,48 @@
:message "Metabase namespaces should have the form metabase[-enterprise].<module>.* [:metabase/namespace-name]"
:type :metabase/namespace-name)))))))
+(defn- ns-form-node->import-node [ns-form-node]
+ (some (fn [node]
+ (when (and (hooks/list-node? node)
+ (let [first-child (first (:children node))]
+ (and (hooks/keyword-node? first-child)
+ (= (hooks/sexpr first-child) :import))))
+ node))
+ (:children ns-form-node)))
+
+(defn- jsqlparser-import?
+ "Check if a symbol or string represents a jsqlparser import."
+ [s]
+ (str/starts-with? (str s) "net.sf.jsqlparser"))
+
+(defn- lint-jsqlparser-imports [ns-form-node]
+ (when-let [import-node (ns-form-node->import-node ns-form-node)]
+ (doseq [node (rest (:children import-node))
+ :when (not (contains? (hooks.common/ignored-linters node) :metabase/no-jsqlparser-imports))]
+ (cond
+ ;; Handle (net.sf.jsqlparser.foo Bar Baz) form
+ (hooks/list-node? node)
+ (let [package-node (first (:children node))
+ package-name (when package-node (str (hooks/sexpr package-node)))]
+ (when (jsqlparser-import? package-name)
+ (hooks/reg-finding! (assoc (meta node)
+ :message "Don't import net.sf.jsqlparser classes directly. This code should be agnostic to the parsing library. [:metabase/no-jsqlparser-imports]"
+ :type :metabase/no-jsqlparser-imports))))
+
+ ;; Handle net.sf.jsqlparser.foo.Bar form (single class import)
+ (hooks/token-node? node)
+ (when (jsqlparser-import? (hooks/sexpr node))
+ (hooks/reg-finding! (assoc (meta node)
+ :message "Don't import net.sf.jsqlparser classes directly. This code should be agnostic to the parsing library. [:metabase/no-jsqlparser-imports]"
+ :type :metabase/no-jsqlparser-imports)))))))
+
(defn lint-ns [x]
(doto (:node x)
lint-require-shapes
lint-requires-on-new-lines
(lint-modules (modules/config x))
- lint-namespace-name)
+ lint-namespace-name
+ lint-jsqlparser-imports)
x)
(comment
diff --git a/deps.edn b/deps.edn
index 744bdf52c4e..844d3febde8 100644
--- a/deps.edn
+++ b/deps.edn
@@ -84,7 +84,7 @@
io.github.eerohele/pp {#_#_:git/tag "2024-11-13.77" ; super fast pretty-printing library
:git/sha "ffc4edc482c057cd9412c62f018a41e9140c618b"
:git/url "https://github.com/eerohele/pp"}
- io.github.metabase/macaw {:mvn/version "0.2.30"} ; Parse native SQL queries
+ io.github.metabase/macaw {:mvn/version "0.2.33"} ; Parse native SQL queries
io.netty/netty-codec-http {:mvn/version "4.2.9.Final"} ; override of transitive dep from aws s3
io.prometheus/simpleclient_hotspot {:mvn/version "0.16.0"} ; prometheus jvm collector
junegunn/grouper {:mvn/version "0.1.1"} ; Batch processing helper
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/query_analyzer.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/query_analyzer.clj
index ee6c4128590..a15066a128d 100644
--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/query_analyzer.clj
+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/query_analyzer.clj
@@ -7,7 +7,6 @@
(:require
[clojure.string :as str]
[macaw.core :as macaw]
- [metabase-enterprise.metabot-v3.query-analyzer.impl :as nqa.impl]
[metabase-enterprise.metabot-v3.query-analyzer.parameter-substitution :as nqa.sub]
[metabase.driver :as driver]
[metabase.driver.util :as driver.u]
@@ -117,7 +116,7 @@
to return tables that are in the query."
[driver query & {:keys [mode] :or {mode :compound-select}}]
(let [db-id (:database query)
- macaw-opts (nqa.impl/macaw-options driver)
+ macaw-opts (driver.u/macaw-options driver)
table-opts (assoc macaw-opts :mode mode)
sql-string (:query (nqa.sub/replace-tags query))
result (macaw/query->tables sql-string table-opts)]
@@ -141,7 +140,7 @@
(defmethod tables-for-native* :sql
[driver query opts]
(if (or (:all-drivers-trusted? opts)
- (nqa.impl/trusted-for-table-permissions? driver))
+ (driver.u/trusted-for-table-permissions? driver))
(tables-via-macaw driver query opts)
{:error :query-analysis.error/driver-not-supported}))
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/query_analyzer/impl.cljc b/enterprise/backend/src/metabase_enterprise/metabot_v3/query_analyzer/impl.cljc
deleted file mode 100644
index 34a345c482e..00000000000
--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/query_analyzer/impl.cljc
+++ /dev/null
@@ -1,66 +0,0 @@
-(ns metabase-enterprise.metabot-v3.query-analyzer.impl
- (:require
- [metabase.driver :as driver]))
-
-;; NOTE: In the future we should replace [[considered-drivers]] and [[macaw-options]] with (a) driver method(s),
-;; but given that the interface with Macaw is still in a state of flux, and how simple the current configuration is,
-;; we defer extending the public interface and define the logic locally instead. Macaw itself is not battle tested
-;; outside this same narrow range of databases in any case.
-
-(def ^:private considered-drivers
- "Since we are unable to ask basic questions of the driver hierarchy outside of that module, we need to explicitly
- mention all sub-types. This is probably not a bad thing."
- #{:h2 :mysql :postgres :redshift :sqlite :sqlserver})
-
-;; At some point, we may want a way for 3rd party drivers to opt in, but a public API deserves some hammock time.
-;; Using a separate list to the above, as we may want this to be more restrictive.
-(def trusted-for-table-permissions?
- "Do we trust that Macaw will not give us false negatives for tables referenced by a given query?"
- #{:h2 :mysql :postgres})
-
-(defn macaw-options
- "Generate the options expected by Macaw based on the nature of the given driver."
- [driver]
- ;; If this isn't a driver we've considered, fallback to Macaw's conservative defaults.
- (when (contains? considered-drivers driver)
- ;; According to the SQL-92 specification, non-quoted identifiers should be case-insensitive, and the majority of
- ;; engines are implemented this way.
- ;;
- ;; In practice there are exceptions, notably MySQL and SQL Server, where case sensitivity is a property of the
- ;; underlying resource referenced by the identifier, and the case-sensitivity does not depend on whether the
- ;; reference is quoted.
- ;;
- ;; For MySQL the case sensitivity of databases and tables depends on both the underlying file system, and a system
- ;; variable used to initialize the database. For SQL Server it depends on the collation settings of the collection
- ;; where the corresponding schema element is defined.
- ;;
- ;; For MySQL, columns and aliases can never be case-sensitive, and for SQL Server the default collation is case-
- ;; insensitive too, so it makes sense to just treat all databases as case-insensitive as a whole.
- ;;
- ;; In future, Macaw may support discriminating on the identifier type, in which case we could be more precise for
- ;; these databases. Being 100% correct would require querying system variables and schema configuration however,
- ;; which is likely a step too far in complexity.
- ;;
- ;; Currently, we go with :agnostic, as it is the most relaxed semantics (the case of both the identifiers and the
- ;; underlying schema is totally ignored, and correspondence is non-deterministic), but Macaw supports more nuanced
- ;; :lower and :upper configuration values which coerce the query identifiers to a given case then do an exact
- ;; comparison with the schema.
- {:case-insensitive :agnostic
- ;; For both MySQL and SQL Server, whether identifiers are case-sensitive depends on database configuration only,
- ;; and quoting has no effect on this, so we disable this option for consistency with `:case-insensitive`.
- :quotes-preserve-case? (not (contains? #{:mysql :sqlserver} driver))
- :features {:postgres-syntax (isa? driver/hierarchy driver :postgres)
- :square-bracket-quotes (= :sqlserver driver)
- :unsupported-statements false
- :backslash-escape-char true
- ;; This will slow things down, but until we measure the difference, opt for correctness.
- :complex-parsing true}
- ;; 10 seconds
- :timeout 10000
- ;; There is no plan to be exhaustive yet.
- ;; Note that while an allowed list would be more conservative, at the time of writing only 2 of the bundled
- ;; drivers use FINAL as a reserved word, and mentioning them all would be prohibitive.
- ;; In the future, we will use multimethods to define this explicitly per driver, or even discover it automatically
- ;; through the JDBC connection, where possible.
- :non-reserved-words (vec (remove nil? [(when-not (contains? #{:snowflake :oracle} driver)
- :final)]))}))
diff --git a/enterprise/backend/src/metabase_enterprise/transforms/api.clj b/enterprise/backend/src/metabase_enterprise/transforms/api.clj
index cd71361aa82..95f4757c173 100644
--- a/enterprise/backend/src/metabase_enterprise/transforms/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/transforms/api.clj
@@ -1,6 +1,5 @@
(ns metabase-enterprise.transforms.api
(:require
- [macaw.core :as macaw]
[metabase-enterprise.transforms.api.transform-job]
[metabase-enterprise.transforms.api.transform-tag]
[metabase-enterprise.transforms.canceling :as transforms.canceling]
@@ -32,8 +31,10 @@
[metabase.util.malli.schema :as ms]
[ring.util.response :as response]
[toucan2.core :as t2])
+ ;; TODO (Chris 2026-01-22) -- Remove jsqlparser imports/typehints to be SQL parser-agnostic
(:import
(java.sql PreparedStatement)
+ ^{:clj-kondo/ignore [:metabase/no-jsqlparser-imports]}
(net.sf.jsqlparser.statement.select PlainSelect)))
(comment metabase-enterprise.transforms.api.transform-job/keep-me
@@ -418,11 +419,15 @@
:run_id run-id})
(assoc :status 202)))))
+;; TODO (Chris 2026-01-22) -- Remove jsqlparser typehints to be SQL parser-agnostic
(defn- simple-native-query?
"Checks if a native SQL query string is simple enough for automatic checkpoint insertion."
[sql-string]
(try
- (let [^PlainSelect parsed (macaw/parsed-query sql-string)]
+ ;; BEWARE: The API endpoint (caller) does not have info on database engine this query should run on. Hence
+ ;; there's no way of providing appropriate [[metabase.driver.util/macaw-options]]. `nil` is best-effort
+ ;; adding at least default :non-resserved-words.
+ (let [^PlainSelect parsed (driver.u/parsed-query sql-string nil)]
(cond
(not (instance? PlainSelect parsed))
{:is_simple false
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.clj
index 0306ae31316..c505521d880 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
@@ -19,6 +19,7 @@
[metabase.driver.sql.query-processor :as sql.qp]
[metabase.driver.sql.util :as sql.u]
[metabase.driver.sync :as driver.s]
+ [metabase.driver.util :as driver.u]
[metabase.util :as u]
[metabase.util.date-2 :as u.date]
[metabase.util.i18n :refer [tru]]
@@ -1028,7 +1029,7 @@
(keep #(driver.sql/find-table-or-transform driver db-tables transforms %)))
(-> query
driver-api/raw-native-query
- macaw/parsed-query
+ (driver.u/parsed-query driver)
macaw/query->components
:tables))))
diff --git a/modules/drivers/clickhouse/test/metabase/driver/clickhouse_test.clj b/modules/drivers/clickhouse/test/metabase/driver/clickhouse_test.clj
index 79ec7fe031d..6ad61563468 100644
--- a/modules/drivers/clickhouse/test/metabase/driver/clickhouse_test.clj
+++ b/modules/drivers/clickhouse/test/metabase/driver/clickhouse_test.clj
@@ -414,3 +414,24 @@
(lib/filter (lib/= val-col "abc"))
(qp/process-query)
(mt/rows))))))))))
+
+;; TODO (lbrdnk 2026-01-23): Excplicit exceptions from [[metabase.driver.util/parsed-query]] are shutdown
+;; at the moment to avoid potential log flooding. We should revisit this during further
+;; parsing work.
+#_(deftest ^:parallel parse-final-identifier-test
+ (mt/test-driver
+ :clickhouse
+ (testing "`final` is not allowed as identifier on Clickhouse, parsing fails with an exception"
+ (mt/with-temp [:model/Database db {:engine "clickhouse"
+ :name "final"
+ :initial_sync_status "complete"}]
+ (mt/with-db
+ db
+ (let [mp (mt/metadata-provider)
+ broken-query (lib/native-query mp "select final from final")]
+ (is (thrown-with-msg? Exception #"SQL parsing failed."
+ (driver/native-query-deps :clickhouse broken-query)))
+ (is (thrown-with-msg? Exception #"SQL parsing failed."
+ (driver/native-result-metadata :clickhouse broken-query)))
+ (is (thrown-with-msg? Exception #"SQL parsing failed."
+ (driver/validate-native-query-fields :clickhouse broken-query)))))))))
diff --git a/modules/drivers/sqlserver/src/metabase/driver/sqlserver.clj b/modules/drivers/sqlserver/src/metabase/driver/sqlserver.clj
index a4fc7e57ccb..49d94433fc3 100644
--- a/modules/drivers/sqlserver/src/metabase/driver/sqlserver.clj
+++ b/modules/drivers/sqlserver/src/metabase/driver/sqlserver.clj
@@ -9,7 +9,6 @@
[honey.sql :as sql]
[honey.sql.helpers :as sql.helpers]
[java-time.api :as t]
- [macaw.core :as macaw]
[metabase.driver :as driver]
[metabase.driver-api.core :as driver-api]
[metabase.driver.sql :as driver.sql]
@@ -23,6 +22,7 @@
[metabase.driver.sql.query-processor.boolean-to-comparison :as sql.qp.boolean-to-comparison]
[metabase.driver.sql.query-processor.util :as sql.qp.u]
[metabase.driver.sql.util :as sql.u]
+ [metabase.driver.util :as driver.u]
[metabase.lib.schema.metadata :as lib.schema.metadata]
[metabase.util :as u]
[metabase.util.honey-sql-2 :as h2x]
@@ -30,12 +30,15 @@
[metabase.util.log :as log]
[metabase.util.malli :as mu]
[metabase.util.performance :as perf :refer [mapv get-in]])
+ ;; TODO (Chris 2026-01-22) -- Remove jsqlparser imports/typehints to be SQL parser-agnostic
(:import
(java.sql Connection DatabaseMetaData PreparedStatement ResultSet Time)
(java.time LocalDate LocalDateTime LocalTime OffsetDateTime OffsetTime ZonedDateTime)
(java.time.format DateTimeFormatter)
(java.util UUID)
+ ^{:clj-kondo/ignore [:metabase/no-jsqlparser-imports]}
(net.sf.jsqlparser.schema Table)
+ ^{:clj-kondo/ignore [:metabase/no-jsqlparser-imports]}
(net.sf.jsqlparser.statement.select PlainSelect Select)))
(set! *warn-on-reflection* true)
@@ -1023,11 +1026,12 @@
lines)]
(driver/insert-from-source! driver db-id table-definition {:type :rows :data data-rows}))))
+;; TODO (Chris 2026-01-22) -- Remove jsqlparser typehints/classes to be SQL parser-agnostic
(defmethod driver/compile-transform :sqlserver
[driver {:keys [query output-table]}]
(let [{sql-query :query sql-params :params} query
^String table-name (first (sql.qp/format-honeysql driver (keyword output-table)))
- ^Select parsed-query (macaw/parsed-query sql-query)
+ ^Select parsed-query (driver.u/parsed-query sql-query driver)
^PlainSelect select-body (.getSelectBody parsed-query)]
(.setIntoTables select-body [(Table. table-name)])
[(str parsed-query) sql-params]))
diff --git a/src/metabase/driver/sql.clj b/src/metabase/driver/sql.clj
index 345b2f2b730..fad16f793e2 100644
--- a/src/metabase/driver/sql.clj
+++ b/src/metabase/driver/sql.clj
@@ -16,6 +16,7 @@
[metabase.driver.sql.query-processor :as sql.qp]
[metabase.driver.sql.references :as sql.references]
[metabase.driver.sql.util :as sql.u]
+ [metabase.driver.util :as driver.u]
[metabase.util.humanization :as u.humanization]
[metabase.util.malli :as mu]
[metabase.util.performance :refer [some]]
@@ -190,7 +191,7 @@
db-transforms (driver-api/transforms query)]
(-> query
driver-api/raw-native-query
- macaw/parsed-query
+ (driver.u/parsed-query driver)
(macaw/query->components {:strip-contexts? true})
:tables
(->> (map :component))
@@ -300,11 +301,11 @@
(mu/defmethod driver/native-result-metadata :sql
[driver :- :keyword
native-query :- :metabase.lib.schema/native-only-query]
- (let [{:keys [returned-fields]} (->> native-query
- driver-api/raw-native-query
- macaw/parsed-query
- macaw/->ast
- (sql.references/field-references driver))]
+ (let [{:keys [returned-fields]} (-> native-query
+ driver-api/raw-native-query
+ (driver.u/parsed-query driver)
+ macaw/->ast
+ (->> (sql.references/field-references driver)))]
(mapcat #(->> (resolve-field driver native-query %)
(keep :col))
returned-fields)))
@@ -312,11 +313,11 @@
(mu/defmethod driver/validate-native-query-fields :sql :- [:set [:ref driver-api/schema.validate.error]]
[driver :- :keyword
native-query :- :metabase.lib.schema/native-only-query]
- (let [{:keys [used-fields returned-fields errors]} (->> native-query
- driver-api/raw-native-query
- macaw/parsed-query
- macaw/->ast
- (sql.references/field-references driver))
+ (let [{:keys [used-fields returned-fields errors]} (-> native-query
+ driver-api/raw-native-query
+ (driver.u/parsed-query driver)
+ macaw/->ast
+ (->> (sql.references/field-references driver)))
check-fields #(mapcat (fn [col-spec]
(->> (resolve-field driver (driver-api/->metadata-provider native-query) col-spec)
(keep :error)))
diff --git a/src/metabase/driver/util.clj b/src/metabase/driver/util.clj
index 4d77d6d74e5..0224cb3ac36 100644
--- a/src/metabase/driver/util.clj
+++ b/src/metabase/driver/util.clj
@@ -5,6 +5,7 @@
[clojure.core.memoize :as memoize]
[clojure.set :as set]
[clojure.string :as str]
+ [macaw.core :as macaw]
[metabase.app-db.core :as mdb]
[metabase.auth-provider.core :as auth-provider]
[metabase.config.core :as config]
@@ -743,3 +744,81 @@
(auth-provider/fetch-auth auth-provider database-id db-details)
db-details))
db-details)))
+
+;;; +----------------------------------------------------------------------------------------------------------------+
+;;; | Macaw parsing helpers |
+;;; +----------------------------------------------------------------------------------------------------------------+
+
+(def ^:private considered-drivers
+ "Since we are unable to ask basic questions of the driver hierarchy outside of that module, we need to explicitly
+ mention all sub-types. This is probably not a bad thing."
+ #{:h2 :mysql :postgres :redshift :sqlite :sqlserver})
+
+;; At some point, we may want a way for 3rd party drivers to opt in, but a public API deserves some hammock time.
+;; Using a separate list to the above, as we may want this to be more restrictive.
+(def trusted-for-table-permissions?
+ "Do we trust that Macaw will not give us false negatives for tables referenced by a given query?"
+ #{:h2 :mysql :postgres})
+
+(defn macaw-options
+ "Generate the options expected by Macaw based on the nature of the given driver."
+ [driver]
+ (merge
+ ;; If this isn't a driver we've considered, fallback to Macaw's conservative defaults.
+ (when (contains? considered-drivers driver)
+ {;; According to the SQL-92 specification, non-quoted identifiers should be case-insensitive, and the majority of
+ ;; engines are implemented this way.
+ ;;
+ ;; In practice there are exceptions, notably MySQL and SQL Server, where case sensitivity is a property of the
+ ;; underlying resource referenced by the identifier, and the case-sensitivity does not depend on whether the
+ ;; reference is quoted.
+ ;;
+ ;; For MySQL the case sensitivity of databases and tables depends on both the underlying file system, and a system
+ ;; variable used to initialize the database. For SQL Server it depends on the collation settings of the collection
+ ;; where the corresponding schema element is defined.
+ ;;
+ ;; For MySQL, columns and aliases can never be case-sensitive, and for SQL Server the default collation is case-
+ ;; insensitive too, so it makes sense to just treat all databases as case-insensitive as a whole.
+ ;;
+ ;; In future, Macaw may support discriminating on the identifier type, in which case we could be more precise for
+ ;; these databases. Being 100% correct would require querying system variables and schema configuration however,
+ ;; which is likely a step too far in complexity.
+ ;;
+ ;; Currently, we go with :agnostic, as it is the most relaxed semantics (the case of both the identifiers and the
+ ;; underlying schema is totally ignored, and correspondence is non-deterministic), but Macaw supports more nuanced
+ ;; :lower and :upper configuration values which coerce the query identifiers to a given case then do an exact
+ ;; comparison with the schema.
+ :case-insensitive :agnostic
+ ;; For both MySQL and SQL Server, whether identifiers are case-sensitive depends on database configuration only,
+ ;; and quoting has no effect on this, so we disable this option for consistency with `:case-insensitive`.
+ :quotes-preserve-case? (not (contains? #{:mysql :sqlserver} driver))
+ :features {:postgres-syntax (isa? driver/hierarchy driver :postgres)
+ :square-bracket-quotes (= :sqlserver driver)
+ :unsupported-statements false
+ :backslash-escape-char true
+ ;; This will slow things down, but until we measure the difference, opt for correctness.
+ :complex-parsing true}
+ ;; 10 seconds
+ :timeout 10000})
+ {;; There is no plan to be exhaustive yet.
+ ;; Note that while an allowed list would be more conservative, at the time of writing only 1 of the bundled
+ ;; drivers use FINAL as a reserved word, and mentioning them all would be prohibitive.
+ ;; In the future, we will use multimethods to define this explicitly per driver, or even discover it automatically
+ ;; through the JDBC connection, where possible.
+ :non-reserved-words (vec (remove nil? [(when-not (contains? #{:clickhouse} driver)
+ :final)]))}))
+
+(defn parsed-query
+ "Wrapped for `parsed-query` providing default options and throwing exceptions on parsing failures."
+ [sql driver & {:as opts}]
+ (let [result
+ #_{:clj-kondo/ignore [:discouraged-var]}
+ (macaw/parsed-query sql (merge (macaw-options driver)
+ opts))]
+ ;; TODO (lbrdnk 2026-01-23): In follow-up work we should ensure that failure to parse is not silently swallowed.
+ ;; I'm leaving that off at the moment to avoid potential log flooding.
+ #_(when (and (map? result) (some? (:error result)))
+ (throw (ex-info "SQL parsing failed."
+ {:macaw-error (:error result)}
+ (-> result :context :cause))))
+ result))
diff --git a/test/metabase/driver/postgres_test.clj b/test/metabase/driver/postgres_test.clj
index c360b61511d..3e972f6ad0a 100644
--- a/test/metabase/driver/postgres_test.clj
+++ b/test/metabase/driver/postgres_test.clj
@@ -2163,3 +2163,30 @@
(fn [^Connection conn]
(with-open [stmt (.createStatement conn)]
(.execute stmt "SELECT pg_sleep(6)")))))))))
+
+(deftest ^:parallel parse-final-identifier-test
+ (mt/test-driver
+ :postgres
+
+ (testing "`final` is allowed as identifier and parsed correctly"
+ (mt/with-temp [:model/Database db {:engine "postgres"
+ :name "final"
+ :initial_sync_status "complete"}
+ :model/Table t {:name "final"
+ :schema "public"
+ :db_id (:id db)}
+ :model/Field _ {:name "final"
+ :table_id (:id t)}]
+ (mt/with-db
+ db
+ (let [mp (mt/metadata-provider)
+ query (lib/native-query mp "select final from final")
+ broken-query (lib/native-query mp "select final, xix from final")]
+ (is (=? #{{:table (:id t)}}
+ (driver/native-query-deps :postgres query)))
+ (is (=? [{:name "final"
+ :lib/desired-column-alias "final"}]
+ (driver/native-result-metadata :postgres query)))
+ (is (=? {:type :missing-column
+ :name "xix"}
+ (first (driver/validate-native-query-fields :postgres broken-query))))))))))
diff --git a/test/metabase/driver/sql/references_test.clj b/test/metabase/driver/sql/references_test.clj
index 26e7c70762c..49e2e53fb27 100644
--- a/test/metabase/driver/sql/references_test.clj
+++ b/test/metabase/driver/sql/references_test.clj
@@ -5,6 +5,8 @@
[metabase.driver-api.core :as driver-api]
[metabase.driver.sql.references :as sql.references]))
+;; TODO (Chris 2026-01-22) -- Refactor to use driver.u/parsed-query instead of macaw/parsed-query
+#_{:clj-kondo/ignore [:discouraged-var]}
(defn- ->references [query]
(->> query macaw/parsed-query macaw/->ast (sql.references/field-references :sql)))