Skip to content

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

Move honeysql helper to simplify module dependencies (#64689)

Noah Moss27a078faf0e1
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index 02335b8a767..c9d49012652 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -848,7 +848,6 @@
app-db
channel
config
- driver
premium-features
settings
task
@@ -1084,7 +1083,6 @@
audit-app
collections
config
- driver
events
lib
lib-be
@@ -1157,7 +1155,6 @@
app-db
channel
config
- driver
events
login-history
request
diff --git a/dev/src/dev/deps_graph.clj b/dev/src/dev/deps_graph.clj
index cd8c796a463..9528376ae6a 100644
--- a/dev/src/dev/deps_graph.clj
+++ b/dev/src/dev/deps_graph.clj
@@ -88,13 +88,16 @@
[zloc :- ::zloc]
(when (= (z/tag zloc) :list)
(let [first-child (z/down zloc)]
- (and (= (z/tag first-child) :token)
- (require-symbols (z/sexpr first-child))))))
+ (when (= (z/tag first-child) :token)
+ ;; Check all child symbols on the line since `require` might be called in a threading macro
+ ;; like (-> 'ns require)
+ (some require-symbols (z/child-sexprs zloc))))))
(mu/defn- find-required-namespace :- [:maybe simple-symbol?]
"Given a `zloc` pointing to one of the children of something like `(require ...)` find a required namespace symbol."
[zloc :- ::zloc]
(when-let [symbol-loc (z/find-depth-first zloc #(and (= (z/tag %) :token)
+ (symbol? (z/sexpr %))
(not= (z/sexpr %) 'quote)))]
(let [symb (z/sexpr symbol-loc)]
(if (qualified-symbol? symb)
diff --git a/dev/test/dev/deps_graph_test.clj b/dev/test/dev/deps_graph_test.clj
index d24116f9a95..9f10f51d23a 100644
--- a/dev/test/dev/deps_graph_test.clj
+++ b/dev/test/dev/deps_graph_test.clj
@@ -7,12 +7,15 @@
(deftest ^:parallel find-required-namespaces-test
(are [s expected] (= (quote expected)
(#'dev.deps-graph/find-required-namespaces (z/of-string s)))
- "(require 'malli.generator)" #{malli.generator}
- "(require (quote malli.generator))" #{malli.generator}
- "(classloader/require 'a 'b)" #{a b}
- "(requiring-resolve 'a/b 'c/d)" #{a c}
- "(require '[malli.generator :as mg])" #{malli.generator}
- "(require '[malli.generator])" #{malli.generator}))
+ "(require 'malli.generator)" #{malli.generator}
+ "(require (quote malli.generator))" #{malli.generator}
+ "(classloader/require 'a 'b)" #{a b}
+ "(requiring-resolve 'a/b 'c/d)" #{a c}
+ "(require '[malli.generator :as mg])" #{malli.generator}
+ "(require '[malli.generator])" #{malli.generator}
+ "(-> 'malli.generator requiring-resolve)" #{malli.generator}))
+ ;; TODO: reader conditionals don't work properly
+ ; "(#?(:clj requiring-resolve :cljs resolve) 'malli.generator)" #{malli.generator}))
(deftest ^:parallel find-requires-test
(are [s expected] (= (quote expected)
@@ -21,6 +24,12 @@
((require '[malli.generator])
(requiring-resolve 'whatever/x))
+ "(-> 'whatever requiring-resolve)"
+ ((-> 'whatever requiring-resolve))
+
+ ; "(#?(:clj requiring-resolve :cljs resolve) 'malli.generator)"
+ ; ((#?(:clj requiring-resolve :cljs resolve) 'malli.generator))
+
;; should ignore comments.
"(do #_(require '[malli.generator]))"
()
diff --git a/enterprise/backend/src/metabase_enterprise/transforms/models/job_run.clj b/enterprise/backend/src/metabase_enterprise/transforms/models/job_run.clj
index 3daa273b36d..777fc81e6f6 100644
--- a/enterprise/backend/src/metabase_enterprise/transforms/models/job_run.clj
+++ b/enterprise/backend/src/metabase_enterprise/transforms/models/job_run.clj
@@ -1,8 +1,8 @@
(ns metabase-enterprise.transforms.models.job-run
(:require
[metabase.app-db.core :as mdb]
- [metabase.driver.sql.query-processor :as sql.qp]
[metabase.models.interface :as mi]
+ [metabase.util.honey-sql-2 :as h2x]
[methodical.core :as methodical]
[toucan2.core :as t2]
[toucan2.realize :as t2.realize]))
@@ -81,7 +81,7 @@
[age unit]
(t2/update! :model/TransformJobRun
:is_active true
- :updated_at [:< (sql.qp/add-interval-honeysql-form (mdb/db-type) :%now (- age) unit)]
+ :updated_at [:< (h2x/add-interval-honeysql-form (mdb/db-type) :%now (- age) unit)]
{:status :timeout
:end_time :%now
:is_active nil
diff --git a/enterprise/backend/src/metabase_enterprise/transforms/models/transform_run.clj b/enterprise/backend/src/metabase_enterprise/transforms/models/transform_run.clj
index c169b83f884..1c0278b9477 100644
--- a/enterprise/backend/src/metabase_enterprise/transforms/models/transform_run.clj
+++ b/enterprise/backend/src/metabase_enterprise/transforms/models/transform_run.clj
@@ -3,11 +3,11 @@
[medley.core :as m]
[metabase-enterprise.transforms.models.transform-run-cancelation :as cancel]
[metabase.app-db.core :as mdb]
- [metabase.driver.sql.query-processor :as sql.qp]
[metabase.models.interface :as mi]
[metabase.query-processor.parameters.dates :as params.dates]
[metabase.util :as u]
[metabase.util.date-2 :as u.date]
+ [metabase.util.honey-sql-2 :as h2x]
[metabase.util.i18n :refer [tru]]
[methodical.core :as methodical]
[toucan2.core :as t2]
@@ -124,7 +124,7 @@
[age unit]
(u/prog1 (t2/update! :model/TransformRun
:is_active true
- :start_time [:< (sql.qp/add-interval-honeysql-form (mdb/db-type) :%now (- age) unit)]
+ :start_time [:< (h2x/add-interval-honeysql-form (mdb/db-type) :%now (- age) unit)]
{:status :timeout
:end_time :%now
:is_active nil
@@ -140,7 +140,7 @@
:from :transform_run_cancelation
:where [:<
:transform_run_cancelation.time
- (sql.qp/add-interval-honeysql-form (mdb/db-type) :%now (- age) unit)]}]
+ (h2x/add-interval-honeysql-form (mdb/db-type) :%now (- age) unit)]}]
{:status :canceled
:end_time :%now
:is_active nil
diff --git a/modules/drivers/clickhouse/src/metabase/driver/clickhouse_qp.clj b/modules/drivers/clickhouse/src/metabase/driver/clickhouse_qp.clj
index 49d405c67dc..6dae0e235a8 100644
--- a/modules/drivers/clickhouse/src/metabase/driver/clickhouse_qp.clj
+++ b/modules/drivers/clickhouse/src/metabase/driver/clickhouse_qp.clj
@@ -9,7 +9,7 @@
[metabase.driver.clickhouse-version :as clickhouse-version]
[metabase.driver.sql-jdbc.execute :as sql-jdbc.execute]
[metabase.driver.sql.parameters.substitution :as sql.params.substitution]
- [metabase.driver.sql.query-processor :as sql.qp :refer [add-interval-honeysql-form]]
+ [metabase.driver.sql.query-processor :as sql.qp]
[metabase.driver.sql.query-processor.util :as sql.qp.u]
[metabase.driver.sql.util :as sql.u]
[metabase.util :as u]
@@ -275,7 +275,7 @@
(if (some interval? args)
(if-let [[field intervals] (u/pick-first (complement interval?) args)]
(reduce (fn [hsql-form [_ amount unit]]
- (add-interval-honeysql-form driver hsql-form amount unit))
+ (sql.qp/add-interval-honeysql-form driver hsql-form amount unit))
(sql.qp/->honeysql driver field)
intervals)
(throw (ex-info "Summing intervals is not supported" {:args args})))
diff --git a/src/metabase/driver/h2.clj b/src/metabase/driver/h2.clj
index 4bc7e529423..f4d616283d2 100644
--- a/src/metabase/driver/h2.clj
+++ b/src/metabase/driver/h2.clj
@@ -303,30 +303,9 @@
;; FIXME: need to check the equivalent of check-native-query-not-using-default-user and check-action-commands-allowed
((get-method driver/execute-raw-queries! :sql-jdbc) driver conn-spec queries))
-(defn- dateadd [unit amount expr]
- (let [expr (h2x/cast-unless-type-in "datetime" #{"datetime" "timestamp" "timestamp with time zone" "date"} expr)]
- (-> [:dateadd
- (h2x/literal unit)
- (if (number? amount)
- (sql.qp/inline-num (long amount))
- (h2x/cast-unless-type-in "integer" #{"long" "integer"} amount))
- expr]
- (h2x/with-database-type-info (h2x/database-type expr)))))
-
(defmethod sql.qp/add-interval-honeysql-form :h2
[driver hsql-form amount unit]
- (cond
- (= unit :quarter)
- (recur driver hsql-form (h2x/* amount 3) :month)
-
- ;; H2 only supports long ints in the `dateadd` amount field; since we want to support fractional seconds (at least
- ;; for application DB purposes) convert to `:millisecond`
- (and (= unit :second)
- (not (zero? (rem amount 1))))
- (recur driver hsql-form (* amount 1000.0) :millisecond)
-
- :else
- (dateadd unit amount hsql-form)))
+ (h2x/add-interval-honeysql-form driver hsql-form amount unit))
(defmethod driver/humanize-connection-error-message :h2
[_ messages]
diff --git a/src/metabase/driver/mysql.clj b/src/metabase/driver/mysql.clj
index 63fdaba8efe..9fc59e30006 100644
--- a/src/metabase/driver/mysql.clj
+++ b/src/metabase/driver/mysql.clj
@@ -242,10 +242,7 @@
(defmethod sql.qp/add-interval-honeysql-form :mysql
[driver hsql-form amount unit]
- ;; MySQL doesn't support `:millisecond` as an option, but does support fractional seconds
- (if (= unit :millisecond)
- (recur driver hsql-form (/ amount 1000.0) :second)
- [:date_add hsql-form [:raw (format "INTERVAL %s %s" amount (name unit))]]))
+ (h2x/add-interval-honeysql-form driver hsql-form amount unit))
;; now() returns current timestamp in seconds resolution; now(6) returns it in nanosecond resolution
(defmethod sql.qp/current-datetime-honeysql-form :mysql
diff --git a/src/metabase/driver/postgres.clj b/src/metabase/driver/postgres.clj
index adc25850dc3..ed61536bb05 100644
--- a/src/metabase/driver/postgres.clj
+++ b/src/metabase/driver/postgres.clj
@@ -457,42 +457,9 @@
[_ json-field-identifier]
[:length [:cast json-field-identifier :text]])
-(defn- ->timestamp [honeysql-form]
- (h2x/cast-unless-type-in "timestamp" #{"timestamp" "timestamptz" "timestamp with time zone" "date"} honeysql-form))
-
-(defn- format-interval
- "Generate a Postgres 'INTERVAL' literal.
-
- (sql/format-expr [::interval 2 :day])
- =>
- [\"INTERVAL '2 day'\"]"
- ;; I tried to write this with Malli but couldn't figure out how to make it work. See
- ;; https://metaboat.slack.com/archives/CKZEMT1MJ/p1676076592468909
- [_fn [amount unit]]
- {:pre [(number? amount)
- (#{:millisecond :second :minute :hour :day :week :month :year} unit)]}
- [(format "INTERVAL '%s %s'" (num amount) (name unit))])
-
-(sql/register-fn! ::interval #'format-interval)
-
-(defn- interval [amount unit]
- (h2x/with-database-type-info [::interval amount unit] "interval"))
-
(defmethod sql.qp/add-interval-honeysql-form :postgres
[driver hsql-form amount unit]
- ;; Postgres doesn't support quarter in intervals (#20683)
- (cond
- (= unit :quarter)
- (recur driver hsql-form (* 3 amount) :month)
-
- ;; date + interval -> timestamp, so cast the expression back to date
- (h2x/is-of-type? hsql-form "date")
- (h2x/cast "date" (h2x/+ hsql-form (interval amount unit)))
-
- :else
- (let [hsql-form (->timestamp hsql-form)]
- (-> (h2x/+ hsql-form (interval amount unit))
- (h2x/with-type-info (h2x/type-info hsql-form))))))
+ (h2x/add-interval-honeysql-form driver hsql-form amount unit))
(defmethod sql.qp/current-datetime-honeysql-form :postgres
[driver]
@@ -550,12 +517,12 @@
(h2x/cast "date" [:date_trunc (h2x/literal unit) expr])
#_else
- (let [expr' (->timestamp expr)]
+ (let [expr' (h2x/->pg-timestamp expr)]
(-> [:date_trunc (h2x/literal unit) expr']
(h2x/with-database-type-info (h2x/database-type expr'))))))
(defn- extract-from-timestamp [unit expr]
- (extract unit (->timestamp expr)))
+ (extract unit (h2x/->pg-timestamp expr)))
(defn- extract-integer [unit expr]
(h2x/->integer (extract-from-timestamp unit expr)))
diff --git a/src/metabase/driver/sql/query_processor.clj b/src/metabase/driver/sql/query_processor.clj
index 946e23658c0..e0734b19d75 100644
--- a/src/metabase/driver/sql/query_processor.clj
+++ b/src/metabase/driver/sql/query_processor.clj
@@ -422,16 +422,20 @@
(binding [driver.common/*start-of-week* :monday]
(date driver :day-of-week honeysql-expr)))
+;; add-interval-honeysql-form is also defined in metabase.util.honey-sql-2 for Postgres, MySQL/MariaDB, and H2. Prefer
+;; that for app db queries to avoid unnecessary dependencies on the driver module.
(defmulti add-interval-honeysql-form
- "Return a HoneySQL form that performs represents addition of some temporal interval to the original `hsql-form`.
+ "Return a HoneySQL form that represents addition of some temporal interval to the original `hsql-form`.
`unit` is one of the units listed in [[metabase.util.date-2/add-units]].
(add-interval-honeysql-form :my-driver hsql-form 1 :day) -> [:date_add hsql-form 1 (h2x/literal 'day')]
- `amount` is usually an integer, but can be floating-point for units like seconds."
- {:added "0.34.2" :arglists '([driver hsql-form amount unit])}
- driver/dispatch-on-initialized-driver
- :hierarchy #'driver/hierarchy)
+ `amount` is usually an integer, but can be floating-point for units like seconds.
+
+ This multimethod can be extended by drivers in their respective namespaces."
+ {:added "0.34.2" :arglists '([db-type hsql-form amount unit])}
+ (fn [db-type _hsql-form _amount _unit]
+ (keyword db-type)))
(mu/defn adjust-start-of-week
"Truncate to the day the week starts on.
diff --git a/src/metabase/model_persistence/task/persist_refresh.clj b/src/metabase/model_persistence/task/persist_refresh.clj
index f7939055ef7..a605c424d64 100644
--- a/src/metabase/model_persistence/task/persist_refresh.clj
+++ b/src/metabase/model_persistence/task/persist_refresh.clj
@@ -9,7 +9,6 @@
[metabase.app-db.core :as mdb]
[metabase.driver :as driver]
[metabase.driver.ddl.interface :as ddl.i]
- [metabase.driver.sql.query-processor :as sql.qp]
[metabase.events.core :as events]
[metabase.model-persistence.models.persisted-info :as persisted-info]
[metabase.model-persistence.settings :as model-persistence.settings]
@@ -18,6 +17,7 @@
[metabase.task-history.core :as task-history]
[metabase.task.core :as task]
[metabase.util :as u]
+ [metabase.util.honey-sql-2 :as h2x]
[metabase.util.log :as log]
[metabase.util.malli :as mu]
[potemkin.types :as p]
@@ -167,7 +167,7 @@
;; 1. so that people have a chance to change their mind.
;; 2. if a query is running against the cache, it doesn't get ripped out.
[:< :state_change_at
- (sql.qp/add-interval-honeysql-form (mdb/db-type) :%now -1 :hour)]]
+ (h2x/add-interval-honeysql-form (mdb/db-type) :%now -1 :hour)]]
[:= :c.type "question"]
[:= :c.archived true]
;; card_id is set to null when the corresponding card is deleted
diff --git a/src/metabase/product_feedback/task/creator_sentiment_emails.clj b/src/metabase/product_feedback/task/creator_sentiment_emails.clj
index 3a561dfaac5..71f58443a76 100644
--- a/src/metabase/product_feedback/task/creator_sentiment_emails.clj
+++ b/src/metabase/product_feedback/task/creator_sentiment_emails.clj
@@ -9,9 +9,9 @@
[metabase.channel.email.messages :as messages]
[metabase.channel.settings :as channel.settings]
[metabase.config.core :as config]
- [metabase.driver.sql.query-processor :as sql.qp]
[metabase.premium-features.core :as premium-features]
[metabase.task.core :as task]
+ [metabase.util.honey-sql-2 :as h2x]
[metabase.util.log :as log]
[toucan2.core :as t2])
(:import
@@ -37,8 +37,8 @@
:join [[:report_card :rc] [:= :rc.creator_id :u.id]
[:report_dashboard :d] [:= :d.creator_id :u.id]]
:where [:and
- [:>= :rc.created_at (sql.qp/add-interval-honeysql-form (mdb/db-type) :%now -2 :month)]
- [:>= :d.created_at (sql.qp/add-interval-honeysql-form (mdb/db-type) :%now -2 :month)]
+ [:>= :rc.created_at (h2x/add-interval-honeysql-form (mdb/db-type) :%now -2 :month)]
+ [:>= :d.created_at (h2x/add-interval-honeysql-form (mdb/db-type) :%now -2 :month)]
[:= :u.is_active true]
[:= :u.type "personal"]
(when has-whitelabelling? [:= :u.is_superuser true])]
diff --git a/src/metabase/search/scoring.clj b/src/metabase/search/scoring.clj
index e0042a90ff3..8cf03c9f41a 100644
--- a/src/metabase/search/scoring.clj
+++ b/src/metabase/search/scoring.clj
@@ -3,8 +3,8 @@
[clojure.string :as str]
[honey.sql.helpers :as sql.helpers]
[metabase.app-db.core :as mdb]
- [metabase.driver.sql.query-processor :as sql.qp]
- [metabase.search.config :as search.config]))
+ [metabase.search.config :as search.config]
+ [metabase.util.honey-sql-2 :as h2x]))
(def ^:private seconds-in-a-day 86400)
@@ -66,7 +66,7 @@
(defn user-recency-expr
"Expression to select the `:user-recency` timestamp for the `current-user-id`."
[{:keys [current-user-id]}]
- (let [one-day-ago (sql.qp/add-interval-honeysql-form (mdb/db-type) :%now -1 :day)]
+ (let [one-day-ago (h2x/add-interval-honeysql-form (mdb/db-type) :%now -1 :day)]
{:select [[[:case
;; Transforms get a hardcoded 1-day last_viewed_at because we don't track views on them
[:= :search_index.model [:inline "transform"]]
diff --git a/src/metabase/session/task/session_cleanup.clj b/src/metabase/session/task/session_cleanup.clj
index 265edf5f515..f8b4d52cc03 100644
--- a/src/metabase/session/task/session_cleanup.clj
+++ b/src/metabase/session/task/session_cleanup.clj
@@ -5,8 +5,8 @@
[clojurewerkz.quartzite.triggers :as triggers]
[metabase.app-db.core :as mdb]
[metabase.config.core :as config]
- [metabase.driver.sql.query-processor :as sql.qp]
[metabase.task.core :as task]
+ [metabase.util.honey-sql-2 :as h2x]
[toucan2.core :as t2]))
(set! *warn-on-reflection* true)
@@ -14,10 +14,10 @@
(defn- cleanup-sessions!
"Deletes sessions from the database which are no longer valid"
[]
- (let [oldest-allowed [:inline (sql.qp/add-interval-honeysql-form (mdb/db-type)
- :%now
- (- (config/config-int :max-session-age))
- :minute)]]
+ (let [oldest-allowed [:inline (h2x/add-interval-honeysql-form (mdb/db-type)
+ :%now
+ (- (config/config-int :max-session-age))
+ :minute)]]
(t2/delete! :model/Session :created_at [:< oldest-allowed])))
(def ^:private session-cleanup-job-key (jobs/key "metabase.task.session-cleanup.job"))
diff --git a/src/metabase/sync/field_values.clj b/src/metabase/sync/field_values.clj
index 2f11c352037..b9aef9df608 100644
--- a/src/metabase/sync/field_values.clj
+++ b/src/metabase/sync/field_values.clj
@@ -82,7 +82,7 @@
(sync-util/with-error-handling (format "Error deleting expired advanced field values for %s" (sync-util/name-for-logging field))
(let [conditions [:field_id (:id field)
:type [:in field-values/advanced-field-values-types]
- :created_at [:< ((requiring-resolve 'metabase.driver.sql.query-processor/add-interval-honeysql-form)
+ :created_at [:< ((requiring-resolve 'metabase.util.honey-sql-2/add-interval-honeysql-form)
(mdb/db-type)
:%now
(- (t/as field-values/advanced-field-values-max-age :days))
diff --git a/src/metabase/sync/sync_metadata/tables.clj b/src/metabase/sync/sync_metadata/tables.clj
index 2267a96b3f9..81104b8d416 100644
--- a/src/metabase/sync/sync_metadata/tables.clj
+++ b/src/metabase/sync/sync_metadata/tables.clj
@@ -312,7 +312,7 @@
;; we're just using this as a cheap namespace
suffix (str "__mbarchiv__" (.toEpochSecond (t/offset-date-time)))
threshold-expr (apply
- (requiring-resolve 'metabase.driver.sql.query-processor/add-interval-honeysql-form)
+ (requiring-resolve 'metabase.util.honey-sql-2/add-interval-honeysql-form)
(mdb/db-type) :%now archive-tables-threshold)
tables-to-archive (t2/select :model/Table
:db_id (u/the-id database)
diff --git a/src/metabase/util/honey_sql_2.clj b/src/metabase/util/honey_sql_2.clj
index b9c4fbf1cb4..abebe8a52b2 100644
--- a/src/metabase/util/honey_sql_2.clj
+++ b/src/metabase/util/honey_sql_2.clj
@@ -422,3 +422,98 @@
:h2 (with-database-type-info :%now "timestamp")
:mysql (with-database-type-info [:now [:inline 6]] "timestamp")
:postgres (with-database-type-info :%now "timestamptz")))
+
+(defn- format-postgres-interval
+ "Generate a Postgres 'INTERVAL' literal.
+
+ (sql/format-expr [::postgres-interval 2 :day])
+ =>
+ [\"INTERVAL '2 day'\"]"
+ ;; I tried to write this with Malli but couldn't figure out how to make it work. See
+ ;; https://metaboat.slack.com/archives/CKZEMT1MJ/p1676076592468909
+ [_fn [amount unit]]
+ {:pre [(number? amount)
+ (#{:millisecond :second :minute :hour :day :week :month :year} unit)]}
+ [(clojure.core/format "INTERVAL '%s %s'" (num amount) (name unit))])
+
+(sql/register-fn! ::postgres-interval #'format-postgres-interval)
+
+(defn- pg-interval [amount unit]
+ (with-database-type-info [::postgres-interval amount unit] "interval"))
+
+(defn ->pg-timestamp
+ "Cast to timestamp, preserving timestamptz if present."
+ [honeysql-form]
+ (cast-unless-type-in "timestamp" #{"timestamp" "timestamptz" "timestamp with time zone" "date"} honeysql-form))
+
+(defmulti add-interval-honeysql-form
+ "Return a HoneySQL form that represents addition of some temporal interval to the original `hsql-form`.
+ `unit` is one of the units listed in [[metabase.util.date-2/add-units]].
+
+ (add-interval-honeysql-form :my-driver hsql-form 1 :day) -> [:date_add hsql-form 1 (h2x/literal 'day')]
+
+ `amount` is usually an integer, but can be floating-point for units like seconds.
+
+ This multimethod is intended for use in app DB queries; other drivers should extend
+ metabase.driver.sql.query-processor/add-interval-honeysql-form instead."
+ {:arglists '([db-type hsql-form amount unit])}
+ (fn [db-type _hsql-form _amount _unit]
+ (keyword db-type)))
+
+(defmethod add-interval-honeysql-form :postgres
+ [db-type hsql-form amount unit]
+ ;; Postgres doesn't support quarter in intervals (#20683)
+ (cond
+ (= unit :quarter)
+ (recur db-type hsql-form (clojure.core/* 3 amount) :month)
+
+ ;; date + interval -> timestamp, so cast the expression back to date
+ (is-of-type? hsql-form "date")
+ (cast "date" (+ hsql-form (pg-interval amount unit)))
+
+ :else
+ (let [hsql-form (->pg-timestamp hsql-form)]
+ (-> (+ hsql-form (pg-interval amount unit))
+ (with-type-info (type-info hsql-form))))))
+
+(defmethod add-interval-honeysql-form :mysql
+ [db-type hsql-form amount unit]
+ ;; MySQL doesn't support `:millisecond` as an option, but does support fractional seconds
+ (if (= unit :millisecond)
+ (recur db-type hsql-form (clojure.core// amount 1000.0) :second)
+ [:date_add hsql-form [:raw (clojure.core/format "INTERVAL %s %s" amount (name unit))]]))
+
+(defn- dateadd-h2 [unit amount expr]
+ (let [expr (cast-unless-type-in "datetime" #{"datetime" "timestamp" "timestamp with time zone" "date"} expr)]
+ (-> [:dateadd
+ (literal unit)
+ (if (number? amount)
+ [:inline (long amount)]
+ (cast-unless-type-in "integer" #{"long" "integer"} amount))
+ expr]
+ (with-database-type-info (database-type expr)))))
+
+(defmethod add-interval-honeysql-form :h2
+ [db-type hsql-form amount unit]
+ (cond
+ (= unit :quarter)
+ (recur db-type hsql-form (* amount 3) :month)
+
+ ;; H2 only supports long ints in the `dateadd` amount field; since we want to support fractional seconds (at least
+ ;; for application DB purposes) convert to `:millisecond`
+ (and (= unit :second)
+ (not (zero? (rem amount 1))))
+ (recur db-type hsql-form (clojure.core/* amount 1000.0) :millisecond)
+
+ :else
+ (dateadd-h2 unit amount hsql-form)))
+
+(defmethod add-interval-honeysql-form :default
+ [db-type hsql-form amount unit]
+ (throw (ex-info (clojure.core/format (str "metabase.util.honey-sql-2/add-interval-honeysql-form not implemented for db-type %s. "
+ "You might want to be calling metabase.driver.sql.query-processor/add-interval-honeysql-form instead.")
+ db-type)
+ {:db-type db-type
+ :hsql-form hsql-form
+ :amount amount
+ :unit unit})))
diff --git a/test/metabase/driver/postgres_test.clj b/test/metabase/driver/postgres_test.clj
index d97af3bef63..9323843e0b6 100644
--- a/test/metabase/driver/postgres_test.clj
+++ b/test/metabase/driver/postgres_test.clj
@@ -62,21 +62,6 @@
(binding [sync-util/*log-exceptions-and-continue?* false]
(mt/with-test-user :rasta (thunk)))))
-(deftest ^:parallel interval-test
- (is (= ["INTERVAL '2 day'"]
- (sql/format-expr [::postgres/interval 2 :day])))
- (is (= ["INTERVAL '-2.5 year'"]
- (sql/format-expr [::postgres/interval -2.5 :year])))
- (are [amount unit msg] (thrown-with-msg?
- AssertionError
- msg
- (sql/format-expr [::postgres/interval amount unit]))
- "2" :day #"\QAssert failed: (number? amount)\E"
- :day 2 #"\QAssert failed: (number? amount)\E"
- 2 "day" #"\QAssert failed: (#{:day :hour :week :second :month :year :millisecond :minute} unit)\E"
- 2 2 #"\QAssert failed: (#{:day :hour :week :second :month :year :millisecond :minute} unit)\E"
- 2 :can #"\QAssert failed: (#{:day :hour :week :second :month :year :millisecond :minute} unit)\E"))
-
(deftest ^:parallel extract-test
(is (= ["extract(month from NOW())"]
(sql.qp/format-honeysql :postgres (#'postgres/extract :month :%now)))))
diff --git a/test/metabase/server/middleware/session_test.clj b/test/metabase/server/middleware/session_test.clj
index 974c14399ce..b5642e9120a 100644
--- a/test/metabase/server/middleware/session_test.clj
+++ b/test/metabase/server/middleware/session_test.clj
@@ -9,13 +9,13 @@
[metabase.app-db.core :as mdb]
[metabase.config.core :as config]
[metabase.core.initialization-status :as init-status]
- [metabase.driver.sql.query-processor :as sql.qp]
[metabase.premium-features.core :as premium-features]
[metabase.request.core :as request]
[metabase.server.middleware.session :as mw.session]
[metabase.session.core :as session]
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]
+ [metabase.util.honey-sql-2 :as h2x]
[metabase.util.i18n :as i18n]
[metabase.util.secret :as u.secret]
[ring.mock.request :as ring.mock]
@@ -37,10 +37,10 @@
(testing "Session expiration time = 1 minute"
(with-redefs [env/env (assoc env/env :max-session-age "1")]
(doseq [[created-at expected msg]
- [[:%now false "brand-new session"]
- [#t "1970-01-01T00:00:01Z" true "really old session"]
- [(sql.qp/add-interval-honeysql-form (mdb/db-type) :%now -61 :second) true "session that is 61 seconds old"]
- [(sql.qp/add-interval-honeysql-form (mdb/db-type) :%now -59 :second) false "session that is 59 seconds old"]]]
+ [[:%now false "brand-new session"]
+ [#t "1970-01-01T00:00:01Z" true "really old session"]
+ [(h2x/add-interval-honeysql-form (mdb/db-type) :%now -61 :second) true "session that is 61 seconds old"]
+ [(h2x/add-interval-honeysql-form (mdb/db-type) :%now -59 :second) false "session that is 59 seconds old"]]]
(testing (format "\n%s %s be expired." msg (if expected "SHOULD" "SHOULD NOT"))
(mt/with-temp [:model/User {user-id :id}]
(let [session-id (session/generate-session-id)
diff --git a/test/metabase/util/honey_sql_2_test.clj b/test/metabase/util/honey_sql_2_test.clj
index 8fa03a8b645..119a53be08f 100644
--- a/test/metabase/util/honey_sql_2_test.clj
+++ b/test/metabase/util/honey_sql_2_test.clj
@@ -29,6 +29,22 @@
(is (= ["(a AT TIME ZONE 'US/Pacific')"]
(sql/format-expr [::h2x/at-time-zone :a "US/Pacific"])))))
+(deftest ^:parallel postgres-interval-test
+ (testing `::h2x/postgres-interval
+ (is (= ["INTERVAL '2 day'"]
+ (sql/format-expr [::h2x/postgres-interval 2 :day])))
+ (is (= ["INTERVAL '-2.5 year'"]
+ (sql/format-expr [::h2x/postgres-interval -2.5 :year])))
+ (are [amount unit msg] (thrown-with-msg?
+ AssertionError
+ msg
+ (sql/format-expr [::h2x/postgres-interval amount unit]))
+ "2" :day #"\QAssert failed: (number? amount)\E"
+ :day 2 #"\QAssert failed: (number? amount)\E"
+ 2 "day" #"\QAssert failed: (#{:day :hour :week :second :month :year :millisecond :minute} unit)\E"
+ 2 2 #"\QAssert failed: (#{:day :hour :week :second :month :year :millisecond :minute} unit)\E"
+ 2 :can #"\QAssert failed: (#{:day :hour :week :second :month :year :millisecond :minute} unit)\E")))
+
(deftest ^:parallel format-test
(testing "Basic format test not including a specific quoting option"
(is (= ["SELECT setting"]