Skip to content

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

Untangle util and a few other cross-module cycle knots (#77954)

Chris Truterf35a8a0077b7
diff --git a/.clj-kondo/config.edn b/.clj-kondo/config.edn
index aec31094099..92f7f9a29b5 100644
--- a/.clj-kondo/config.edn
+++ b/.clj-kondo/config.edn
@@ -424,6 +424,7 @@
metabase.analyze.classifiers.core classifiers
metabase.channel.core channel
metabase.channel.render.core channel.render
+ metabase.channel.render.markdown markdown
metabase.cloud-migration.core cloud-migration
metabase.eid-translation.core eid-translation
metabase.llm.test-util llm.tu
@@ -460,7 +461,6 @@
metabase.util.macros u.macros
metabase.util.malli mu
metabase.util.malli.schema ms
- metabase.util.markdown markdown
metabase.util.password u.password
metabase.util.ui-logic ui-logic
metabase.xrays.core xrays
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index 085f47cf760..b467977acaa 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -355,13 +355,14 @@
:api #{metabase.app-db.cluster-lock ; TODO (Chris 2026-09-16) -- callers should go through app-db.core
metabase.app-db.core
metabase.app-db.init
+ metabase.app-db.quartz
metabase.app-db.setting
metabase.app-db.setup
metabase.app-db.sql-errors
metabase.app-db.transient-error}
:uses #{auth-provider
connection-pool
- task
+ task.secure-delegate
util
util.classloader
util.config}
@@ -1169,6 +1170,7 @@
:ns-prefix "metabase.agent-lib"
:api #{metabase.agent-lib.representations metabase.agent-lib.representations.repair metabase.agent-lib.representations.resolve}
:uses #{lib
+ lib.be
lib.metadata
lib.schema
models
@@ -1309,6 +1311,7 @@
:module-exports #{mcp.oauth-server}
:api #{metabase.mcp.callback-api
metabase.mcp.core
+ metabase.mcp.http-handler
metabase.mcp.init
metabase.mcp.usage
metabase.mcp.v2.api}
@@ -2449,10 +2452,9 @@
segments
{:team "Graphy"
- :api #{metabase.segments.api
- metabase.segments.schema}
+ :module-exports #{segments.rest}
+ :api #{metabase.segments.schema}
:uses #{api
- events
lib
lib.be
lib.schema
@@ -2463,11 +2465,24 @@
users
util
warehouse-schema-overlay
- warehouses.schema
- xrays}
+ warehouses.schema}
:model-exports #{:model/Segment}
:model-imports #{:model/Collection :model/Table :model/User}}
+ segments.rest
+ {:team "Graphy"
+ :api #{metabase.segments.rest.api}
+ :uses #{api
+ events
+ lib
+ lib.be
+ models
+ permissions
+ segments
+ util
+ xrays}
+ :model-imports #{:model/Segment}}
+
server
{:team "UX West"
:api #{metabase.server.core
@@ -2488,22 +2503,18 @@
embedding
lib.be
lib.schema
- mcp
- mcp.oauth-server
metabot.agent-api
premium-features
query-processor
request
session
settings
- sso
system
tracing
users
util
util.config
- enterprise/custom-viz-plugin
- enterprise/sso}
+ enterprise/custom-viz-plugin}
:model-imports #{:model/Session}}
session
@@ -2626,7 +2637,7 @@
{:team "UX West"
:module-exports #{sso.auth-identity}
:api #{metabase.sso.api
- metabase.sso.api.slack-connect
+ metabase.sso.auth-wrapper
metabase.sso.core
metabase.sso.init
metabase.sso.settings}
@@ -2641,7 +2652,8 @@
startup
system
util
- util.config}
+ util.config
+ enterprise/sso}
:model-imports #{:model/AuthIdentity :model/PermissionsGroupMembership}}
sso.auth-identity
@@ -2739,14 +2751,12 @@
task
{:team "UX West"
- :module-exports #{task.history}
- :api #{metabase.task.bootstrap
- metabase.task.core}
+ :module-exports #{task.history task.secure-delegate}
+ :api #{metabase.task.core}
:uses #{app-db
tracing
util
- util.classloader
- util.config}}
+ util.classloader}}
task.history
{:team "UX West"
@@ -2769,6 +2779,11 @@
:model-exports #{:model/TaskHistory :model/TaskRun}
:model-imports #{:model/Card :model/Dashboard :model/Database}}
+ task.secure-delegate
+ {:team "UX West"
+ :api #{metabase.task.secure-delegate.core}
+ :uses #{util util.classloader util.config}}
+
testing-api
{:team "DevEx"
:api #{metabase.testing-api.api
@@ -2837,7 +2852,8 @@
{:team "DevEx"
:api #{metabase.tracing.core
metabase.tracing.init}
- :uses #{events
+ :uses #{app-db
+ events
settings
task
util
@@ -3143,7 +3159,7 @@
util.config
util.graph}
:api :any
- :uses #{settings util.classloader util.config}}
+ :uses #{util.classloader util.config}}
util.classloader
{:team "DevEx"
diff --git a/.github/file-paths.yaml b/.github/file-paths.yaml
index 29081345280..bda9dc4b468 100644
--- a/.github/file-paths.yaml
+++ b/.github/file-paths.yaml
@@ -358,6 +358,7 @@ openapi:
- "src/metabase/api/**"
- "src/metabase/api_routes/**"
- "src/metabase/*_rest/api.clj"
+ - "src/metabase/*/rest/api.clj"
- "src/metabase/*/api.clj"
- "src/metabase/*/api/*.clj"
- "enterprise/backend/src/metabase_enterprise/**/api.clj"
diff --git a/dev/src/dev.clj b/dev/src/dev.clj
index c3861a91a67..c5f911f7733 100644
--- a/dev/src/dev.clj
+++ b/dev/src/dev.clj
@@ -80,12 +80,12 @@
[metabase.query-processor.compile :as qp.compile]
[metabase.query-processor.timezone :as qp.timezone]
[metabase.server.core :as server]
- [metabase.server.test-handler :as server.test-handler]
[metabase.settings.core :as setting]
[metabase.sync.core :as sync]
[metabase.test :as mt]
[metabase.test-runner]
[metabase.test.data.impl :as data.impl]
+ [metabase.test.server.handler :as test.server.handler]
[metabase.util :as u]
[metabase.util.log :as log]
[methodical.core :as methodical]
@@ -180,7 +180,7 @@
(defn start!
"Start Metabase"
[]
- (server/start-web-server! (server.test-handler/test-handler))
+ (server/start-web-server! (test.server.handler/test-handler))
(init!)
(when config/is-dev?
(prune-deleted-inmem-databases!)
diff --git a/dev/src/dev/render_png.clj b/dev/src/dev/render_png.clj
index a7b57c92fe0..3c659983185 100644
--- a/dev/src/dev/render_png.clj
+++ b/dev/src/dev/render_png.clj
@@ -9,13 +9,13 @@
[metabase.channel.email.result-attachment :as email.result-attachment]
[metabase.channel.render.core :as channel.render]
[metabase.channel.render.image-bundle :as img]
+ [metabase.channel.render.markdown :as markdown]
[metabase.channel.render.png :as png]
[metabase.channel.render.style :as style]
[metabase.notification.payload.core :as notification.payload]
[metabase.query-processor.core :as qp]
[metabase.system.core :as system]
[metabase.test :as mt]
- [metabase.util.markdown :as markdown]
[toucan2.core :as t2])
(:import
(java.io File)))
diff --git a/docs/developers-guide/driver-changelog.md b/docs/developers-guide/driver-changelog.md
index 9a20bce4b02..e50847321bf 100644
--- a/docs/developers-guide/driver-changelog.md
+++ b/docs/developers-guide/driver-changelog.md
@@ -12,6 +12,30 @@ title: Driver interface changelog
## Metabase 0.64.0
+- Date and time functions that depended on the `start-of-week` setting now take a `time-config` map as their first
+ argument. Drivers should call the `driver-api` versions instead, which take the old arguments and fill in the
+ instance's time config:
+
+ - `metabase.util.date-2/extract` → `driver-api/date-extract`
+ - `metabase.util.date-2/truncate` → `driver-api/date-truncate`
+ - `metabase.util.date-2/bucket` → `driver-api/date-bucket`
+ - `metabase.util.date-2/range` → `driver-api/date-range`
+ - `metabase.util.date-2/comparison-range` → `driver-api/date-comparison-range`
+ - `metabase.lib.core/desugar-filter-clause` → `driver-api/desugar-filter-clause`
+ - `metabase.lib.core/negate-boolean-expression` → `driver-api/negate-boolean-expression`
+
+ Drivers that call the `driver-api` versions will not need to change if the time config gains more options, or these
+ functions gain more arguments.
+
+ The `metabase.util.date-2` arities without `t`, which used the current time, have been removed.
+ With a config argument in front, a call written for the old signature, such as `(truncate t :day)`, would have
+ quietly matched one of them and used the current time instead of `t`.
+ Without them it fails with an arity error, and so will calls that miss any argument added later.
+ Callers of those arities should pass the current time as `t`, e.g. `(t/zoned-date-time)`.
+
+ The `:first-day-of-week`, `:first-week-of-year`, and `:week-of-year` methods of `metabase.util.date-2/adjuster` now
+ take the start of the week as their last argument, e.g. `(driver-api/start-of-week)`.
+
- `metabase.driver.sql.normalize/default-schema` now takes the database as well as the driver:
`[driver database]`. The schema an unqualified table reference resolves to is a property of the connection for a
driver that opens a database where others have a default schema — ClickHouse now answers with the database its
diff --git a/enterprise/backend/src/metabase_enterprise/sso/api/routes.clj b/enterprise/backend/src/metabase_enterprise/sso/api/routes.clj
index 9476222f488..e10906cdc35 100644
--- a/enterprise/backend/src/metabase_enterprise/sso/api/routes.clj
+++ b/enterprise/backend/src/metabase_enterprise/sso/api/routes.clj
@@ -16,7 +16,7 @@
;;
;; TODO -- we need to feature-flag this based on the `:sso-` feature flags
-;; NOTE: there is a wrapper in metabase.server.auth-wrapper to ensure that oss versions give nice error
+;; NOTE: there is a wrapper in metabase.sso.auth-wrapper to ensure that oss versions give nice error
;; messages. These must be kept in sync manually since compojure are opaque functions.
(def ^{:arglists '([request respond raise])} routes
"Ring routes for auth (SAML) API endpoints."
diff --git a/frontend/src/metabase-lib/query/temporal_bucket.ts b/frontend/src/metabase-lib/query/temporal_bucket.ts
index ad1de659092..cedb760c44e 100644
--- a/frontend/src/metabase-lib/query/temporal_bucket.ts
+++ b/frontend/src/metabase-lib/query/temporal_bucket.ts
@@ -1,5 +1,5 @@
import * as ML from "cljs/metabase.lib.js";
-import type { TemporalUnit } from "metabase-types/api";
+import type { DayOfWeekId, TemporalUnit } from "metabase-types/api";
import { displayInfo } from "./metadata";
import type { Bucket, Clause, ColumnMetadata, Query } from "./types";
@@ -78,15 +78,23 @@ type RelativeDateRangeFormatOpts = {
includeCurrent?: boolean;
};
-export function formatRelativeDateRange({
- value,
- unit,
- offsetValue,
- offsetUnit,
- includeCurrent,
-}: RelativeDateRangeFormatOpts): string {
+export type TimeConfig = {
+ "start-of-week": DayOfWeekId;
+};
+
+export function formatRelativeDateRange(
+ timeConfig: TimeConfig,
+ {
+ value,
+ unit,
+ offsetValue,
+ offsetUnit,
+ includeCurrent,
+ }: RelativeDateRangeFormatOpts,
+): string {
return ML.format_relative_date_range(value, unit, offsetValue, offsetUnit, {
"include-current": includeCurrent,
+ ...timeConfig,
});
}
diff --git a/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/CurrentDatePicker/CurrentDatePicker.tsx b/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/CurrentDatePicker/CurrentDatePicker.tsx
index 200997a7216..79b49f51f82 100644
--- a/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/CurrentDatePicker/CurrentDatePicker.tsx
+++ b/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/CurrentDatePicker/CurrentDatePicker.tsx
@@ -8,6 +8,7 @@ import type {
import { Button, Group, Stack, Tooltip } from "metabase/ui";
import * as Lib from "metabase-lib";
+import { useTimeConfig } from "../use-time-config";
import { formatDateRange } from "../utils";
import { getCurrentValue, getUnitGroups } from "./utils";
@@ -23,10 +24,11 @@ export function CurrentDatePicker({
availableUnits,
onChange,
}: CurrentDatePickerProps) {
+ const timeConfig = useTimeConfig();
const unitGroups = getUnitGroups(availableUnits);
const getTooltipLabel = (unit: DatePickerTruncationUnit) => {
- return formatDateRange(getCurrentValue(unit));
+ return formatDateRange(timeConfig, getCurrentValue(unit));
};
const handleClick = (unit: DatePickerTruncationUnit) => {
diff --git a/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/CurrentDatePicker/CurrentDatePicker.unit.spec.tsx b/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/CurrentDatePicker/CurrentDatePicker.unit.spec.tsx
index 22e6a26e597..a79eff4e204 100644
--- a/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/CurrentDatePicker/CurrentDatePicker.unit.spec.tsx
+++ b/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/CurrentDatePicker/CurrentDatePicker.unit.spec.tsx
@@ -1,11 +1,13 @@
import _userEvent from "@testing-library/user-event";
+import { createMockSettingsState } from "__support__/state";
import { renderWithProviders, screen } from "__support__/ui";
import { DATE_PICKER_UNITS } from "metabase/querying/common/constants";
import type {
DatePickerUnit,
RelativeDatePickerValue,
} from "metabase/querying/common/types";
+import type { DayOfWeekId } from "metabase-types/api";
import { CurrentDatePicker } from "./CurrentDatePicker";
@@ -18,6 +20,8 @@ const DEFAULT_VALUE: RelativeDatePickerValue = {
interface SetupOpts {
value?: RelativeDatePickerValue;
availableUnits?: DatePickerUnit[];
+ settingsLoaded?: boolean;
+ startOfWeek?: DayOfWeekId;
}
const userEvent = _userEvent.setup({
@@ -27,8 +31,15 @@ const userEvent = _userEvent.setup({
function setup({
value = DEFAULT_VALUE,
availableUnits = DATE_PICKER_UNITS,
+ settingsLoaded = true,
+ startOfWeek = "sunday",
}: SetupOpts = {}) {
const onChange = jest.fn();
+ const settings = createMockSettingsState({ "start-of-week": startOfWeek });
+
+ if (!settingsLoaded) {
+ Reflect.deleteProperty(settings.values, "start-of-week");
+ }
renderWithProviders(
<CurrentDatePicker
@@ -36,6 +47,11 @@ function setup({
availableUnits={availableUnits}
onChange={onChange}
/>,
+ {
+ storeInitialState: {
+ settings,
+ },
+ },
);
return { onChange };
@@ -60,7 +76,17 @@ describe("CurrentDatePicker", () => {
});
it("should show the date range for the selected interval", async () => {
- setup();
+ setup({ startOfWeek: "monday" });
+
+ await userEvent.hover(screen.getByText("Week"));
+
+ expect(
+ await screen.findByText("Right now, this is Dec 30, 2019 – Jan 5, 2020"),
+ ).toBeInTheDocument();
+ });
+
+ it("should use Sunday while settings are loading", async () => {
+ setup({ settingsLoaded: false });
await userEvent.hover(screen.getByText("Week"));
diff --git a/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/DateIntervalPicker/DateIntervalPicker.tsx b/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/DateIntervalPicker/DateIntervalPicker.tsx
index 6b2243244a5..9132a0b429e 100644
--- a/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/DateIntervalPicker/DateIntervalPicker.tsx
+++ b/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/DateIntervalPicker/DateIntervalPicker.tsx
@@ -20,6 +20,7 @@ import { NumberInputWithFallbackValue } from "../../NumberInputWithFallbackValue
import type { DatePickerSubmitButtonProps } from "../../types";
import { renderDefaultSubmitButton } from "../../utils";
import { IncludeCurrentSwitch } from "../IncludeCurrentSwitch";
+import { useTimeConfig } from "../use-time-config";
import {
formatDateRange,
getInterval,
@@ -49,10 +50,11 @@ export function DateIntervalPicker({
onChange,
onSubmit,
}: DateIntervalPickerProps) {
+ const timeConfig = useTimeConfig();
const interval = getInterval(value);
const unitOptions = getUnitOptions(value, availableUnits);
- const dateRangeText = formatDateRange(value);
- const outOfBounds = isOutOfBounds(value, minDate, maxDate);
+ const dateRangeText = formatDateRange(timeConfig, value);
+ const outOfBounds = isOutOfBounds(timeConfig, value, minDate, maxDate);
const handleIntervalChange = (inputValue: number | string) => {
if (typeof inputValue === "number") {
diff --git a/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/DateOffsetIntervalPicker/DateOffsetIntervalPicker.tsx b/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/DateOffsetIntervalPicker/DateOffsetIntervalPicker.tsx
index 213806651a7..aa7937198df 100644
--- a/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/DateOffsetIntervalPicker/DateOffsetIntervalPicker.tsx
+++ b/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/DateOffsetIntervalPicker/DateOffsetIntervalPicker.tsx
@@ -10,6 +10,7 @@ import { Box, Button, Divider, Group, Icon, Select, Text } from "metabase/ui";
import { NumberInputWithFallbackValue } from "../../NumberInputWithFallbackValue";
import type { DatePickerSubmitButtonProps } from "../../types";
import { renderDefaultSubmitButton } from "../../utils";
+import { useTimeConfig } from "../use-time-config";
import {
formatDateRange,
getInterval,
@@ -48,13 +49,14 @@ export function DateOffsetIntervalPicker({
onChange,
onSubmit,
}: DateOffsetIntervalPickerProps) {
+ const timeConfig = useTimeConfig();
const interval = getInterval(value);
const unitOptions = getUnitOptions(value, availableUnits);
const offsetInterval = getOffsetInterval(value);
const offsetUnitOptions = getOffsetUnitOptions(value, availableUnits);
const directionText = getDirectionText(value);
- const dateRangeText = formatDateRange(value);
- const outOfBounds = isOutOfBounds(value, minDate, maxDate);
+ const dateRangeText = formatDateRange(timeConfig, value);
+ const outOfBounds = isOutOfBounds(timeConfig, value, minDate, maxDate);
const handleIntervalChange = (inputValue: number | string) => {
if (typeof inputValue === "number") {
diff --git a/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/RelativeDatePicker.unit.spec.tsx b/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/RelativeDatePicker.unit.spec.tsx
index 6dece5b5f2c..398ea6944fd 100644
--- a/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/RelativeDatePicker.unit.spec.tsx
+++ b/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/RelativeDatePicker.unit.spec.tsx
@@ -1,5 +1,6 @@
import userEvent from "@testing-library/user-event";
+import { createMockSettingsState } from "__support__/state";
import { renderWithProviders, screen } from "__support__/ui";
import {
DATE_PICKER_DIRECTIONS,
@@ -40,6 +41,11 @@ function setup({
onChange={onChange}
onBack={onBack}
/>,
+ {
+ storeInitialState: {
+ settings: createMockSettingsState({ "start-of-week": "sunday" }),
+ },
+ },
);
return { onChange, onBack };
diff --git a/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/use-time-config.ts b/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/use-time-config.ts
new file mode 100644
index 00000000000..8b6849590da
--- /dev/null
+++ b/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/use-time-config.ts
@@ -0,0 +1,12 @@
+import { useSetting } from "metabase/settings";
+import type { TimeConfig } from "metabase-lib";
+
+const DEFAULT_START_OF_WEEK: TimeConfig["start-of-week"] = "sunday";
+
+export function useTimeConfig(): TimeConfig {
+ const startOfWeek = useSetting("start-of-week");
+
+ return {
+ "start-of-week": startOfWeek ?? DEFAULT_START_OF_WEEK,
+ };
+}
diff --git a/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/utils.ts b/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/utils.ts
index 15057ea32f3..97ac5f1767c 100644
--- a/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/utils.ts
+++ b/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/utils.ts
@@ -1,4 +1,4 @@
-import { dayjs } from "metabase/dayjs";
+import { type Dayjs, dayjs } from "metabase/dayjs";
import { DATE_PICKER_TRUNCATION_UNITS } from "metabase/querying/common/constants";
import type {
DatePickerTruncationUnit,
@@ -8,6 +8,7 @@ import type {
RelativeIntervalDirection,
} from "metabase/querying/common/types";
import * as Lib from "metabase-lib";
+import type { DayOfWeekId } from "metabase-types/api";
import { DEFAULT_VALUE, TABS } from "./constants";
@@ -120,14 +121,11 @@ export function getUnitOptions(
}));
}
-export function formatDateRange({
- value,
- unit,
- offsetValue,
- offsetUnit,
- options,
-}: RelativeDatePickerValue): string {
- return Lib.formatRelativeDateRange({
+export function formatDateRange(
+ timeConfig: Lib.TimeConfig,
+ { value, unit, offsetValue, offsetUnit, options }: RelativeDatePickerValue,
+): string {
+ return Lib.formatRelativeDateRange(timeConfig, {
value,
unit,
offsetValue,
@@ -137,18 +135,63 @@ export function formatDateRange({
}
export function isOutOfBounds(
+ timeConfig: Lib.TimeConfig,
{ value, unit, offsetValue, offsetUnit }: RelativeDatePickerValue,
minDate?: Date,
maxDate?: Date,
): boolean {
const base = dayjs().add(offsetValue ?? 0, offsetUnit ?? "day");
- const start = base.add(Math.min(value, 0), unit).startOf(unit).toDate();
- const end = base.add(Math.max(value, 0), unit).endOf(unit).toDate();
+ const start = startOfUnit(
+ timeConfig,
+ base.add(Math.min(value, 0), unit),
+ unit,
+ ).toDate();
+ const end = endOfUnit(
+ timeConfig,
+ base.add(Math.max(value, 0), unit),
+ unit,
+ ).toDate();
return (
(minDate != null && start < minDate) || (maxDate != null && end > maxDate)
);
}
+const DAY_OF_WEEK_INDEX: Record<DayOfWeekId, number> = {
+ sunday: 0,
+ monday: 1,
+ tuesday: 2,
+ wednesday: 3,
+ thursday: 4,
+ friday: 5,
+ saturday: 6,
+};
+
+function startOfUnit(
+ timeConfig: Lib.TimeConfig,
+ date: Dayjs,
+ unit: DatePickerTruncationUnit,
+): Dayjs {
+ if (unit !== "week") {
+ return date.startOf(unit);
+ }
+
+ const firstDay = DAY_OF_WEEK_INDEX[timeConfig["start-of-week"]];
+ const daysSinceFirstDay = (date.day() - firstDay + 7) % 7;
+ return date.subtract(daysSinceFirstDay, "day").startOf("day");
+}
+
+function endOfUnit(
+ timeConfig: Lib.TimeConfig,
+ date: Dayjs,
+ unit: DatePickerTruncationUnit,
+): Dayjs {
+ return unit === "week"
+ ? startOfUnit(timeConfig, date, unit)
+ .add(1, "week")
+ .subtract(1, "millisecond")
+ : date.endOf(unit);
+}
+
export function getDefaultValue(
availableDirections: RelativeIntervalDirection[],
) {
diff --git a/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/utils.unit.spec.ts b/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/utils.unit.spec.ts
index 5c67f42c88a..d392016c806 100644
--- a/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/utils.unit.spec.ts
+++ b/frontend/src/metabase/querying/common/components/DatePicker/RelativeDatePicker/utils.unit.spec.ts
@@ -3,6 +3,7 @@ import type {
RelativeDatePickerValue,
RelativeIntervalDirection,
} from "metabase/querying/common/types";
+import type { TimeConfig } from "metabase-lib";
import { CURRENT_TAB, LAST_TAB, NEXT_TAB } from "./constants";
import type { Tab } from "./types";
@@ -211,6 +212,7 @@ describe("getAvailableTabs", () => {
});
describe("isOutOfBounds", () => {
+ const timeConfig: TimeConfig = { "start-of-week": "sunday" };
const past = (days: number): RelativeDatePickerValue => ({
type: "relative",
value: -days,
@@ -228,35 +230,72 @@ describe("isOutOfBounds", () => {
});
it("is in bounds when no min or max is set", () => {
- expect(isOutOfBounds(past(365))).toBe(false);
+ expect(isOutOfBounds(timeConfig, past(365))).toBe(false);
});
it("is out of bounds when a past range starts before minDate", () => {
- expect(isOutOfBounds(past(365), new Date(2026, 0, 1))).toBe(true);
+ expect(isOutOfBounds(timeConfig, past(365), new Date(2026, 0, 1))).toBe(
+ true,
+ );
});
it("is in bounds when a past range starts on or after minDate", () => {
- expect(isOutOfBounds(past(7), new Date(2026, 0, 1))).toBe(false);
+ expect(isOutOfBounds(timeConfig, past(7), new Date(2026, 0, 1))).toBe(
+ false,
+ );
});
it("is out of bounds when a future range ends after maxDate", () => {
- expect(isOutOfBounds(future(365), undefined, new Date(2026, 1, 1))).toBe(
- true,
- );
+ expect(
+ isOutOfBounds(timeConfig, future(365), undefined, new Date(2026, 1, 1)),
+ ).toBe(true);
});
it("is in bounds when a future range ends on or before maxDate", () => {
- expect(isOutOfBounds(future(7), undefined, new Date(2026, 2, 1))).toBe(
- false,
- );
+ expect(
+ isOutOfBounds(timeConfig, future(7), undefined, new Date(2026, 2, 1)),
+ ).toBe(false);
});
it("respects offsetValue and offsetUnit when checking minDate", () => {
expect(
isOutOfBounds(
+ timeConfig,
{ ...past(7), offsetValue: -365, offsetUnit: "day" },
new Date(2026, 0, 1),
),
).toBe(true);
});
+
+ it("uses the configured start of week", () => {
+ const currentWeek: RelativeDatePickerValue = {
+ type: "relative",
+ value: 0,
+ unit: "week",
+ };
+
+ expect(
+ isOutOfBounds(
+ { "start-of-week": "monday" },
+ currentWeek,
+ new Date(2026, 0, 26),
+ ),
+ ).toBe(false);
+ expect(isOutOfBounds(timeConfig, currentWeek, new Date(2026, 0, 26))).toBe(
+ true,
+ );
+
+ const sundayWeekEnd = new Date(2026, 0, 31, 23, 59, 59, 999);
+ expect(
+ isOutOfBounds(
+ { "start-of-week": "monday" },
+ currentWeek,
+ undefined,
+ sundayWeekEnd,
+ ),
+ ).toBe(true);
+ expect(
+ isOutOfBounds(timeConfig, currentWeek, undefined, sundayWeekEnd),
+ ).toBe(false);
+ });
});
diff --git a/mage/src/mage/modules.clj b/mage/src/mage/modules.clj
index 96ca49a6508..1f9dfe1ba78 100644
--- a/mage/src/mage/modules.clj
+++ b/mage/src/mage/modules.clj
@@ -198,6 +198,7 @@
system
task
task.history
+ task.secure-delegate
tiles
timeline
tracing
diff --git a/modules/drivers/mongo/src/metabase/driver/mongo/parameters.clj b/modules/drivers/mongo/src/metabase/driver/mongo/parameters.clj
index 7a6c0ac872c..46e2be5928a 100644
--- a/modules/drivers/mongo/src/metabase/driver/mongo/parameters.clj
+++ b/modules/drivers/mongo/src/metabase/driver/mongo/parameters.clj
@@ -158,7 +158,7 @@
;; since that desugars to
;;
;; [:or [:= <field> 1] ...].
- lib/desugar-filter-clause
+ driver-api/desugar-filter-clause
driver-api/wrap-value-literals-in-mbql5
(->> (mongo.qp/compile-filter query stage-number))
json/encode)]
diff --git a/modules/drivers/mongo/src/metabase/driver/mongo/query_processor.clj b/modules/drivers/mongo/src/metabase/driver/mongo/query_processor.clj
index d054b561f48..6938f7cc15f 100644
--- a/modules/drivers/mongo/src/metabase/driver/mongo/query_processor.clj
+++ b/modules/drivers/mongo/src/metabase/driver/mongo/query_processor.clj
@@ -719,9 +719,9 @@ function(bin) {
java.time.ZonedDateTime (t/offset-date-time t report-zone)))
t (normalize-t t)]
(letfn [(extract [unit]
- (u.date/extract t unit))
+ (driver-api/date-extract t unit))
(bucket [unit]
- ($date-from-string (u.date/bucket t unit)))]
+ ($date-from-string (driver-api/date-bucket t unit)))]
(case (or unit :default)
:default ($date-from-string t)
:minute (bucket :minute)
@@ -759,7 +759,7 @@ function(bin) {
t
(-> t
(u.date/add unit amount)
- (u.date/bucket unit)))))))
+ (driver-api/date-bucket unit)))))))
;;; ---------------------------------------------------- functions ---------------------------------------------------
@@ -1308,7 +1308,7 @@ function(bin) {
(mu/defmethod negate :default :- ::lib.schema.mbql-clause/clause
[expr :- ::lib.schema.expression/boolean]
- (lib/negate-boolean-expression expr))
+ (driver-api/negate-boolean-expression expr))
(mu/defmethod negate :and :- ::lib.schema.mbql-clause/clause
[[_ opts & subclauses] :- :mbql.clause/and]
diff --git a/src/metabase/agent_lib/representations/repair.clj b/src/metabase/agent_lib/representations/repair.clj
index b24b3cde08c..0662fe8c3a5 100644
--- a/src/metabase/agent_lib/representations/repair.clj
+++ b/src/metabase/agent_lib/representations/repair.clj
@@ -30,6 +30,7 @@
[clojure.string :as str]
[clojure.walk :as walk]
[metabase.agent-lib.representations.resolve :as repr.resolve]
+ [metabase.lib-be.core :as lib-be]
[metabase.lib.core :as lib]
[metabase.lib.expression :as lib.expression]
[metabase.lib.metadata.protocols :as lib.metadata.protocols]
@@ -1096,7 +1097,7 @@
(if (= "default" unit)
literal
(let [parsed (u.date/parse literal)
- t (u.date/truncate parsed (keyword unit))
+ t (u.date/truncate (lib-be/time-config) parsed (keyword unit))
;; a `Z`-suffixed literal parses to a `ZonedDateTime`, which renders back as
;; `2025-06-01T00:00Z[UTC]` - that would reach the `/question#` hash and the LLM-facing
;; export verbatim, so a rewrite that is not ISO is dropped rather than emitted
diff --git a/src/metabase/analytics/settings.clj b/src/metabase/analytics/settings.clj
index 495f1a0ca20..87180e941c5 100644
--- a/src/metabase/analytics/settings.clj
+++ b/src/metabase/analytics/settings.clj
@@ -5,6 +5,7 @@
[metabase.config.core :as config]
[metabase.settings.core :as setting :refer [defsetting]]
[metabase.util.date-2 :as u.date]
+ [metabase.util.experiment :as experiment]
[metabase.util.i18n :refer [deferred-tru]]))
(defsetting analytics-uuid
@@ -118,3 +119,16 @@
:visibility :admin
:export? true
:feature :audit-app)
+
+(defsetting experiments-enabled
+ (deferred-tru "Enable or disable all code experiments. When disabled, only the production code path runs.")
+ :type :boolean
+ :default false
+ :doc false
+ :visibility :admin
+ :export? false
+ :audit :getter)
+
+;; Wire the setting into the experiment machinery, which sits below the settings framework in the module
+;; graph. The fn is called on every experiment invocation, so toggling the setting takes effect immediately.
+(experiment/set-experiments-enabled-fn! experiments-enabled)
diff --git a/src/metabase/api_routes/routes.clj b/src/metabase/api_routes/routes.clj
index a30b83e4bf3..a07ac5d399b 100644
--- a/src/metabase/api_routes/routes.clj
+++ b/src/metabase/api_routes/routes.clj
@@ -57,7 +57,7 @@
[metabase.query-processor.api]
[metabase.revisions.api]
[metabase.search.api]
- [metabase.segments.api]
+ [metabase.segments.rest.api]
[metabase.session.api]
[metabase.settings-rest.api]
[metabase.setup-rest.api]
@@ -119,7 +119,7 @@
metabase.public-sharing-rest.api/keep-me
metabase.query-processor.api/keep-me
metabase.revisions.api/keep-me
- metabase.segments.api/keep-me
+ metabase.segments.rest.api/keep-me
metabase.settings-rest.api/keep-me
metabase.setup-rest.api/keep-me
metabase.task-history.api/keep-me
@@ -242,7 +242,7 @@
"/pulse" metabase.pulse.api/pulse-routes
"/revision" (+auth 'metabase.revisions.api)
"/search" (+auth metabase.search.api/routes)
- "/segment" (+auth 'metabase.segments.api)
+ "/segment" (+auth 'metabase.segments.rest.api)
"/session" metabase.session.api/routes
"/setting" (+auth 'metabase.settings-rest.api)
"/setup" 'metabase.setup-rest.api
diff --git a/src/metabase/app_db/custom_migrations/util.clj b/src/metabase/app_db/custom_migrations/util.clj
index 14ead562c48..58676df20ae 100644
--- a/src/metabase/app_db/custom_migrations/util.clj
+++ b/src/metabase/app_db/custom_migrations/util.clj
@@ -2,13 +2,13 @@
(:require
[clojurewerkz.quartzite.scheduler :as qs]
[metabase.app-db.connection :as mdb.connection]
- [metabase.classloader.core :as classloader]
- [metabase.task.bootstrap]))
+ [metabase.app-db.quartz]
+ [metabase.classloader.core :as classloader]))
(set! *warn-on-reflection* true)
(defn- set-jdbc-backend-properties! []
- (metabase.task.bootstrap/set-jdbc-backend-properties! (mdb.connection/db-type)))
+ (metabase.app-db.quartz/set-jdbc-backend-properties! (mdb.connection/db-type)))
#_{:clj-kondo/ignore [:metabase/discourage-dynamic-vars]}
(def ^:dynamic *allow-temp-scheduling*
diff --git a/src/metabase/app_db/quartz.clj b/src/metabase/app_db/quartz.clj
index 4fc65070396..ee14a004a25 100644
--- a/src/metabase/app_db/quartz.clj
+++ b/src/metabase/app_db/quartz.clj
@@ -1,11 +1,24 @@
(ns metabase.app-db.quartz
- "Quartz's `ConnectionProvider` for the application DB."
+ "Quartz JDBC plumbing over the application DB: a `ConnectionProvider` backed by our connection pool,
+ a `ClassLoadHelper` that uses our classloader, and the JDBC backend system properties."
(:require
[metabase.app-db.connection :as mdb.connection]
- [metabase.task.bootstrap :as task.bootstrap]))
+ [metabase.classloader.core :as classloader]
+ [metabase.task.secure-delegate.core :as secure-delegate]
+ [metabase.util.log :as log]))
(set! *warn-on-reflection* true)
+;; Optional interceptor for wrapping JDBC connections before Quartz uses them.
+;; Set by tracing.quartz to add SQL-level tracing. nil means no interception.
+(defonce ^:private connection-interceptor (atom nil))
+
+(defn set-connection-interceptor!
+ "Set an optional function to wrap JDBC connections before Quartz uses them.
+ Called by tracing.quartz to add SQL-level tracing. Pass nil to remove."
+ [f]
+ (reset! connection-interceptor f))
+
;; Custom `ConnectionProvider` implementation that uses a dedicated connection pool for the application DB to provide
;; connections.
(defrecord ^:private ConnectionProvider []
@@ -22,8 +35,56 @@
;;
;; the pool is separate from the main application DB pool so that a Quartz operation triggered by a thread inside
;; a `with-transaction` block can't deadlock when application code has saturated the main pool.
- (task.bootstrap/intercept-connection (.getConnection (mdb.connection/quartz-data-source))))
+ (let [conn (.getConnection (mdb.connection/quartz-data-source))]
+ (if-let [interceptor @connection-interceptor]
+ (interceptor conn)
+ conn)))
(shutdown [_]))
(when-not *compile-files*
(System/setProperty "org.quartz.dataSource.db.connectionProvider.class" (.getName ConnectionProvider)))
+
+(defn- load-class ^Class [^String class-name]
+ (Class/forName class-name true (classloader/the-classloader)))
+
+(defrecord ^:private ClassLoadHelper []
+ org.quartz.spi.ClassLoadHelper
+ (initialize [_])
+ (getClassLoader [_]
+ (classloader/the-classloader))
+ (loadClass [_ class-name]
+ (load-class class-name))
+ (loadClass [_ class-name _]
+ (load-class class-name)))
+
+(when-not *compile-files*
+ (System/setProperty "org.quartz.scheduler.classLoadHelper.class" (.getName ClassLoadHelper)))
+
+(defonce ^:private jdbc-property-setters
+ ;; Fns of the db-type that [[set-jdbc-backend-properties!]] runs right before the scheduler initializes.
+ ;; They let a module that depends on `app-db`, such as `mq`, install its own Quartz `DriverDelegate`.
+ (atom []))
+
+(defn register-jdbc-property-setter!
+ "Register `f`, a fn of the app-db `db-type`, to run when Quartz's JDBC backend properties are set.
+ Setters run in registration order, just before the scheduler initializes."
+ [f]
+ (swap! jdbc-property-setters conj f))
+
+(defn set-jdbc-backend-properties!
+ "Set the appropriate system properties needed so Quartz can connect to the JDBC backend. (Since we don't know our DB
+ connection properties ahead of time, we'll need to set these at runtime rather than Setting them in the
+ `quartz.properties` file.)
+
+ Installs Metabase's per-DB `DriverDelegate` (see [[metabase.task.secure-delegate.core]]): a
+ `StdJDBCDelegate`/`PostgreSQLDelegate` subclass that reads BLOB columns through a class allow-list, so
+ Quartz reconstructs only the plain-data classes Metabase's job data is made of. Then runs any setters
+ registered via [[register-jdbc-property-setter!]]. A registered setter that throws is logged and
+ skipped so the scheduler still gets a working delegate."
+ [db-type]
+ (secure-delegate/install! db-type)
+ (doseq [setter @jdbc-property-setters]
+ (try
+ (setter db-type)
+ (catch Throwable t
+ (log/warnf "A registered Quartz JDBC property setter failed; continuing: %s" (ex-message t))))))
diff --git a/src/metabase/channel/impl/email.clj b/src/metabase/channel/impl/email.clj
index 06f035db926..ed0248421e2 100644
--- a/src/metabase/channel/impl/email.clj
+++ b/src/metabase/channel/impl/email.clj
@@ -17,6 +17,7 @@
[metabase.channel.models.channel :as models.channel]
[metabase.channel.params :as channel.params]
[metabase.channel.render.core :as channel.render]
+ [metabase.channel.render.markdown :as markdown]
[metabase.channel.render.style :as style]
[metabase.channel.render.util :as render.util]
[metabase.channel.settings :as channel.settings]
@@ -30,7 +31,6 @@
[metabase.util.log :as log]
[metabase.util.malli :as mu]
[metabase.util.malli.schema :as ms]
- [metabase.util.markdown :as markdown]
[metabase.util.ui-logic :as ui-logic]
[ring.util.codec :as codec])
(:import
diff --git a/src/metabase/channel/impl/slack.clj b/src/metabase/channel/impl/slack.clj
index bacd169cda7..d05a1c967fb 100644
--- a/src/metabase/channel/impl/slack.clj
+++ b/src/metabase/channel/impl/slack.clj
@@ -5,6 +5,7 @@
[metabase.channel.core :as channel]
[metabase.channel.impl.util :as impl.util]
[metabase.channel.render.core :as channel.render]
+ [metabase.channel.render.markdown :as markdown]
[metabase.channel.shared :as channel.shared]
[metabase.channel.slack :as slack]
[metabase.channel.urls :as urls]
@@ -13,8 +14,7 @@
[metabase.system.core :as system]
[metabase.util.i18n :refer [tru]]
[metabase.util.log :as log]
- [metabase.util.malli :as mu]
- [metabase.util.markdown :as markdown]))
+ [metabase.util.malli :as mu]))
(defn- notification-recipient->channel
"Returns the Slack channel target for a raw-value notification recipient.
diff --git a/src/metabase/channel/render/card.clj b/src/metabase/channel/render/card.clj
index 2aa80bb00b4..306b859f9ac 100644
--- a/src/metabase/channel/render/card.clj
+++ b/src/metabase/channel/render/card.clj
@@ -4,6 +4,7 @@
[metabase.channel.db :as channel.db]
[metabase.channel.render.body :as body]
[metabase.channel.render.image-bundle :as image-bundle]
+ [metabase.channel.render.markdown :as markdown]
[metabase.channel.render.png :as png]
[metabase.channel.render.style :as style]
[metabase.channel.render.util :as render.util]
@@ -15,8 +16,7 @@
[metabase.util.i18n :refer [tru]]
[metabase.util.log :as log]
[metabase.util.malli :as mu]
- [metabase.util.malli.registry :as mr]
- [metabase.util.markdown :as markdown]))
+ [metabase.util.malli.registry :as mr]))
(defn- card-href
[card]
diff --git a/src/metabase/util/markdown.clj b/src/metabase/channel/render/markdown.clj
similarity index 99%
rename from src/metabase/util/markdown.clj
rename to src/metabase/channel/render/markdown.clj
index c93abb4572f..e9a9345787d 100644
--- a/src/metabase/util/markdown.clj
+++ b/src/metabase/channel/render/markdown.clj
@@ -1,4 +1,4 @@
-(ns metabase.util.markdown
+(ns metabase.channel.render.markdown
(:require
[clojure.edn :as edn]
[clojure.java.io :as io]
diff --git a/src/metabase/channel/render/preview.clj b/src/metabase/channel/render/preview.clj
index 01684e60ec5..b8910184a3f 100644
--- a/src/metabase/channel/render/preview.clj
+++ b/src/metabase/channel/render/preview.clj
@@ -13,12 +13,12 @@
[metabase.channel.email.result-attachment :as email.result-attachment]
[metabase.channel.render.card :as render.card]
[metabase.channel.render.image-bundle :as img]
+ [metabase.channel.render.markdown :as markdown]
[metabase.channel.render.png :as png]
[metabase.channel.render.style :as style]
[metabase.notification.payload.core :as notification.payload]
[metabase.system.core :as system]
- [metabase.util :as u]
- [metabase.util.markdown :as markdown]))
+ [metabase.util :as u]))
(set! *warn-on-reflection* true)
diff --git a/src/metabase/cloud_migration/models/cloud_migration.clj b/src/metabase/cloud_migration/models/cloud_migration.clj
index 44eebca7c8e..4220b0c0fbe 100644
--- a/src/metabase/cloud_migration/models/cloud_migration.clj
+++ b/src/metabase/cloud_migration/models/cloud_migration.clj
@@ -5,6 +5,7 @@
[clojure.java.io :as io]
[clojure.set :as set]
[metabase.app-db.core :as mdb]
+ [metabase.app-db.quartz :as app-db.quartz]
[metabase.cloud-migration.db :as cloud-migration.db]
[metabase.cloud-migration.settings :as cloud-migration.settings]
[metabase.cmd.copy :as copy]
@@ -13,7 +14,6 @@
[metabase.models.interface :as mi]
[metabase.settings.core :as setting]
[metabase.store-api.core :as store-api]
- [metabase.task.bootstrap :as task.bootstrap]
[metabase.task.core :as task]
[metabase.util :as u]
[metabase.util.i18n :refer [tru]]
@@ -241,7 +241,7 @@
(http/put (migration-url external_id "/uploaded"))
;; Need to restore the previous scheduler configuration because the database quartz is pointing at has changed
;; after finishing the dump to h2 migration
- (task.bootstrap/set-jdbc-backend-properties! (mdb/db-type))
+ (app-db.quartz/set-jdbc-backend-properties! (mdb/db-type))
(log/info "Restarting scheduler")
(task/start-scheduler!)
(log/info "Migration finished")
diff --git a/src/metabase/core/core.clj b/src/metabase/core/core.clj
index d0afedefc6e..b2b29b06080 100644
--- a/src/metabase/core/core.clj
+++ b/src/metabase/core/core.clj
@@ -21,8 +21,10 @@
[metabase.initialization-status.core :as init-status]
[metabase.llm.startup :as llm.startup]
[metabase.logger.core :as logger]
+ [metabase.mcp.http-handler :as mcp.http-handler]
[metabase.metrics.core :as metrics]
[metabase.notification.core :as notification]
+ [metabase.oauth-server.api :as oauth-server.api]
[metabase.permissions.core :as perms]
[metabase.plugins.core :as plugins]
[metabase.premium-features.core :refer [defenterprise]]
@@ -30,6 +32,7 @@
[metabase.server.core :as server]
[metabase.settings.core :as setting]
[metabase.setup.core :as setup]
+ [metabase.sso.auth-wrapper :as auth-wrapper]
[metabase.startup.core :as startup]
[metabase.system.core :as system]
[metabase.task.core :as task]
@@ -277,8 +280,11 @@
(log/info "Starting Metabase in STANDALONE mode")
(try
;; launch embedded webserver
- (let [server-routes (server/make-routes #'api-routes/routes)
- handler (server/make-handler server-routes)]
+ (let [server-routes (server/make-routes {:api #'api-routes/routes
+ :auth #'auth-wrapper/routes
+ :oauth #'oauth-server.api/oauth-routes
+ :well-known #'oauth-server.api/well-known-routes})
+ handler (server/make-handler server-routes #'mcp.http-handler/options)]
(server/start-web-server! handler))
;; run our initialization process
(init!)
diff --git a/src/metabase/core/init.clj b/src/metabase/core/init.clj
index 9206ae30ec2..cc7a3b88fa3 100644
--- a/src/metabase/core/init.clj
+++ b/src/metabase/core/init.clj
@@ -84,7 +84,6 @@
[metabase.usage-metadata.init]
[metabase.user-key-value.init]
[metabase.users.init]
- [metabase.util.experiment.init]
[metabase.version.init]
[metabase.view-log.init]
[metabase.warehouse-schema.init]
diff --git a/src/metabase/driver/sql/parameters/substitution.clj b/src/metabase/driver/sql/parameters/substitution.clj
index f72931068c0..3d16365eb20 100644
--- a/src/metabase/driver/sql/parameters/substitution.clj
+++ b/src/metabase/driver/sql/parameters/substitution.clj
@@ -338,7 +338,7 @@
(params.ops/operator? param-type)
(->> (assoc params :target [:dimension (field->field-ref driver field param-type value)])
params.ops/to-clause
- lib/desugar-filter-clause
+ driver-api/desugar-filter-clause
driver-api/wrap-value-literals-in-mbql5
->honeysql*
(honeysql->replacement-snippet-info driver))
@@ -346,7 +346,7 @@
(params.dates/exclusion-date-type param-type value)
(let [field-ref (field->field-ref driver field param-type value)]
(->> (params.dates/date-string->filter value field-ref)
- lib/desugar-filter-clause
+ driver-api/desugar-filter-clause
driver-api/wrap-value-literals-in-mbql5
->honeysql*
(honeysql->replacement-snippet-info driver)))
diff --git a/src/metabase/driver_api/core.clj b/src/metabase/driver_api/core.clj
index fda1f121af8..0c459f72825 100644
--- a/src/metabase/driver_api/core.clj
+++ b/src/metabase/driver_api/core.clj
@@ -55,6 +55,7 @@
[metabase.sync.util :as sync-util]
[metabase.system.core :as system]
[metabase.upload.db :as upload.db]
+ [metabase.util.date-2 :as u.date]
[metabase.util.match :as match]
[metabase.warehouse-schema.models.table :as table]
[potemkin :as p]))
@@ -188,6 +189,47 @@
to see if the query has been canceled."
[]
qp.pipeline/*canceled-chan*)
+
+;; These fill in the instance's time config, so drivers don't have to pass one.
+
+(defn desugar-filter-clause
+ "[[metabase.lib.core/desugar-filter-clause]] with this instance's time config."
+ [filter-clause]
+ (lib/desugar-filter-clause (lib-be/time-config) filter-clause))
+
+(defn negate-boolean-expression
+ "[[metabase.lib.core/negate-boolean-expression]] with this instance's time config."
+ [expression]
+ (lib/negate-boolean-expression (lib-be/time-config) expression))
+
+(defn date-extract
+ "[[metabase.util.date-2/extract]] with this instance's time config."
+ [t unit]
+ (u.date/extract (lib-be/time-config) t unit))
+
+(defn date-truncate
+ "[[metabase.util.date-2/truncate]] with this instance's time config."
+ [t unit]
+ (u.date/truncate (lib-be/time-config) t unit))
+
+(defn date-bucket
+ "[[metabase.util.date-2/bucket]] with this instance's time config."
+ [t unit]
+ (u.date/bucket (lib-be/time-config) t unit))
+
+(defn date-range
+ "[[metabase.util.date-2/range]] with this instance's time config."
+ ([t unit]
+ (u.date/range (lib-be/time-config) t unit))
+ ([t unit options]
+ (u.date/range (lib-be/time-config) t unit options)))
+
+(defn date-comparison-range
+ "[[metabase.util.date-2/comparison-range]] with this instance's time config."
+ ([t unit comparison-type]
+ (u.date/comparison-range (lib-be/time-config) t unit comparison-type))
+ ([t unit comparison-type options]
+ (u.date/comparison-range (lib-be/time-config) t unit comparison-type options)))
;; should use import-vars :rename once https://github.com/clj-kondo/clj-kondo/issues/2498 is fixed
(p/import-fn setting/get-value-of-type setting-get-value-of-type)
(p/import-fn secrets/value-as-string secret-value-as-string)
diff --git a/src/metabase/legacy_mbql/schema.cljc b/src/metabase/legacy_mbql/schema.cljc
index 7f5ba684173..a76ea436a72 100644
--- a/src/metabase/legacy_mbql/schema.cljc
+++ b/src/metabase/legacy_mbql/schema.cljc
@@ -1012,7 +1012,7 @@
:quarter-of-year [:get-quarter field])
extract-unit (if (= unit :day-of-week) :day-of-week-iso unit)]
(into [:!= extract-expr]
- (map #(u.time/extract % extract-unit))
+ (map #(u.time/extract {:start-of-week :monday} % extract-unit))
args))
&match))))
diff --git a/src/metabase/lib/date_time.cljc b/src/metabase/lib/date_time.cljc
new file mode 100644
index 00000000000..9664f415cc5
--- /dev/null
+++ b/src/metabase/lib/date_time.cljc
@@ -0,0 +1,13 @@
+(ns metabase.lib.date-time
+ "Time configuration at the query boundary. This keeps metadata settings out of lower-level date utilities."
+ (:require
+ [metabase.lib.metadata :as lib.metadata]
+ [metabase.lib.schema.common :as lib.schema.common]
+ [metabase.lib.schema.metadata :as lib.schema.metadata]
+ [metabase.util.malli :as mu]))
+
+(mu/defn config :- ::lib.schema.common/time-config
+ "Return the time config for a query or metadata provider."
+ [metadata-providerable :- ::lib.schema.metadata/metadata-providerable]
+ {:start-of-week (or (some-> (lib.metadata/setting metadata-providerable :start-of-week) keyword)
+ :sunday)})
diff --git a/src/metabase/lib/drill_thru/underlying_records.cljc b/src/metabase/lib/drill_thru/underlying_records.cljc
index ba072a33b2e..a070822cef3 100644
--- a/src/metabase/lib/drill_thru/underlying_records.cljc
+++ b/src/metabase/lib/drill_thru/underlying_records.cljc
@@ -33,6 +33,7 @@
[medley.core :as m]
[metabase.lib.aggregation :as lib.aggregation]
[metabase.lib.binning :as lib.binning]
+ [metabase.lib.date-time :as lib.date-time]
[metabase.lib.drill-thru.common :as lib.drill-thru.common]
[metabase.lib.fe-util :as lib.fe-util]
[metabase.lib.filter :as lib.filter]
@@ -182,7 +183,7 @@
:else
[(cond-> (lib.filter/= column value)
(and unit (lib.schema.temporal-bucketing/datetime-truncation-units unit))
- lib.fe-util/expand-temporal-expression)])))]
+ (#(lib.fe-util/expand-temporal-expression (lib.date-time/config query) %)))])))]
(reduce
(fn [query filter-clause]
(lib.filter/filter query stage-number filter-clause))
diff --git a/src/metabase/lib/fe_util.cljc b/src/metabase/lib/fe_util.cljc
index 64b1d671d39..996d6e467d6 100644
--- a/src/metabase/lib/fe_util.cljc
+++ b/src/metabase/lib/fe_util.cljc
@@ -6,6 +6,7 @@
[metabase.lib.aggregation :as lib.aggregation]
[metabase.lib.card :as lib.card]
[metabase.lib.common :as lib.common]
+ [metabase.lib.date-time :as lib.date-time]
[metabase.lib.dispatch :as lib.dispatch]
[metabase.lib.expression :as lib.expression]
[metabase.lib.hierarchy :as lib.hierarchy]
@@ -91,9 +92,10 @@
To mitigate that expressions are converted to `:between` form which is handled correctly by filter picker. For more
info on the issue see the comment [https://github.com/metabase/metabase/issues/12496#issuecomment-1629317661].
This functionality is backend approach to \"smaller solution\"."
- [[_operator options column-arg dt-arg :as _expression-clause]]
+ [time-config [_operator options column-arg dt-arg :as _expression-clause]]
(let [temporal-unit (:temporal-unit (lib.options/options column-arg))
- interval (u.time/to-range (u.time/coerce-to-timestamp dt-arg) {:unit temporal-unit :n 1})
+ interval (u.time/to-range (u.time/coerce-to-timestamp dt-arg)
+ (assoc time-config :unit temporal-unit, :n 1))
formatter (if (contains? expandable-time-units temporal-unit)
fmt.date/datetime->iso-string
fmt.date/date->iso-string)]
@@ -147,7 +149,8 @@
[query stage-number clause]
((get-method expression-parts-method :default)
query stage-number (cond-> clause
- (expandable-temporal-expression? clause) expand-temporal-expression)))
+ (expandable-temporal-expression? clause)
+ (#(expand-temporal-expression (lib.date-time/config query) %)))))
(defn- composite-clause-in-stages-0-to?
"True when any stage 0..`max-stage` contains an `:aggregation` or `:expressions` clause with
@@ -803,7 +806,8 @@
[query :- ::lib.schema/query
stage-number :- :int
filter-clause :- ::lib.schema.expression/expression]
- (let [->temporal-name #(u.time/format-unit % nil)
+ (let [time-config (lib.date-time/config query)
+ ->temporal-name #(u.time/format-unit time-config % nil)
temporal? #(lib.util/original-isa? % :type/Temporal)
unit= (fn [maybe-clause unit-or-units]
(let [units (set (u/one-or-many unit-or-units))]
@@ -811,33 +815,35 @@
(temporal? maybe-clause)
(lib.util/clause? maybe-clause)
(clojure.core/contains? units (:temporal-unit (second maybe-clause))))))
- ->unit {:get-hour :hour-of-day
- :get-month :month-of-year
- :get-quarter :quarter-of-year}]
+ ->unit {:get-hour :hour-of-day
+ :get-month :month-of-year
+ :get-quarter :quarter-of-year}]
(match/match-one filter-clause
[#{:= :in} _ [:get-day-of-week _ (_ :guard temporal?) :iso] (b :guard int?)]
- (inflections/plural (u.time/format-unit b :day-of-week-iso))
+ (inflections/plural (u.time/format-unit time-config b :day-of-week-iso))
[#{:!= :not-in} _ [:get-day-of-week _ (_ :guard temporal?) :iso] (b :guard int?)]
- (i18n/tru "Excludes {0}" (inflections/plural (u.time/format-unit b :day-of-week-iso)))
+ (i18n/tru "Excludes {0}" (inflections/plural (u.time/format-unit time-config b :day-of-week-iso)))
[#{:= :in} _ [(f :guard #{:get-hour :get-month :get-quarter}) _ (_ :guard temporal?)] (b :guard int?)]
- (u.time/format-unit b (->unit f))
+ (u.time/format-unit time-config b (->unit f))
[#{:!= :not-in} _ [(f :guard #{:get-hour :get-month :get-quarter}) _ (_ :guard temporal?)] (b :guard int?)]
- (i18n/tru "Excludes {0}" (u.time/format-unit b (->unit f)))
+ (i18n/tru "Excludes {0}" (u.time/format-unit time-config b (->unit f)))
[#{:= :in} _ (x :guard (unit= x lib.schema.temporal-bucketing/datetime-truncation-units)) (y :guard string?)]
- (u.time/format-relative-date-range y 0 (:temporal-unit (second x)) nil nil {:include-current true})
+ (u.time/format-relative-date-range time-config
+ y 0 (:temporal-unit (second x)) nil nil
+ {:include-current true})
[:during _ (x :guard temporal?) (y :guard string?) unit]
- (u.time/format-relative-date-range y 1 unit -1 unit {})
+ (u.time/format-relative-date-range time-config y 1 unit -1 unit nil)
[#{:= :in} _ (x :guard temporal?) (y :guard (or (int? y) (string? y)))]
- (lib.temporal-bucket/describe-temporal-pair x y)
+ (lib.temporal-bucket/describe-temporal-pair time-config x y)
[#{:!= :not-in} _ (x :guard temporal?) (y :guard (or (int? y) (string? y)))]
- (i18n/tru "Excludes {0}" (lib.temporal-bucket/describe-temporal-pair x y))
+ (i18n/tru "Excludes {0}" (lib.temporal-bucket/describe-temporal-pair time-config x y))
[:< _ (x :guard temporal?) (y :guard string?)]
(i18n/tru "Before {0}" (->temporal-name y))
diff --git a/src/metabase/lib/filter.cljc b/src/metabase/lib/filter.cljc
index 28217f3a64a..6ae345a56d1 100644
--- a/src/metabase/lib/filter.cljc
+++ b/src/metabase/lib/filter.cljc
@@ -5,6 +5,7 @@
[clojure.string :as str]
[inflections.core :as inflections]
[metabase.lib.common :as lib.common]
+ [metabase.lib.date-time :as lib.date-time]
[metabase.lib.dispatch :as lib.dispatch]
[metabase.lib.equality :as lib.equality]
[metabase.lib.expression :as lib.expression]
@@ -105,7 +106,8 @@
(defmethod lib.metadata.calculation/display-name-method ::varargs
[query stage-number expr style]
(let [->display-name #(lib.metadata.calculation/display-name query stage-number % style)
- ->temporal-name lib.temporal-bucket/describe-temporal-pair
+ time-config (lib.date-time/config query)
+ ->temporal-name #(lib.temporal-bucket/describe-temporal-pair time-config %1 %2)
numeric? #(clojure.core/and (lib.util/original-isa? % :type/Number)
(lib.util/clause? %)
(-> (lib.metadata.calculation/metadata query stage-number %)
@@ -126,14 +128,14 @@
:temporal-unit
lib.temporal-bucket/describe-temporal-unit
u/lower-case-en)
- ->unit {:get-hour :hour-of-day
- :get-month :month-of-year
- :get-quarter :quarter-of-year
- :get-year :year-of-era}]
+ ->unit {:get-hour :hour-of-day
+ :get-month :month-of-year
+ :get-quarter :quarter-of-year
+ :get-year :year-of-era}]
(match/match-one expr
[(op :guard #{:= :in :!= :not-in}) _ [:get-hour _ (a :guard temporal?)] (b :guard int?)]
(i18n/tru "{0} {1} {2}" (->unbucketed-display-name a) (if (#{:= :in} op) "is at" "excludes the hour of")
- (u.time/format-unit b :hour-of-day))
+ (u.time/format-unit time-config b :hour-of-day))
[(op :guard #{:= :in :!= :not-in}) _ [:get-day-of-week _ (a :guard temporal?) :iso] & (args :guard (every? int? args))]
(let [cnt (count args)
@@ -142,22 +144,25 @@
(i18n/tru "{0} {1} {2} {3} selections" (->display-name a) (if in? "is one of" "excludes") cnt
(-> :day-of-week lib.temporal-bucket/describe-temporal-unit u/lower-case-en))
- in? (i18n/tru "{0} is on {1}" (->display-name a) (u.time/format-unit (first args) :day-of-week-iso))
+ in? (i18n/tru "{0} is on {1}" (->display-name a)
+ (u.time/format-unit time-config (first args) :day-of-week-iso))
:else (i18n/tru "{0} excludes {1}" (->unbucketed-display-name a)
- (inflections/plural (u.time/format-unit (first args) :day-of-week-iso)))))
+ (inflections/plural (u.time/format-unit time-config (first args) :day-of-week-iso)))))
[(_ :guard #{:= :in}) _ [(f :guard #{:get-month :get-quarter :get-year}) _ (a :guard temporal?)] (b :guard int?)]
- (i18n/tru "{0} is in {1}" (->unbucketed-display-name a) (u.time/format-unit b (->unit f)))
+ (i18n/tru "{0} is in {1}" (->unbucketed-display-name a) (u.time/format-unit time-config b (->unit f)))
[(_ :guard #{:!= :not-in}) _ [:get-month _ (a :guard temporal?)] (b :guard int?)]
- (i18n/tru "{0} excludes each {1}" (->unbucketed-display-name a) (u.time/format-unit b :month-of-year))
+ (i18n/tru "{0} excludes each {1}" (->unbucketed-display-name a)
+ (u.time/format-unit time-config b :month-of-year))
[(_ :guard #{:!= :not-in}) _ [:get-quarter _ (a :guard temporal?)] (b :guard int?)]
- (i18n/tru "{0} excludes {1} each year" (->unbucketed-display-name a) (u.time/format-unit b :quarter-of-year))
+ (i18n/tru "{0} excludes {1} each year" (->unbucketed-display-name a)
+ (u.time/format-unit time-config b :quarter-of-year))
[(_ :guard #{:!= :not-in}) _ [:get-year _ (a :guard temporal?)] (b :guard int?)]
- (i18n/tru "{0} excludes {1}" (->unbucketed-display-name a) (u.time/format-unit b :year))
+ (i18n/tru "{0} excludes {1}" (->unbucketed-display-name a) (u.time/format-unit time-config b :year))
[(op :guard #{:= :in :!= :not-in}) _ [(f :guard #{:get-hour :get-month :get-quarter :get-year}) _ (a :guard temporal?)] & (args :guard (every? int? args))]
(i18n/tru "{0} {1} {2} {3} selections"
@@ -170,7 +175,10 @@
(i18n/tru "{0} is equal to {1}" (->display-name a) (->display-name b))
[(_ :guard #{:= :in}) _ (a :guard (unit= a lib.schema.temporal-bucketing/datetime-truncation-units)) (b :guard string?)]
- (i18n/tru "{0} is {1}" (->unbucketed-display-name a) (u.time/format-relative-date-range b 0 (:temporal-unit (second a)) nil nil {:include-current true}))
+ (i18n/tru "{0} is {1}" (->unbucketed-display-name a)
+ (u.time/format-relative-date-range time-config
+ b 0 (:temporal-unit (second a)) nil nil
+ {:include-current true}))
[(_ :guard #{:= :in}) _ (a :guard (unit= a :day-of-week)) (b :guard (clojure.core/or (int? b) (string? b)))]
(i18n/tru "{0} is {1}" (->display-name a) (->temporal-name a b))
@@ -235,8 +243,9 @@
(defmethod lib.metadata.calculation/display-name-method ::binary
[query stage-number expr style]
- (let [->display-name #(lib.metadata.calculation/display-name query stage-number % style)
- ->temporal-name #(u.time/format-unit % nil)
+ (let [->display-name #(lib.metadata.calculation/display-name query stage-number % style)
+ time-config (lib.date-time/config query)
+ ->temporal-name #(u.time/format-unit time-config % nil)
temporal? #(lib.util/original-isa? % :type/Temporal)]
(match/match-one expr
[:< _ (x :guard temporal?) (y :guard string?)]
@@ -301,10 +310,11 @@
(defmethod lib.metadata.calculation/display-name-method :during
[query stage-number [_tag _opts expr value unit] style]
- (let [->display-name #(lib.metadata.calculation/display-name query stage-number % style)]
+ (let [->display-name #(lib.metadata.calculation/display-name query stage-number % style)
+ time-config (lib.date-time/config query)]
((binary-filter-display-fns :is)
(->display-name expr)
- (u.time/format-relative-date-range value 1 unit -1 unit {}))))
+ (u.time/format-relative-date-range time-config value 1 unit -1 unit nil))))
(defmethod lib.metadata.calculation/display-name-method :inside
[query stage-number [_tag opts lat-expr lon-expr lat-max lon-min lat-min lon-max] style]
diff --git a/src/metabase/lib/filter/desugar.cljc b/src/metabase/lib/filter/desugar.cljc
index 09180332010..0a3654b052e 100644
--- a/src/metabase/lib/filter/desugar.cljc
+++ b/src/metabase/lib/filter/desugar.cljc
@@ -149,10 +149,11 @@
(mu/defn- desugar-during :- ::clause
"Transform a `:during` expression to an `:and` expression."
- [expr :- ::clause]
+ [time-config :- ::lib.schema.common/time-config
+ expr :- ::clause]
(match/replace expr
[:during opts arg value unit]
- (let [lower-bound (u.time/truncate value unit)
+ (let [lower-bound (u.time/truncate time-config value unit)
upper-bound (u.time/add lower-bound unit 1)]
(-> (lib.filter/and
(lib.filter/>= (with-default-temporal-bucket-in-refs arg) lower-bound)
@@ -299,16 +300,17 @@
(mu/defn- temporal-case-expression :- :mbql.clause/case
"Creates a `:case` expression with a condition for each value of the given unit."
- [expr :- ::clause
- opts :- ::lib.schema.common/options
- unit :- :keyword
- n :- :int]
+ [time-config :- ::lib.schema.common/time-config
+ expr :- ::clause
+ opts :- ::lib.schema.common/options
+ unit :- :keyword
+ n :- :int]
(let [user-locale #?(:clj (i18n/user-locale)
:cljs nil)]
(-> (lib.expression/case
(mapv (fn [raw-value]
[(lib.filter/= (lib.util/fresh-uuids expr) raw-value)
- (u.time/format-unit raw-value unit user-locale)])
+ (u.time/format-unit time-config raw-value unit {:locale user-locale})])
(range 1 (inc n))))
(lib.options/update-options merge opts {:default ""}))))
@@ -318,51 +320,55 @@
Uses the user's locale rather than the site locale, so the results will depend on the runner of the query, not just
the query itself. Filtering should be done based on the number, rather than the name."
- [expression :- ::clause]
+ [time-config :- ::lib.schema.common/time-config
+ expression :- ::clause]
(match/replace expression
- [:month-name opts expr] (&recur (temporal-case-expression expr opts :month-of-year 12))
- [:quarter-name opts expr] (&recur (temporal-case-expression expr opts :quarter-of-year 4))
- [:day-name opts expr] (&recur (temporal-case-expression expr opts :day-of-week 7))))
+ [:month-name opts expr] (&recur (temporal-case-expression time-config expr opts :month-of-year 12))
+ [:quarter-name opts expr] (&recur (temporal-case-expression time-config expr opts :quarter-of-year 4))
+ [:day-name opts expr] (&recur (temporal-case-expression time-config expr opts :day-of-week 7))))
(mu/defn- desugar-expression :- ::clause
"Rewrite various 'syntactic sugar' expressions like `:/` with more than two args into something simpler for drivers
to compile."
- [expression :- ::clause]
+ [time-config :- ::lib.schema.common/time-config
+ expression :- ::clause]
;; The `mbql.jvm-u/desugar-host-and-domain` is implemented only for jvm because regexes are not compatible with
;; Safari.
(let [desugar-host-and-domain* #?(:clj lib.filter.desugar.jvm/desugar-host-and-domain
:cljs (fn [x]
(log/warn "`desugar-host-and-domain` implemented only on JVM.")
x))]
- (-> expression
- desugar-divide-with-extra-args
- desugar-host-and-domain*
- desugar-temporal-names)))
+ (desugar-temporal-names time-config
+ (-> expression
+ desugar-divide-with-extra-args
+ desugar-host-and-domain*))))
(mu/defn- maybe-desugar-expression :- ::clause
- [clause :- ::clause]
- (cond-> clause
- (or (lib.util/clause-of-type? clause :field)
- (mr/validate ::lib.schema.expression/expression clause))
- desugar-expression))
+ [time-config :- ::lib.schema.common/time-config
+ clause :- ::clause]
+ (if (or (lib.util/clause-of-type? clause :field)
+ (mr/validate ::lib.schema.expression/expression clause))
+ (desugar-expression time-config clause)
+ clause))
(mu/defn desugar-filter-clause :- ::clause
"Rewrite various 'syntatic sugar' filter clauses like `:time-interval` and `:inside` as simpler, logically
equivalent clauses. This can be used to simplify the number of filter clauses that need to be supported by anything
that needs to enumerate all the possible filter types."
- [filter-clause :- ::clause]
- (-> filter-clause
- desugar-current-relative-datetime
- desugar-in
- desugar-multi-argument-comparisons
- desugar-does-not-contain
- desugar-time-interval
- desugar-relative-time-interval
- desugar-is-null-and-not-null
- desugar-is-empty-and-not-empty
- desugar-inside
- lib.filter.simplify-compound/simplify-compound-filter
- desugar-temporal-extract
- desugar-during
- desugar-if
- maybe-desugar-expression))
+ [time-config :- ::lib.schema.common/time-config
+ filter-clause :- ::clause]
+ (let [filter-clause (-> filter-clause
+ desugar-current-relative-datetime
+ desugar-in
+ desugar-multi-argument-comparisons
+ desugar-does-not-contain
+ desugar-time-interval
+ desugar-relative-time-interval
+ desugar-is-null-and-not-null
+ desugar-is-empty-and-not-empty
+ desugar-inside
+ lib.filter.simplify-compound/simplify-compound-filter
+ desugar-temporal-extract)
+ filter-clause (desugar-during time-config filter-clause)
+ filter-clause (desugar-if filter-clause)]
+ (maybe-desugar-expression time-config filter-clause)))
diff --git a/src/metabase/lib/filter/negate.cljc b/src/metabase/lib/filter/negate.cljc
index af5a4f36137..08e3290171f 100644
--- a/src/metabase/lib/filter/negate.cljc
+++ b/src/metabase/lib/filter/negate.cljc
@@ -6,6 +6,7 @@
[metabase.lib.filter.simplify-compound :as lib.filter.simplify-compound]
[metabase.lib.hierarchy :as lib.hierarchy]
[metabase.lib.options :as lib.options]
+ [metabase.lib.schema.common :as lib.schema.common]
[metabase.lib.schema.expression :as lib.schema.expression]
[metabase.lib.schema.util :as lib.schema.util]
[metabase.lib.util :as lib.util]
@@ -53,9 +54,9 @@
[:ref ::lib.schema.expression/boolean]
[:ref ::lib.schema.util/unique-uuids]]
"Logically negate a boolean expression (presumably a filter clause)."
- [boolean-expression :- ::lib.schema.expression/boolean]
- (let [expression' (-> boolean-expression
- lib.filter.desugar/desugar-filter-clause
+ [time-config :- ::lib.schema.common/time-config
+ boolean-expression :- ::lib.schema.expression/boolean]
+ (let [expression' (-> (lib.filter.desugar/desugar-filter-clause time-config boolean-expression)
negate*
lib.filter.simplify-compound/simplify-compound-filter)]
(if (= expression' boolean-expression)
diff --git a/src/metabase/lib/filter/update.cljc b/src/metabase/lib/filter/update.cljc
index ae55d635e7c..568dd078166 100644
--- a/src/metabase/lib/filter/update.cljc
+++ b/src/metabase/lib/filter/update.cljc
@@ -17,6 +17,7 @@
If there is no existing filter on the column(s), these add a new filter. Existing filters are replaced."
(:require
[metabase.lib.breakout :as lib.breakout]
+ [metabase.lib.date-time :as lib.date-time]
[metabase.lib.equality :as lib.equality]
[metabase.lib.filter :as lib.filter]
[metabase.lib.ref :as lib.ref]
@@ -199,7 +200,8 @@
(not (string? t))
(u.time/format-for-base-type ((some-fn :effective-type :base-type) temporal-column)))))
start (maybe-string start)
- end (maybe-string end)]
+ end (maybe-string end)
+ time-config (lib.date-time/config query)]
(if-not unit
;; Temporal column is not bucketed: we don't need to update any temporal units here. Add/update a `:between`
;; filter.
@@ -208,11 +210,11 @@
(let [;; clamp range to unit to ensure we select exactly what's represented by the dots/bars. E.g. if I draw my
;; filter from `2024-01-02` to `2024-03-05` and the unit is `:month`, we should only show the months
;; between those two values, i.e. only `2024-02` and `2024-03`.
- start (let [truncated-start (u.time/truncate start unit)]
+ start (let [truncated-start (u.time/truncate time-config start unit)]
(if (zero? (u.time/unit-diff :millisecond truncated-start start))
truncated-start
- (u.time/truncate (u.time/add start unit 1) unit)))
- end (u.time/truncate end unit)
+ (u.time/truncate time-config (u.time/add start unit 1) unit)))
+ end (u.time/truncate time-config end unit)
;; update the breakout unit if appropriate.
breakout-unit (temporal-filter-find-best-breakout-unit unit start end (:effective-type temporal-column))
query (if (= unit breakout-unit)
diff --git a/src/metabase/lib/js.cljs b/src/metabase/lib/js.cljs
index 5cd3c8dc9d1..a68e3f1d6b9 100644
--- a/src/metabase/lib/js.cljs
+++ b/src/metabase/lib/js.cljs
@@ -2460,12 +2460,14 @@
code. It does not need to be wrapped or included here. Just merge these extra keyword conversions into that code and
remove this."
[n unit offset-n offset-unit options]
- (u.time/format-relative-date-range
- n
- (keyword unit)
- offset-n
- (some-> offset-unit keyword)
- (js->clj options :keywordize-keys true)))
+ (let [{:keys [start-of-week] :as options} (js->clj options :keywordize-keys true)]
+ (u.time/format-relative-date-range
+ {:start-of-week (keyword (or start-of-week :sunday))}
+ n
+ (keyword unit)
+ offset-n
+ (some-> offset-unit keyword)
+ (dissoc options :start-of-week))))
(defn ^:export find-matching-column
"Given `a-ref-or-column` and a list of `columns`, finds the column that best matches this ref or column.
diff --git a/src/metabase/lib/schema/common.cljc b/src/metabase/lib/schema/common.cljc
index 53e5f90d6ba..bac204acb6f 100644
--- a/src/metabase/lib/schema/common.cljc
+++ b/src/metabase/lib/schema/common.cljc
@@ -510,3 +510,9 @@
m))
m
deprecated-lib-key-renames))
+
+(mr/def ::time-config
+ "The time settings a query is evaluated under. `metabase.lib.date-time/config` builds it from a metadata provider."
+ [:map
+ {:closed true}
+ [:start-of-week [:enum :monday :tuesday :wednesday :thursday :friday :saturday :sunday]]])
diff --git a/src/metabase/lib/temporal_bucket.cljc b/src/metabase/lib/temporal_bucket.cljc
index 3f20e677d65..32d07830a3c 100644
--- a/src/metabase/lib/temporal_bucket.cljc
+++ b/src/metabase/lib/temporal_bucket.cljc
@@ -458,9 +458,10 @@
(mu/defn describe-temporal-pair :- :string
"Return a string describing the temporal pair.
Used when comparing temporal values like `[:!= ... [:field {:temporal-unit :day-of-week} ...] \"2022-01-01\"]`"
- [temporal-column :- Bucketable
+ [time-config :- ::lib.schema.common/time-config
+ temporal-column :- Bucketable
temporal-value :- [:or :int :string]]
- (u.time/format-unit temporal-value (:unit (temporal-bucket temporal-column))))
+ (u.time/format-unit time-config temporal-value (:unit (temporal-bucket temporal-column))))
(defn add-temporal-bucket-to-ref
"Internal helper shared between a few implementations of [[with-temporal-bucket-method]].
diff --git a/src/metabase/lib_be/core.clj b/src/metabase/lib_be/core.clj
index a9d2c0fad6d..c14f24268df 100644
--- a/src/metabase/lib_be/core.clj
+++ b/src/metabase/lib_be/core.clj
@@ -34,6 +34,7 @@
breakout-bin-width
breakout-bins-num
enable-nested-queries
- start-of-week]
+ start-of-week
+ time-config]
[metabase.lib-be.query
bulk-load-query-metadata!])
diff --git a/src/metabase/lib_be/settings.clj b/src/metabase/lib_be/settings.clj
index 11601856fc1..88f85be6822 100644
--- a/src/metabase/lib_be/settings.clj
+++ b/src/metabase/lib_be/settings.clj
@@ -56,3 +56,8 @@
(assert (#{:monday :tuesday :wednesday :thursday :friday :saturday :sunday} (keyword new-value))
(trs "Invalid day of week: {0}" (pr-str new-value))))
(setting/set-value-of-type! :keyword :start-of-week new-value)))
+
+(defn time-config
+ "The `time-config` map that date and time functions take, built from this instance's settings."
+ []
+ {:start-of-week (start-of-week)})
diff --git a/src/metabase/mcp/core.clj b/src/metabase/mcp/core.clj
index 0cf213e9672..66f4dc10375 100644
--- a/src/metabase/mcp/core.clj
+++ b/src/metabase/mcp/core.clj
@@ -70,12 +70,7 @@
(into (comp (keep #(get-in % [:form :metadata :scope]))
(filter string?))
(vals (api.macros/ns-routes 'metabase.agent-api.api)))
- ;; The v2 surface's scopes, read from the require-free leaf rather than from the registry. Deriving them
- ;; from `v2.registry/registered-scopes` would report only the tools whose namespaces happen to be loaded,
- ;; and reaching `v2.resources` from here puts `metabot.scope` (and `premium-features`) on the security
- ;; middleware's load path — the cycle `metabase.mcp.paths`' docstring exists to prevent. The literal set
- ;; already covers every scope the v2 tools and resources gate on, and
- ;; `v2-surface-scopes-match-metabot-scope-test` keeps it in step.
+ ;; The v2 surface's scopes, read from the require-free leaf rather than the registry (see [[v2-scopes]]).
(into mcp.paths/v2-surface-scopes)))
(defn v2-scopes
@@ -83,11 +78,9 @@
[[all-scopes]] also gathers — those belong to a different resource, and advertising them for v2 is
what puts per-entity scopes the v2 tools don't use on a v2 client's consent screen.
- Read from the require-free literal in [[metabase.mcp.paths/v2-surface-scopes]] rather than from the
- registries: `metabase.server.middleware.security` requires this namespace, so reaching
- `mcp.v2.resources` from here would put `metabot.scope` (and `premium-features`) on the security
- middleware's load path — the cycle `mcp.paths` exists to prevent. Deriving from the registry is also
- load-order dependent, reporting only the tools whose namespaces happen to be loaded.
+ Read from the require-free literal in [[metabase.mcp.paths/v2-surface-scopes]], not the registries.
+ The registries report only the tools whose namespaces happen to be loaded.
+ Reaching them from here would also pull `metabot.scope` in wherever this namespace loads (see [[metabase.mcp.paths]]).
`v2-surface-scopes-match-metabot-scope-test` keeps the literal in step with what the tools gate on."
[]
mcp.paths/v2-surface-scopes)
diff --git a/src/metabase/mcp/http_handler.clj b/src/metabase/mcp/http_handler.clj
new file mode 100644
index 00000000000..6532768ded5
--- /dev/null
+++ b/src/metabase/mcp/http_handler.clj
@@ -0,0 +1,18 @@
+(ns metabase.mcp.http-handler
+ "What MCP adds to the application's HTTP handler."
+ (:require
+ [metabase.mcp.core :as mcp]
+ [metabase.oauth-server.core :as oauth-server]))
+
+(def options
+ "Options for [[metabase.server.core/make-handler]].
+ They add MCP origins to CORS and let the session middleware accept OAuth bearer tokens and MCP UI credentials.
+ The fns are passed as vars, so redefining one takes effect without rebuilding the handler."
+ {:cors {:origins-fn #'mcp/cors-origins
+ :sandbox-origin?-fn #'mcp/sandbox-origin?}
+ :oauth-bearer {:extract-token #'oauth-server/extract-bearer-token
+ :resolve-token #'oauth-server/resolve-access-token
+ :full-access-scope oauth-server/full-access-scope}
+ :mcp-ui-credentials {:on-surface? #'mcp/ui-credential-on-surface?
+ :resolve-credential #'mcp/resolve-ui-credential
+ :scope-satisfied? #'mcp/ui-credential-scope-satisfied?}})
diff --git a/src/metabase/mcp/paths.clj b/src/metabase/mcp/paths.clj
index f4021335d22..baca3d25415 100644
--- a/src/metabase/mcp/paths.clj
+++ b/src/metabase/mcp/paths.clj
@@ -5,11 +5,11 @@
[[metabase.api-routes.routes]] and the resource-metadata endpoints in
[[metabase.oauth-server.api.metadata]] — and for the scope sets the v2 surface accepts and advertises.
- A leaf namespace, with NO requires, so both the handler and the OAuth server can read it without a
- dependency cycle. That is load-bearing rather than tidy: `metabase.server.middleware.security` requires
- `metabase.mcp.core`, so anything `mcp.core` reaches becomes part of the security middleware's load path —
- pulling `metabot.scope` (and through it `premium-features`) in that way deadlocks namespace loading with a
- methodical protocol error at web-server start. Keep this namespace dependency-free.")
+ A leaf namespace with no requires, so the handler and OAuth server can read it without a dependency cycle.
+ Anything `metabase.mcp.core` reaches joins the load path of every namespace that loads it.
+ Pulling `metabot.scope`, and through it `premium-features`, onto that path has deadlocked namespace loading
+ with a methodical protocol error at web-server start.
+ Keep this namespace dependency-free.")
(set! *warn-on-reflection* true)
diff --git a/src/metabase/mcp/v2/tools/definitions.clj b/src/metabase/mcp/v2/tools/definitions.clj
index 32d4d01dd82..aa85b344f10 100644
--- a/src/metabase/mcp/v2/tools/definitions.clj
+++ b/src/metabase/mcp/v2/tools/definitions.clj
@@ -1,7 +1,7 @@
(ns metabase.mcp.v2.tools.definitions
"The v2 MCP `segment_write` and `measure_write` tools: authoring for the two table-attached
MBQL macros. Both call the same domain create/update fns the REST endpoints use
- ([[metabase.segments.api]]/[[metabase.measures.api]]), so permission enforcement — superuser
+ ([[metabase.segments.rest.api]]/[[metabase.measures.api]]), so permission enforcement — superuser
OR data-analyst-with-unrestricted-view-data on the table, plus the table's remote-sync
editability — is inherited, never reimplemented. The tools' own work is id resolution behind
read checks, definition-shape handling (the bare clause form `get_content` returns, full
@@ -34,8 +34,8 @@
#_{:clj-kondo/ignore [:metabase/modules]}
(defn- api-fn [ns-name fn-name] (requiring-resolve (symbol ns-name fn-name)))
-(defn- create-segment! [body] ((api-fn "metabase.segments.api" "create-segment!") body))
-(defn- update-segment! [id body] ((api-fn "metabase.segments.api" "write-check-and-update-segment!") id body))
+(defn- create-segment! [body] ((api-fn "metabase.segments.rest.api" "create-segment!") body))
+(defn- update-segment! [id body] ((api-fn "metabase.segments.rest.api" "write-check-and-update-segment!") id body))
(defn- create-measure! [body] ((api-fn "metabase.measures.api" "create-measure!") body))
(defn- update-measure! [id body] ((api-fn "metabase.measures.api" "write-check-and-update-measure!") id body))
diff --git a/src/metabase/mq/queue/quartz.clj b/src/metabase/mq/queue/quartz.clj
index 7d7a334cae3..d3b37dee472 100644
--- a/src/metabase/mq/queue/quartz.clj
+++ b/src/metabase/mq/queue/quartz.clj
@@ -29,13 +29,13 @@
[clojurewerkz.quartzite.jobs :as jobs]
[clojurewerkz.quartzite.triggers :as triggers]
[metabase.analytics-interface.core :as analytics]
+ [metabase.app-db.quartz :as app-db.quartz]
[metabase.mq.impl :as mq.impl]
[metabase.mq.quartz-affinity :as quartz-affinity]
[metabase.mq.queue.backend :as q.backend]
[metabase.mq.queue.concurrency :as q.concurrency]
[metabase.mq.queue.impl :as q.impl]
[metabase.mq.queue.registry :as q.registry]
- [metabase.task.bootstrap :as task.bootstrap]
[metabase.task.core :as task]
[metabase.util.log :as log])
(:import
@@ -48,12 +48,10 @@
"This backend's identifier, registered with `metabase.mq.init`; its `name` labels metrics."
:queue.backend/quartz)
-;; Install the queue node-affinity DriverDelegate when Quartz's JDBC properties are set. Registered at
-;; load time, and here rather than in `metabase.mq.init`, because it is a property of *this* backend —
-;; init has no business knowing that one backend swaps out a Quartz internal. (`mq` depends on `task`,
-;; not the reverse, so `task.bootstrap` calls back into this rather than referencing `mq`.)
-;; install-delegate! falls back to the plain per-DB delegate if the affinity subclass can't be loaded.
-(task.bootstrap/register-jdbc-property-setter! quartz-affinity/install-delegate!)
+;; Install the queue node-affinity `DriverDelegate` when Quartz's JDBC properties are set.
+;; This registers here rather than in `metabase.mq.init` because the delegate belongs to this backend alone.
+;; If the affinity subclass can't be loaded, `install-delegate!` falls back to the plain per-database delegate.
+(app-db.quartz/register-jdbc-property-setter! quartz-affinity/install-delegate!)
(def ^:private job-group
"Quartz group every queue job/trigger lives in, so they're easy to isolate from the rest of the
diff --git a/src/metabase/parameters/shared.cljc b/src/metabase/parameters/shared.cljc
index 3d8610645a3..52f320160a9 100644
--- a/src/metabase/parameters/shared.cljc
+++ b/src/metabase/parameters/shared.cljc
@@ -118,19 +118,22 @@
#"^(past|next)([0-9]+)([a-z]+)s-from-([0-9]+)([a-z]+)s$" :>> (fn [matches] (apply format-relative-date-with-offset matches))))
(defn- format-day [value locale]
- (-> value
- (time/parse-unit :day-of-week-abbrev "en") ;; always read in en locale
- (time/format-unit :day-of-week locale)))
+ (time/format-unit {:start-of-week :sunday}
+ (time/parse-unit value :day-of-week-abbrev "en") ; always read in en locale
+ :day-of-week
+ {:locale locale}))
(defn- format-hour [value locale]
- (-> value
- (time/parse-unit :hour-of-day-24 "en") ;; always read in en locale
- (time/format-unit :hour-of-day locale)))
+ (time/format-unit {:start-of-week :sunday}
+ (time/parse-unit value :hour-of-day-24 "en") ; always read in en locale
+ :hour-of-day
+ {:locale locale}))
(defn- format-month [value locale]
- (-> value
- (time/parse-unit :month-of-year "en") ;; always read in en locale
- (time/format-unit :month-of-year-full locale)))
+ (time/format-unit {:start-of-week :sunday}
+ (time/parse-unit value :month-of-year "en") ; always read in en locale
+ :month-of-year-full
+ {:locale locale}))
(defn- format-exclude-unit [value unit locale]
(case unit
diff --git a/src/metabase/query_processor/middleware/desugar.clj b/src/metabase/query_processor/middleware/desugar.clj
index f4180e7ccd7..81729ddfa40 100644
--- a/src/metabase/query_processor/middleware/desugar.clj
+++ b/src/metabase/query_processor/middleware/desugar.clj
@@ -2,6 +2,7 @@
(:refer-clojure :exclude [select-keys])
(:require
[metabase.lib.core :as lib]
+ [metabase.lib.date-time :as lib.date-time]
[metabase.lib.schema :as lib.schema]
[metabase.lib.walk :as lib.walk]
[metabase.util.malli :as mu]
@@ -9,11 +10,11 @@
[metabase.util.performance :refer [select-keys]]))
(defn- desugar*
- [stage-or-join]
+ [time-config stage-or-join]
(letfn [(desugar** [x]
(match/replace x
(clause :guard lib/clause?)
- (lib/desugar-filter-clause clause)))]
+ (lib/desugar-filter-clause time-config clause)))]
(merge
(desugar** (dissoc stage-or-join :joins :stages :lib/stage-metadata :parameters))
(select-keys stage-or-join [:joins :stages :lib/stage-metadata :parameters]))))
@@ -23,5 +24,6 @@
`inside` with lower-level clauses like `between`. This is done to minimize the number of MBQL clauses individual
drivers need to support. Clauses replaced by this middleware are marked `^:sugar` in the MBQL schema."
[query :- ::lib.schema/query]
- (lib.walk/walk query (fn [_query _path-type _path stage-or-join]
- (desugar* stage-or-join))))
+ (let [time-config (lib.date-time/config query)]
+ (lib.walk/walk query (fn [_query _path-type _path stage-or-join]
+ (desugar* time-config stage-or-join)))))
diff --git a/src/metabase/query_processor/middleware/optimize_temporal_filters.clj b/src/metabase/query_processor/middleware/optimize_temporal_filters.clj
index cec7a8e050e..9a764b161c4 100644
--- a/src/metabase/query_processor/middleware/optimize_temporal_filters.clj
+++ b/src/metabase/query_processor/middleware/optimize_temporal_filters.clj
@@ -4,6 +4,7 @@
(:refer-clojure :exclude [get-in mapv])
(:require
[better-cond.core :as b]
+ [metabase.lib-be.core :as lib-be]
[metabase.lib.core :as lib]
[metabase.lib.options :as lib.options]
[metabase.lib.schema :as lib.schema]
@@ -139,12 +140,16 @@
(mu/defn- temporal-literal-lower-bound :- ::temporal
[unit :- (into [:enum] u.date/add-units)
t :- ::temporal]
- (:start (u.date/range t unit)))
+ ;; TODO (Chris 2026-09-30) -- thread time-config through from optimize-temporal-clauses instead of
+ ;; re-fetching it per clause, the way lib.filter.desugar does.
+ (:start (u.date/range (lib-be/time-config) t unit)))
(mu/defn- temporal-literal-upper-bound :- ::temporal
[unit :- (into [:enum] u.date/add-units)
t :- ::temporal]
- (:end (u.date/range t unit)))
+ ;; TODO (Chris 2026-09-30) -- thread time-config through from optimize-temporal-clauses instead of
+ ;; re-fetching it per clause, the way lib.filter.desugar does.
+ (:end (u.date/range (lib-be/time-config) t unit)))
(defn- change-temporal-unit-to-default [field]
(match/replace field
@@ -243,7 +248,9 @@
(if (date-field-with-day-bucketing? query path field)
(lib/!= (change-temporal-unit-to-default field) (change-temporal-unit-to-default temporal-value))
(when-let [optimized ((get-method optimize-clause :=) query path clause)]
- (lib/negate-boolean-expression optimized))))
+ ;; TODO (Chris 2026-09-30) -- thread time-config through from optimize-temporal-clauses instead of
+ ;; re-fetching it per clause, the way lib.filter.desugar does.
+ (lib/negate-boolean-expression (lib-be/time-config) optimized))))
(mu/defn- optimize-comparison-clause :- [:maybe ::lib.schema.mbql-clause/clause]
[query :- ::lib.schema/query
diff --git a/src/metabase/query_processor/parameters/dates.clj b/src/metabase/query_processor/parameters/dates.clj
index e482d1f2d28..ec48ca3d6a0 100644
--- a/src/metabase/query_processor/parameters/dates.clj
+++ b/src/metabase/query_processor/parameters/dates.clj
@@ -10,6 +10,7 @@
[medley.core :as m]
[metabase.driver :as driver]
[metabase.driver.common :as driver.common]
+ [metabase.lib-be.core :as lib-be]
[metabase.lib.core :as lib]
[metabase.lib.schema.common :as lib.schema.common]
[metabase.lib.schema.expression :as lib.schema.expression]
@@ -76,10 +77,12 @@
(comparison-range start end unit :day))
([start end unit resolution]
- (merge
- (u.date/comparison-range start unit :>= {:resolution resolution})
- (u.date/comparison-range end unit :<= {:resolution resolution, :end :inclusive})
- {:unit unit})))
+ (let [time-config (lib-be/time-config)
+ options {:resolution resolution}]
+ (merge
+ (u.date/comparison-range time-config start unit :>= options)
+ (u.date/comparison-range time-config end unit :<= (assoc options :end :inclusive))
+ {:unit unit}))))
(defn- second-range
[start end]
diff --git a/src/metabase/query_processor/util/relative_datetime.clj b/src/metabase/query_processor/util/relative_datetime.clj
index f18d3f2197a..cd8d54eb726 100644
--- a/src/metabase/query_processor/util/relative_datetime.clj
+++ b/src/metabase/query_processor/util/relative_datetime.clj
@@ -2,6 +2,7 @@
"Utility function for server side relative datetime computation."
(:require
[java-time.api :as t]
+ [metabase.lib-be.core :as lib-be]
[metabase.query-processor.timezone :as qp.timezone]
[metabase.util.date-2 :as u.date]
[metabase.util.honey-sql-2 :as h2x]))
@@ -23,8 +24,7 @@
"Compute relative datetime from [[qp.timezone/now]] shifted by `unit` and `amount`. Format the resulting value
to literal string compatible with most sql databases, to avoid possible jdbc driver timezone conversions."
[unit amount effective-or-base-type]
- (-> (qp.timezone/now)
- (u.date/truncate unit)
+ (-> (u.date/truncate (lib-be/time-config) (qp.timezone/now) unit)
(u.date/add unit amount)
(maybe-truncate-dt-value effective-or-base-type)
(u.date/format-sql)))
diff --git a/src/metabase/segments/api.clj b/src/metabase/segments/rest/api.clj
similarity index 99%
rename from src/metabase/segments/api.clj
rename to src/metabase/segments/rest/api.clj
index 4fcee6e7424..003c6e2c009 100644
--- a/src/metabase/segments/api.clj
+++ b/src/metabase/segments/rest/api.clj
@@ -1,4 +1,4 @@
-(ns metabase.segments.api
+(ns metabase.segments.rest.api
"/api/segment endpoints."
(:require
[metabase.api.common :as api]
diff --git a/src/metabase/server/handler.clj b/src/metabase/server/handler.clj
index e35d0a2a815..d3004fea603 100644
--- a/src/metabase/server/handler.clj
+++ b/src/metabase/server/handler.clj
@@ -75,20 +75,21 @@
(log/warnf "Failed to load dev remote API proxy middleware: %s" (ex-message e))
nil)))
-(def ^:private middleware
+(defn- middleware
"Ring async middleware has the form
(defn middleware-fn [handler]
(fn handler' [request respond raise]
(handler request respond raise)))"
+ [{:keys [cors] :as options}]
;; ▼▼▼ The returned `handlers` will see the requests in order from BOTTOM-TO-TOP, but the middleware is CONSTRUCTED/WRAPPED from TOP-TO-BOTTOM. ▼▼▼
(->> [ ;; Inside of the middleware onion
#'mw.exceptions/catch-uncaught-exceptions ; catch any Exceptions that weren't passed to `raise`
- #'mw.exceptions/catch-api-exceptions ; catch exceptions and return them in our expected format
+ #(#'mw.exceptions/catch-api-exceptions % cors) ; catch exceptions and return them in our expected format
#'mw.log/log-api-call ; log info about the request, db call counts etc.
#'agent-api.usage/wrap-record-cli-usage ; record CLI usage analytics for metabase-cli REST API calls
#'mw.browser-cookie/ensure-browser-id-cookie ; add cookie to identify browser; add `:browser-id` to the request
- #'mw.security/add-security-headers ; Add HTTP headers to API responses to prevent them from being cached
+ #(#'mw.security/add-security-headers % cors) ; Add HTTP headers to API responses to prevent them from being cached
#'mw.json/wrap-json-body ; extracts json POST/PUT body and makes it available on request
#'mw.offset-paging/handle-paging ; binds per-request parameters to handle paging
#'mw.json/wrap-streamed-json-response ; middleware to automatically serialize suitable objects as JSON in responses
@@ -101,7 +102,7 @@
#'mw.session/reset-session-timeout ; Resets the timeout cookie for user activity to [[metabase.request.cookies/session-timeout]]
#'mw.session/bind-current-user ; Binds *current-user* and *current-user-id* if :metabase-user-id is non-nil
#'mw.data-app-scope/wrap-data-app-scope ; narrows a data-app request (X-Metabase-Client: data-app) to the `data-app` scope (runs after current-user-info so it sees any resolved token scopes)
- #'mw.session/wrap-current-user-info ; looks for :metabase-session-key and sets :metabase-user-id and other info if Session ID is valid
+ #(#'mw.session/wrap-current-user-info % options) ; looks for :metabase-session-key and sets :metabase-user-id and other info if Session ID is valid
#'mw.pf-cache/wrap-premium-features-cache-check ; check cookie to refresh premium features cache if needed
#'mw.settings-cache/wrap-settings-cache-check ; check cookie to refresh settings cache if needed
#'analytics/embedding-mw ; reads sdk client headers, binds them to *client* and *version*, and tracks sdk-response metrics
@@ -122,30 +123,63 @@
]
(remove nil?)))
+(def ^:private Options
+ "Middleware configuration from the application: extra CORS origins, and credentials beyond sessions and API keys.
+ Every key is required, so a server built without them fails at startup rather than refusing those credentials."
+ [:map
+ {:closed true}
+ [:cors
+ [:map
+ {:closed true}
+ [:origins-fn ifn?]
+ [:sandbox-origin?-fn ifn?]]]
+ [:oauth-bearer ::mw.session/oauth-bearer]
+ [:mcp-ui-credentials ::mw.session/mcp-ui-credentials]])
+
+(def ^:private OptionsOrVar
+ [:or Options [:fn {:error/message "a var holding handler options"} var?]])
+
+(defn- current-options
+ "The options map, dereferenced if `options` is a var.
+ Throws if it does not match [[Options]]."
+ [options]
+ ;; Checked here because `mu/defn` does not validate schemas in prod.
+ (mu/validate-throw Options (if (var? options) @options options)))
+
(mu/defn- apply-middleware :- ::api.macros/handler
- [handler :- ::api.macros/handler]
+ [handler :- ::api.macros/handler
+ options :- Options]
(reduce
(fn [handler middleware-fn]
(middleware-fn handler))
handler
- middleware))
+ (middleware options)))
;;; for interactive dev we'll create a handler that rebuilds itself (reapplies the middleware) whenever any of it
-;;; changes.
+;;; changes, including the options when they are passed as a var.
(mu/defn- dev-handler :- ::api.macros/handler
- [server-routes :- ::api.macros/handler]
- (let [handler (atom (apply-middleware server-routes))]
- (doseq [varr (cons #'middleware middleware)
+ [server-routes :- ::api.macros/handler
+ options :- OptionsOrVar]
+ (let [rebuild #(apply-middleware server-routes (current-options options))
+ handler (atom (rebuild))]
+ (doseq [varr (concat [#'middleware
+ #'mw.exceptions/catch-api-exceptions
+ #'mw.security/add-security-headers
+ #'mw.session/wrap-current-user-info
+ options]
+ (middleware (current-options options)))
:when (instance? clojure.lang.IRef varr)]
(add-watch varr ::reload (fn [_key _ref _old-state _new-state]
(log/infof "%s changed, rebuilding handler" varr)
- (reset! handler (apply-middleware server-routes)))))
+ (reset! handler (rebuild)))))
(fn dev-handler* [request respond raise]
(@handler request respond raise))))
(mu/defn make-handler :- ::api.macros/handler
- "Create the primary entry point to the Ring HTTP server."
- [server-routes :- ::api.macros/handler]
+ "Create the primary entry point to the Ring HTTP server, with middleware configured by `options`.
+ Pass `options` as a var to have the dev handler rebuild when it is redefined."
+ [server-routes :- ::api.macros/handler
+ options :- OptionsOrVar]
(if config/is-dev?
- (dev-handler server-routes)
- (apply-middleware server-routes)))
+ (dev-handler server-routes options)
+ (apply-middleware server-routes (current-options options))))
diff --git a/src/metabase/server/instance.clj b/src/metabase/server/instance.clj
index 6ea8ac7c810..78930ed8f0d 100644
--- a/src/metabase/server/instance.clj
+++ b/src/metabase/server/instance.clj
@@ -139,8 +139,12 @@
"Start the embedded Jetty web server. Returns `:started` if a new server was started; `nil` if there was already a
running server.
- (let [server-routes (metabase.server.core/make-routes #'metabase.api-routes.core/routes)
- handler (metabase.server.core/make-handler server-routes)]
+ (let [server-routes (metabase.server.core/make-routes
+ {:api #'metabase.api-routes.core/routes
+ :auth #'metabase.sso.auth-wrapper/routes
+ :oauth #'metabase.oauth-server.api/oauth-routes
+ :well-known #'metabase.oauth-server.api/well-known-routes})
+ handler (metabase.server.core/make-handler server-routes #'metabase.mcp.http-handler/options)]
(metabase.server.core/start-web-server! handler))"
[handler :- ::api.macros/handler]
(when-not (instance)
diff --git a/src/metabase/server/middleware/exceptions.clj b/src/metabase/server/middleware/exceptions.clj
index b0083a7eb7c..6bc22fc0f31 100644
--- a/src/metabase/server/middleware/exceptions.clj
+++ b/src/metabase/server/middleware/exceptions.clj
@@ -18,6 +18,12 @@
(declare api-exception-response)
+(def ^:private cors-key ::cors)
+
+(defn- security-headers [request]
+ (mw.security/security-headers :origin (get-in request [:headers "origin"])
+ :cors (get request cors-key)))
+
(defmulti api-exception-response
"Convert an uncaught exception from an API endpoint into an appropriate format to be returned by the REST API (e.g. a
map, which eventually gets serialized to JSON, or a plain string message). `request` is the Ring request that
@@ -27,7 +33,7 @@
(class e)))
(defmethod api-exception-response Throwable
- [^Throwable e _request]
+ [^Throwable e request]
(let [{:keys [status-code], :as info} (ex-data e)
other-info (dissoc info :status-code :schema :type :toucan2/context-trace ::log/context)
body (cond
@@ -63,7 +69,7 @@
(when (nil? status-code)
(analytics/inc! :metabase-api/unhandled-errors))
{:status (or status-code 500)
- :headers (mw.security/security-headers)
+ :headers (security-headers request)
:body body}))
(defmethod api-exception-response SQLException
@@ -78,17 +84,19 @@
(or (some-> request-method name u/upper-case-en) "?")
uri
(or (request/ip-address request) "unknown"))
- {:status-code 204, :body nil, :headers (mw.security/security-headers)})
+ {:status-code 204, :body nil, :headers (security-headers request)})
(defn catch-api-exceptions
"Middleware (with `[request respond raise]`) that catches API Exceptions and returns them in our normal-style format rather than the Jetty 500
Stacktrace page, which is not so useful for our frontend."
- [handler]
- (fn [request respond _raise]
- (handler
- request
- respond
- #(respond (api-exception-response % request)))))
+ ([handler]
+ (catch-api-exceptions handler nil))
+ ([handler cors]
+ (fn [request respond _raise]
+ (handler
+ request
+ respond
+ #(respond (api-exception-response % (assoc request cors-key cors)))))))
(defn catch-uncaught-exceptions
"Middleware (with `[request respond raise]`) that catches any unexpected Exceptions and reroutes them through `raise`
diff --git a/src/metabase/server/middleware/security.clj b/src/metabase/server/middleware/security.clj
index c0d0a21b61f..43fec63621c 100644
--- a/src/metabase/server/middleware/security.clj
+++ b/src/metabase/server/middleware/security.clj
@@ -9,7 +9,6 @@
[metabase.analytics.core :as analytics]
[metabase.config.core :as config]
[metabase.embedding.settings :as embedding.settings]
- [metabase.mcp.core :as mcp]
[metabase.premium-features.core :refer [defenterprise]]
[metabase.request.core :as request]
[metabase.server.settings :as server.settings]
@@ -500,22 +499,25 @@
approved-list)))))))
(defn access-control-headers
- "Returns headers for CORS requests. Merges embedding SDK origins and MCP app origins."
- [origin approved-origins]
- (let [mcp-origins (mcp/cors-origins)
- all-origins (str/trim (str approved-origins " " mcp-origins))
- localhost-allowed? (and (localhost-origin? origin) (not (server.settings/disable-cors-on-localhost)))
- mcp-sandbox? (mcp/sandbox-origin? origin)]
- (when (or (seq all-origins) localhost-allowed? mcp-sandbox?)
- (merge
- (when (or (approved-origin? origin all-origins) mcp-sandbox?)
- {"Access-Control-Allow-Origin" origin
- "Vary" "Origin"})
- {"Access-Control-Allow-Headers" "*"
- "Access-Control-Allow-Methods" "*"
- "Access-Control-Expose-Headers" "Content-Disposition, X-Metabase-Anti-CSRF-Token, X-Metabase-Version, Mcp-Session-Id"
- ;; Needed for Embedding SDK. Should cache preflight requests for the specified number of seconds.
- "Access-Control-Max-Age" "60"}))))
+ "Returns headers for CORS requests. `cors` can supply an `:origins-fn` and a
+ `:sandbox-origin?-fn` for origins owned by a higher-level module."
+ ([origin approved-origins]
+ (access-control-headers origin approved-origins nil))
+ ([origin approved-origins {:keys [origins-fn sandbox-origin?-fn]}]
+ (let [extra-origins (when origins-fn (origins-fn))
+ all-origins (str/trim (str approved-origins " " extra-origins))
+ localhost-allowed? (and (localhost-origin? origin) (not (server.settings/disable-cors-on-localhost)))
+ sandbox-origin? (boolean (and sandbox-origin?-fn (sandbox-origin?-fn origin)))]
+ (when (or (seq all-origins) localhost-allowed? sandbox-origin?)
+ (merge
+ (when (or (approved-origin? origin all-origins) sandbox-origin?)
+ {"Access-Control-Allow-Origin" origin
+ "Vary" "Origin"})
+ {"Access-Control-Allow-Headers" "*"
+ "Access-Control-Allow-Methods" "*"
+ "Access-Control-Expose-Headers" "Content-Disposition, X-Metabase-Anti-CSRF-Token, X-Metabase-Version, Mcp-Session-Id"
+ ;; Needed for Embedding SDK. Should cache preflight requests for the specified number of seconds.
+ "Access-Control-Max-Age" "60"})))))
(defn security-headers
"Fetch a map of security headers that should be added to a response based on the passed options.
@@ -524,7 +526,7 @@
embedding is configured). `:script-nonce?` adds the nonce to `script-src`, see
[[script-nonce-response-key]]."
[& {:keys [origin nonce script-nonce? frame-ancestors allow-cache? data-app-iframe? data-app-connect-hosts
- allow-blob-img?]
+ allow-blob-img? cors]
:or {frame-ancestors :none, allow-cache? false, script-nonce? false, data-app-iframe? false,
allow-blob-img? false}}]
(merge
@@ -532,7 +534,7 @@
strict-transport-security-header
(content-security-policy-header-with-frame-ancestors frame-ancestors nonce script-nonce? data-app-iframe?
data-app-connect-hosts allow-blob-img?)
- (access-control-headers origin (embedding.settings/embedding-app-origins-sdk))
+ (access-control-headers origin (embedding.settings/embedding-app-origins-sdk) cors)
;; Tell browsers not to render our site as an iframe (prevent clickjacking)
(x-frame-options-header frame-ancestors)
{;; Prevent Flash / PDF files from including content from site.
@@ -643,10 +645,11 @@
(or (<= 200 status 299)
(= status 304)))))
-(defn- add-security-headers* [request response]
+(defn- add-security-headers* [cors request response]
;; merge is other way around so that handler can override headers
(let [headers (security-headers
:origin (get (:headers request) "origin")
+ :cors cors
:nonce (:nonce request)
:script-nonce? (boolean (get response script-nonce-response-key))
;; The internal data-app iframe is only ever framed by the
@@ -682,11 +685,14 @@
(update response :headers #(merge %2 %1 cors-headers) headers)))
(defn add-security-headers
- "Middleware that adds HTTP security and cache-busting headers."
- [handler]
- (fn [request respond raise]
- (let [request (assoc request :nonce (generate-nonce))]
- (handler
- request
- (comp respond (partial add-security-headers* request))
- raise))))
+ "Middleware that adds HTTP security and cache-busting headers. `cors` contains optional callbacks supplied by the
+ application when it constructs the handler."
+ ([handler]
+ (add-security-headers handler nil))
+ ([handler cors]
+ (fn [request respond raise]
+ (let [request (assoc request :nonce (generate-nonce))]
+ (handler
+ request
+ (comp respond (partial add-security-headers* cors request))
+ raise)))))
diff --git a/src/metabase/server/middleware/session.clj b/src/metabase/server/middleware/session.clj
index 83261b6a4ab..1bd4629409f 100644
--- a/src/metabase/server/middleware/session.clj
+++ b/src/metabase/server/middleware/session.clj
@@ -24,8 +24,6 @@
[metabase.api.macros.scope :as scope]
[metabase.config.core :as config]
[metabase.initialization-status.core :as init-status]
- [metabase.mcp.core :as mcp]
- [metabase.oauth-server.core :as oauth-server]
[metabase.premium-features.core :as premium-features]
[metabase.request.core :as request]
[metabase.request.schema :as request.schema]
@@ -39,6 +37,7 @@
[metabase.util.log :as log]
[metabase.util.malli :as mu]
[metabase.util.malli.registry :as mr]
+ [metabase.util.malli.schema :as ms]
[metabase.util.password :as u.password]
[metabase.util.string :as string]))
@@ -162,6 +161,22 @@
(-> user-info
(dissoc :api-key)))))))
+(mr/def ::oauth-bearer
+ "Fns that authenticate a request by its OAuth bearer token, and the scope that grants full access."
+ [:map
+ {:closed true}
+ [:extract-token ifn?]
+ [:resolve-token ifn?]
+ [:full-access-scope ms/NonBlankString]])
+
+(mr/def ::mcp-ui-credentials
+ "Fns that authenticate a request by the credential an MCP App UI carries."
+ [:map
+ {:closed true}
+ [:on-surface? ifn?]
+ [:resolve-credential ifn?]
+ [:scope-satisfied? ifn?]])
+
(def ^:private full-access-token-scopes
"The `:token-scopes` value that grants a bearer-authenticated request access to the general
REST API as its user. The `::scope/unrestricted` keyword sentinel (not the `\"*\"` string)
@@ -179,8 +194,8 @@
This mapping is the single trust hinge for OAuth bearer auth on the general API; keep it here
and unit-test the two directions (full ⇒ unrestricted, narrow ⇒ passed through) so the
security invariant can't silently regress."
- [granted-scopes]
- (if (contains? granted-scopes oauth-server/full-access-scope)
+ [full-access-scope granted-scopes]
+ (if (contains? granted-scopes full-access-scope)
full-access-token-scopes
granted-scopes))
@@ -190,15 +205,16 @@
merged request carries both the user identity and the access the token was granted, and marks it
`:authenticated-via-oauth?`. A token with no scopes does not authenticate. This is the only place an
OAuth access token authenticates a request to the general (`/api/*`) API."
- [request :- ::request.schema/request]
- (when (init-status/complete?)
- (when-let [token (oauth-server/extract-bearer-token request)]
- (when-let [{:keys [user-id scopes]} (oauth-server/resolve-access-token token)]
+ [{:keys [extract-token resolve-token full-access-scope]} :- [:maybe ::oauth-bearer]
+ request :- ::request.schema/request]
+ (when (and extract-token (init-status/complete?))
+ (when-let [token (extract-token request)]
+ (when-let [{:keys [user-id scopes]} (resolve-token token)]
;; Downstream, nil `:token-scopes` passes as scope-unaware auth, so a scope-less token is refused here.
(when (seq scopes)
(some-> (server.db/oauth-user-info user-id (premium-features/enable-advanced-permissions?))
(m/update-existing :is-group-manager? boolean)
- (assoc :token-scopes (oauth-token->token-scopes scopes)
+ (assoc :token-scopes (oauth-token->token-scopes full-access-scope scopes)
:authenticated-via-oauth? true)))))))
(defn- current-user-info-for-mcp-ui-credential
@@ -223,16 +239,16 @@
the decision on its own: `ensure-scopes-checked` passes anything whose `:token-scopes` is nil. Drop the
stamp and an unsatisfied route is served rather than refused. `dataset-routes-cost-the-query-scope-test`
is what catches that."
- [request]
- (when (and (init-status/complete?)
- (mcp/ui-credential-on-surface? (:request-method request) (:uri request)))
+ [{:keys [on-surface? resolve-credential scope-satisfied?]} request]
+ (when (and on-surface?
+ (init-status/complete?)
+ (on-surface? (:request-method request) (:uri request)))
(when-let [{:keys [uid sid] :as claims}
- (mcp/resolve-ui-credential (get-in request [:headers "x-metabase-mcp-ui-auth"]))]
+ (resolve-credential (get-in request [:headers "x-metabase-mcp-ui-auth"]))]
(some-> (server.db/oauth-user-info uid (premium-features/enable-advanced-permissions?))
(m/update-existing :is-group-manager? boolean)
(assoc :token-scopes #{::scope/mcp-ui}
- :token-scopes-checked (mcp/ui-credential-scope-satisfied?
- (:request-method request) (:uri request) claims)
+ :token-scopes-checked (scope-satisfied? (:request-method request) (:uri request) claims)
:mcp-ui-session-id sid
:mcp-ui-credential claims)))))
@@ -245,14 +261,15 @@
mcp-ui-info "mcp-ui")))
(defn- merge-current-user-info
- [{:keys [metabase-session-key anti-csrf-token], {:strs [x-metabase-locale x-api-key]} :headers, :as request}]
+ [{:keys [oauth-bearer mcp-ui-credentials]}
+ {:keys [metabase-session-key anti-csrf-token], {:strs [x-metabase-locale x-api-key]} :headers, :as request}]
(let [session-info (current-user-info-for-session metabase-session-key anti-csrf-token)
api-key-info (when-not session-info (current-user-info-for-api-key x-api-key))
;; Bearer and MCP UI credentials are consulted only when no normal session/API key authenticated.
oauth-info (when-not (or session-info api-key-info)
- (current-user-info-for-oauth-token request))
+ (current-user-info-for-oauth-token oauth-bearer request))
mcp-ui-info (when-not (or session-info api-key-info oauth-info)
- (current-user-info-for-mcp-ui-credential request))
+ (current-user-info-for-mcp-ui-credential mcp-ui-credentials request))
embedding-route (analytics/get-route)
auth-method (auth-method session-info api-key-info oauth-info mcp-ui-info embedding-route)]
(merge
@@ -268,13 +285,17 @@
(defn wrap-current-user-info
"Add `:metabase-user-id`, `:is-superuser?`, `:is-group-manager?` and `:user-locale` to the request if a valid session
token, API key, OAuth bearer access token, OR MCP UI credential was passed. A bearer token additionally sets
- `:token-scopes` (the access it was granted); precedence is session > API key > bearer > MCP UI credential."
- [handler]
- (fn [request respond raise]
- (let [request' (tracing/with-span :db-app "db-app.session-lookup" {}
- (merge-current-user-info request))]
- (analytics/with-auth-method! (:embedding/auth-method request')
- (handler request' respond raise)))))
+ `:token-scopes` (the access it was granted); precedence is session > API key > bearer > MCP UI credential.
+ Bearer tokens and MCP UI credentials authenticate only when `options` supplies their `:oauth-bearer` and
+ `:mcp-ui-credentials` fns."
+ ([handler]
+ (wrap-current-user-info handler nil))
+ ([handler options]
+ (fn [request respond raise]
+ (let [request' (tracing/with-span :db-app "db-app.session-lookup" {}
+ (merge-current-user-info options request))]
+ (analytics/with-auth-method! (:embedding/auth-method request')
+ (handler request' respond raise))))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | bind-current-user |
diff --git a/src/metabase/server/routes.clj b/src/metabase/server/routes.clj
index 5b4b2715e6f..be82e4d54fd 100644
--- a/src/metabase/server/routes.clj
+++ b/src/metabase/server/routes.clj
@@ -9,10 +9,8 @@
[metabase.app-db.core :as mdb]
[metabase.appearance.core :as appearance]
[metabase.initialization-status.core :as init-status]
- [metabase.oauth-server.api :as oauth-server.api]
[metabase.query-processor.schema :as qp.schema]
[metabase.request.core :as request]
- [metabase.server.auth-wrapper :as auth-wrapper]
[metabase.server.middleware.embedding-sdk-bundle :as mw.embedding-sdk-bundle]
[metabase.server.routes.index :as index]
[metabase.server.routes.static :as static]
@@ -102,14 +100,20 @@
(api-routes request respond raise))))
(mu/defn make-routes :- ::api.macros/handler
- "Create the top-level Ring route handler for Metabase."
- [api-routes :- ::api.macros/handler]
+ "Create the top-level Ring route handler for Metabase from the handlers that modules above `server` supply:
+ `:api` for `/api`, `:auth` for `/auth`, and `:oauth` and `:well-known` for the OAuth provider."
+ [{:keys [api auth oauth well-known]} :- [:map
+ {:closed true}
+ [:api ::api.macros/handler]
+ [:auth ::api.macros/handler]
+ [:oauth ::api.macros/handler]
+ [:well-known ::api.macros/handler]]]
;; top-level routes defined outside the api.macros surface (SPA shell, health, redirects) have no OpenAPI metadata
#_{:clj-kondo/ignore [:discouraged-var]}
(compojure/routes
- auth-wrapper/routes
- (context "/.well-known" [] oauth-server.api/well-known-routes)
- (context "/oauth" [] oauth-server.api/oauth-routes)
+ auth
+ (context "/.well-known" [] well-known)
+ (context "/oauth" [] oauth)
;; ^/$ -> index.html
(GET "/" [] index/index)
(GET "/favicon.ico" [] (response/resource-response (appearance/application-favicon-url)))
@@ -123,7 +127,7 @@
(OPTIONS "/auth/*" [] {:status 200 :body ""})
(OPTIONS "/api/*" [] {:status 200 :body ""})
;; ^/api/ -> All other API routes
- (context "/api" [] (api-handler api-routes))
+ (context "/api" [] (api-handler api))
;; ^/app/ -> static files under frontend_client/app
(context "/app" [] static-files-handler)
;; ^/public/ -> Public frontend and download routes
diff --git a/src/metabase/server/auth_wrapper.clj b/src/metabase/sso/auth_wrapper.clj
similarity index 89%
rename from src/metabase/server/auth_wrapper.clj
rename to src/metabase/sso/auth_wrapper.clj
index d08248aba94..abcb899d381 100644
--- a/src/metabase/server/auth_wrapper.clj
+++ b/src/metabase/sso/auth_wrapper.clj
@@ -1,4 +1,4 @@
-(ns metabase.server.auth-wrapper
+(ns metabase.sso.auth-wrapper
(:require
[metabase.api.util.handlers :as handlers]
[metabase.config.core :as config]
@@ -18,7 +18,7 @@
"/api" {"/saml" not-enabled
"/ee" {"/sso" {"/oidc" not-enabled}}}}))
-;; This needs to be injected into [[metabase.server.routes/routes]] -- not [[metabase.api-routes.core/routes]] !!!
+;; This needs to be injected into [[metabase.server.routes/make-routes]] -- not [[metabase.api-routes.core/routes]] !!!
(def routes
"Ring routes for auth API endpoints.
Slack Connect (OSS) is always available. Other SSO routes (SAML, JWT, OIDC) require EE."
diff --git a/src/metabase/task/bootstrap.clj b/src/metabase/task/bootstrap.clj
deleted file mode 100644
index 4cec974e70d..00000000000
--- a/src/metabase/task/bootstrap.clj
+++ /dev/null
@@ -1,71 +0,0 @@
-(ns metabase.task.bootstrap
- (:require
- [metabase.classloader.core :as classloader]
- [metabase.task.secure-delegate :as secure-delegate]
- [metabase.util.log :as log]))
-
-(set! *warn-on-reflection* true)
-
-;; Optional interceptor for wrapping JDBC connections before Quartz uses them.
-;; Set by task.tracing to add SQL-level tracing. nil means no interception.
-(defonce ^:private connection-interceptor (atom nil))
-
-(defn set-connection-interceptor!
- "Set an optional function to wrap JDBC connections before Quartz uses them.
- Called by task.tracing to add SQL-level tracing. Pass nil to remove."
- [f]
- (reset! connection-interceptor f))
-
-(defn intercept-connection
- "Wrap `conn` with the interceptor set by [[set-connection-interceptor!]], if any."
- [conn]
- (if-let [interceptor @connection-interceptor]
- (interceptor conn)
- conn))
-
-(defn- load-class ^Class [^String class-name]
- (Class/forName class-name true (classloader/the-classloader)))
-
-(defrecord ^:private ClassLoadHelper []
- org.quartz.spi.ClassLoadHelper
- (initialize [_])
- (getClassLoader [_]
- (classloader/the-classloader))
- (loadClass [_ class-name]
- (load-class class-name))
- (loadClass [_ class-name _]
- (load-class class-name)))
-
-(when-not *compile-files*
- (System/setProperty "org.quartz.scheduler.classLoadHelper.class" (.getName ClassLoadHelper)))
-
-(defonce ^:private jdbc-property-setters
- ;; Extra fns (of db-type) run by set-jdbc-backend-properties! right before the scheduler initializes.
- ;; Lets a higher-level module (e.g. `mq`, which installs its node-affinity Quartz DriverDelegate)
- ;; hook in without `task` depending on it — `task` cannot depend on the modules that depend on it.
- (atom []))
-
-(defn register-jdbc-property-setter!
- "Register `f` (a fn of the app-db `db-type`) to run when Quartz's JDBC backend properties are set,
- just before the scheduler initializes. Used by the `mq` module to install its node-affinity
- `DriverDelegate` — registering here inverts the dependency so `task` never references `mq`."
- [f]
- (swap! jdbc-property-setters conj f))
-
-(defn set-jdbc-backend-properties!
- "Set the appropriate system properties needed so Quartz can connect to the JDBC backend. (Since we don't know our DB
- connection properties ahead of time, we'll need to set these at runtime rather than Setting them in the
- `quartz.properties` file.)
-
- Installs Metabase's per-DB `DriverDelegate` (see [[metabase.task.secure-delegate]]): a
- `StdJDBCDelegate`/`PostgreSQLDelegate` subclass that reads BLOB columns through a class allow-list, so
- Quartz reconstructs only the plain-data classes Metabase's job data is made of. Then runs any setters
- registered via [[register-jdbc-property-setter!]]. A registered setter that throws is logged and
- skipped so the scheduler still gets a working delegate."
- [db-type]
- (secure-delegate/install! db-type)
- (doseq [setter @jdbc-property-setters]
- (try
- (setter db-type)
- (catch Throwable t
- (log/warnf "A registered Quartz JDBC property setter failed; continuing: %s" (ex-message t))))))
diff --git a/src/metabase/task/impl.clj b/src/metabase/task/impl.clj
index 0f0640b754c..54df0b73a58 100644
--- a/src/metabase/task/impl.clj
+++ b/src/metabase/task/impl.clj
@@ -23,8 +23,8 @@
[clojurewerkz.quartzite.scheduler :as qs]
[environ.core :as env]
[metabase.app-db.core :as mdb]
+ [metabase.app-db.quartz]
[metabase.classloader.core :as classloader]
- [metabase.task.bootstrap]
[metabase.task.job-factory :as job-factory]
[metabase.tracing.core :as tracing]
[metabase.util :as u]
@@ -87,7 +87,7 @@
;;; +----------------------------------------------------------------------------------------------------------------+
(defn- set-jdbc-backend-properties! []
- (metabase.task.bootstrap/set-jdbc-backend-properties! (mdb/db-type)))
+ (metabase.app-db.quartz/set-jdbc-backend-properties! (mdb/db-type)))
(defn- delete-jobs-with-no-class!
"Delete any jobs that have been scheduled but whose class is no longer available."
diff --git a/src/metabase/task/secure_delegate.clj b/src/metabase/task/secure_delegate/core.clj
similarity index 93%
rename from src/metabase/task/secure_delegate.clj
rename to src/metabase/task/secure_delegate/core.clj
index 3bc783135f1..494b0a64ffd 100644
--- a/src/metabase/task/secure_delegate.clj
+++ b/src/metabase/task/secure_delegate/core.clj
@@ -1,4 +1,4 @@
-(ns metabase.task.secure-delegate
+(ns metabase.task.secure-delegate.core
"Metabase's Quartz `DriverDelegate`s and their installation.
Quartz's stock delegate reads BLOB columns with a bare `ObjectInputStream`, which reconstructs any
@@ -12,7 +12,7 @@
The delegate classes are `gen-class`. [[install!]] loads the one matching the app DB and sets it as
Quartz's `driverDelegateClass`; it must run before the scheduler initializes (see
- `metabase.task.bootstrap`)."
+ `metabase.app-db.quartz`)."
(:require
[clojure.java.io :as io]
[metabase.classloader.core :as classloader]
@@ -58,8 +58,10 @@
;; Postgres uses PostgreSQLDelegate (byte-based BLOB handling); everything else uses StdJDBCDelegate.
(def ^:private delegate
- {:postgres {:class "metabase.task.SecurePostgresDelegate" :ns 'metabase.task.secure-delegate-postgres}
- :default {:class "metabase.task.SecureStdDelegate" :ns 'metabase.task.secure-delegate-std}})
+ {:postgres {:class "metabase.task.secure_delegate.SecurePostgresDelegate"
+ :ns 'metabase.task.secure-delegate.postgres}
+ :default {:class "metabase.task.secure_delegate.SecureStdDelegate"
+ :ns 'metabase.task.secure-delegate.std}})
(defn- class-loadable? [^String class-name]
(try
diff --git a/src/metabase/task/secure_delegate_postgres.clj b/src/metabase/task/secure_delegate/postgres.clj
similarity index 51%
rename from src/metabase/task/secure_delegate_postgres.clj
rename to src/metabase/task/secure_delegate/postgres.clj
index a669d9b2269..cbb7c4b01b7 100644
--- a/src/metabase/task/secure_delegate_postgres.clj
+++ b/src/metabase/task/secure_delegate/postgres.clj
@@ -1,15 +1,15 @@
-(ns metabase.task.secure-delegate-postgres
+(ns metabase.task.secure-delegate.postgres
"Quartz `DriverDelegate` for Postgres: `PostgreSQLDelegate` (byte-based BLOB reads) with
`getObjectFromBlob` overridden to read through the allow-list. The postgres counterpart of
- `metabase.task.secure-delegate-std`; keep them in sync. See [[metabase.task.secure-delegate]]."
+ `metabase.task.secure-delegate.std`; keep them in sync. See [[metabase.task.secure-delegate.core]]."
(:gen-class :extends org.quartz.impl.jdbcjobstore.PostgreSQLDelegate
- :name metabase.task.SecurePostgresDelegate)
+ :name metabase.task.secure_delegate.SecurePostgresDelegate)
(:require
- [metabase.task.secure-delegate :as secure-delegate]))
+ [metabase.task.secure-delegate.core :as secure-delegate]))
(set! *warn-on-reflection* true)
(defn -getObjectFromBlob
- "gen-class override — see [[metabase.task.secure-delegate/object-from-blob-postgres]]."
+ "gen-class override — see [[metabase.task.secure-delegate.core/object-from-blob-postgres]]."
[_this rs col-name]
(secure-delegate/object-from-blob-postgres rs col-name))
diff --git a/src/metabase/task/secure_delegate_std.clj b/src/metabase/task/secure_delegate/std.clj
similarity index 51%
rename from src/metabase/task/secure_delegate_std.clj
rename to src/metabase/task/secure_delegate/std.clj
index ee0726e0c7c..2a28c874eec 100644
--- a/src/metabase/task/secure_delegate_std.clj
+++ b/src/metabase/task/secure_delegate/std.clj
@@ -1,15 +1,15 @@
-(ns metabase.task.secure-delegate-std
+(ns metabase.task.secure-delegate.std
"Quartz `DriverDelegate` for H2/MySQL: `StdJDBCDelegate` with `getObjectFromBlob` overridden to read
- through the allow-list. Logic lives in [[metabase.task.secure-delegate]]; keep this in sync with
- `metabase.task.secure-delegate-postgres` (differs only in base class)."
+ through the allow-list. Logic lives in [[metabase.task.secure-delegate.core]]; keep this in sync with
+ `metabase.task.secure-delegate.postgres` (differs only in base class)."
(:gen-class :extends org.quartz.impl.jdbcjobstore.StdJDBCDelegate
- :name metabase.task.SecureStdDelegate)
+ :name metabase.task.secure_delegate.SecureStdDelegate)
(:require
- [metabase.task.secure-delegate :as secure-delegate]))
+ [metabase.task.secure-delegate.core :as secure-delegate]))
(set! *warn-on-reflection* true)
(defn -getObjectFromBlob
- "gen-class override — see [[metabase.task.secure-delegate/object-from-blob-std]]."
+ "gen-class override — see [[metabase.task.secure-delegate.core/object-from-blob-std]]."
[_this rs col-name]
(secure-delegate/object-from-blob-std rs col-name))
diff --git a/src/metabase/tracing/quartz.clj b/src/metabase/tracing/quartz.clj
index e1d93110d4c..2593eaaf412 100644
--- a/src/metabase/tracing/quartz.clj
+++ b/src/metabase/tracing/quartz.clj
@@ -14,7 +14,7 @@
Both are gated on the `:quartz` trace group — zero overhead when disabled."
(:require
[clojure.string :as str]
- [metabase.task.bootstrap :as task.bootstrap]
+ [metabase.app-db.quartz :as app-db.quartz]
[metabase.task.core :as task]
[metabase.tracing.core :as tracing]
[metabase.util :as u]
@@ -189,4 +189,4 @@
(defmethod task/init! ::QuartzTracing [_]
(log/info "Initializing Quartz tracing instrumentation")
(task/add-job-listener! (create-tracing-job-listener))
- (task.bootstrap/set-connection-interceptor! connection-interceptor))
+ (app-db.quartz/set-connection-interceptor! connection-interceptor))
diff --git a/src/metabase/transforms/notification.clj b/src/metabase/transforms/notification.clj
index 99384ed799e..f37d263beda 100644
--- a/src/metabase/transforms/notification.clj
+++ b/src/metabase/transforms/notification.clj
@@ -50,7 +50,7 @@
"Event info for the failure digest, covering the previous calendar day."
[]
(let [yesterday (u.date/add (t/zoned-date-time (digest-timezone)) :day -1)
- {:keys [start end]} (u.date/range yesterday :day)
+ {:keys [start end]} (u.date/range {:start-of-week :sunday} yesterday :day)
jobs (failing-jobs start end)]
{:job_count (count jobs)
:failure_count (reduce + 0 (map :failure_count jobs))
diff --git a/src/metabase/util/date_2.clj b/src/metabase/util/date_2.clj
index a04dad6bbea..c9194f27107 100644
--- a/src/metabase/util/date_2.clj
+++ b/src/metabase/util/date_2.clj
@@ -218,8 +218,14 @@
;; operation. Maybe we should rename this unit to clear up the potential confusion (?)
:year})
-(defn- start-of-week []
- ((requiring-resolve 'metabase.settings.core/get) :start-of-week))
+(def ^:private TimeConfig
+ ;; Mirrors ::lib.schema.common/time-config, duplicated because util can't depend on lib.
+ [:map
+ {:closed true}
+ [:start-of-week [:enum :monday :tuesday :wednesday :thursday :friday :saturday :sunday]]])
+
+(def ^:private ComparisonType
+ [:enum := :< :<= :> :>=])
(let [m (u.date.common/static-instances DayOfWeek)]
(defn- day-of-week*
@@ -244,34 +250,33 @@
(mu/defn extract :- :int
"Extract a field such as `:minute-of-hour` from a temporal value `t`.
- (extract (t/zoned-date-time \"2019-11-05T15:44-08:00[US/Pacific]\") :day-of-month)
+ (extract {:start-of-week :sunday}
+ (t/zoned-date-time \"2019-11-05T15:44-08:00[US/Pacific]\") :day-of-month)
;; -> 5
Values are returned as numbers (currently, always and integers, but this may change if we add support for
- `:fraction-of-second` in the future.)"
- ([unit :- (into [:enum] (conj extract-units :day-of-week-iso))]
- (extract (t/zoned-date-time) unit))
-
- ([t :- TemporalInstance
- unit :- (into [:enum] (conj extract-units :day-of-week-iso))]
- (t/as t (case unit
- :second-of-minute :second-of-minute
- :minute-of-hour :minute-of-hour
- :hour-of-day :hour-of-day
- :day-of-week (.dayOfWeek (week-fields (start-of-week)))
- :day-of-week-iso (.dayOfWeek (week-fields :monday))
- :day-of-month :day-of-month
- :day-of-year :day-of-year
- :week-of-year (.weekOfYear (week-fields (start-of-week)))
- :month-of-year :month-of-year
- :quarter-of-year :quarter-of-year
- :year :year))))
+ `:fraction-of-second` in the future.) `time-config` controls the first day used by week-based fields."
+ [{:keys [start-of-week]} :- TimeConfig
+ t :- TemporalInstance
+ unit :- (into [:enum] (conj extract-units :day-of-week-iso))]
+ (t/as t (case unit
+ :second-of-minute :second-of-minute
+ :minute-of-hour :minute-of-hour
+ :hour-of-day :hour-of-day
+ :day-of-week (.dayOfWeek (week-fields start-of-week))
+ :day-of-week-iso (.dayOfWeek (week-fields :monday))
+ :day-of-month :day-of-month
+ :day-of-year :day-of-year
+ :week-of-year (.weekOfYear (week-fields start-of-week))
+ :month-of-year :month-of-year
+ :quarter-of-year :quarter-of-year
+ :year :year)))
(defmulti ^TemporalAdjuster adjuster
"Get the custom `TemporalAdjuster` named by `k`.
;; adjust 2019-12-10T17:26 to the second week of the year
- (t/adjust #t \"2019-12-10T17:26\" (u.date/adjuster :week-of-year 2)) ;; -> #t \"2019-01-06T17:26\""
+ (t/adjust #t \"2019-12-10T17:26\" (u.date/adjuster :week-of-year 2 :sunday)) ;; -> #t \"2019-01-06T17:26\""
{:arglists '([k & args])}
(fn [k & _] (keyword k)))
@@ -280,10 +285,10 @@
(throw (Exception. (tru "No temporal adjuster named {0}" k))))
(defmethod adjuster :first-day-of-week
- [_]
+ [_ start-of-week]
(reify TemporalAdjuster
(adjustInto [_ t]
- (t/adjust t :previous-or-same-day-of-week (start-of-week)))))
+ (t/adjust t :previous-or-same-day-of-week start-of-week))))
(defmethod adjuster :first-day-of-quarter
[_]
@@ -292,19 +297,19 @@
(.with t (.atDay (t/year-quarter t) 1)))))
(defmethod adjuster :first-week-of-year
- [_]
+ [_ start-of-week]
(reify TemporalAdjuster
(adjustInto [_ t]
(-> t
(t/adjust :first-day-of-year)
- (t/adjust (adjuster :first-day-of-week))))))
+ (t/adjust (adjuster :first-day-of-week start-of-week))))))
(defmethod adjuster :week-of-year
- [_ week-of-year]
+ [_ week-of-year start-of-week]
(reify TemporalAdjuster
(adjustInto [_ t]
(-> t
- (t/adjust (adjuster :first-week-of-year))
+ (t/adjust (adjuster :first-week-of-year start-of-week))
(t/plus (t/weeks (dec week-of-year)))))))
;; if you attempt to truncate a `LocalDate` to `:day` or anything smaller we can go ahead and return it as is
@@ -329,23 +334,21 @@
(mu/defn truncate :- TemporalInstance
"Truncate a temporal value `t` to the beginning of `unit`, e.g. `:hour` or `:day`. Not all truncation units are
supported on all subclasses of `Temporal` — for example, you can't truncate a `LocalTime` to `:month`, for obvious
- reasons."
- ([unit :- (into [:enum] truncate-units)]
- (truncate (t/zoned-date-time) unit))
-
- ([^Temporal t :- TemporalInstance
- unit :- (into [:enum] truncate-units)]
- (case unit
- :default t
- :millisecond (t/truncate-to t :millis)
- :second (t/truncate-to t :seconds)
- :minute (t/truncate-to t :minutes)
- :hour (t/truncate-to t :hours)
- :day (t/truncate-to t :days)
- :week (-> (.with t (adjuster :first-day-of-week)) (t/truncate-to :days))
- :month (-> (t/adjust t :first-day-of-month) (t/truncate-to :days))
- :quarter (-> (.with t (adjuster :first-day-of-quarter)) (t/truncate-to :days))
- :year (-> (t/adjust t :first-day-of-year) (t/truncate-to :days)))))
+ reasons. `time-config` controls the beginning of a week."
+ [{:keys [start-of-week]} :- TimeConfig
+ ^Temporal t :- TemporalInstance
+ unit :- (into [:enum] truncate-units)]
+ (case unit
+ :default t
+ :millisecond (t/truncate-to t :millis)
+ :second (t/truncate-to t :seconds)
+ :minute (t/truncate-to t :minutes)
+ :hour (t/truncate-to t :hours)
+ :day (t/truncate-to t :days)
+ :week (-> (.with t (adjuster :first-day-of-week start-of-week)) (t/truncate-to :days))
+ :month (-> (t/adjust t :first-day-of-month) (t/truncate-to :days))
+ :quarter (-> (.with t (adjuster :first-day-of-quarter)) (t/truncate-to :days))
+ :year (-> (t/adjust t :first-day-of-year) (t/truncate-to :days))))
(mu/defn bucket :- [:or number? TemporalInstance]
"Perform a truncation or extraction unit on temporal value `t`. (These two operations are collectively known as
@@ -353,18 +356,19 @@
You can combine this function with `group-by` to do some date/time bucketing in Clojure-land:
- (group-by #(bucket % :quarter-of-year) (map t/local-date [\"2019-01-01\" \"2019-01-02\" \"2019-01-04\"]))
- ;; -> {1 [(t/local-date \"2019-01-01\") (t/local-date \"2019-01-02\")], 2 [(t/local-date \"2019-01-04\")]}"
- ([unit :- (into [:enum] cat [extract-units truncate-units])]
- (bucket (t/zoned-date-time) unit))
+ (group-by #(bucket {:start-of-week :sunday} % :quarter-of-year)
+ (map t/local-date [\"2019-01-01\" \"2019-01-02\" \"2019-01-04\"]))
+ ;; -> {1 [(t/local-date \"2019-01-01\") (t/local-date \"2019-01-02\")], 2 [(t/local-date \"2019-01-04\")]}
- ([t :- TemporalInstance
- unit :- (into [:enum] cat [extract-units truncate-units])]
- (cond
- (= unit :default) t
- (extract-units unit) (extract t unit)
- (truncate-units unit) (truncate t unit)
- :else (throw (Exception. (tru "Invalid unit: {0}" unit))))))
+ `time-config` controls week-based extraction and truncation."
+ [time-config :- TimeConfig
+ t :- TemporalInstance
+ unit :- (into [:enum] cat [extract-units truncate-units])]
+ (cond
+ (= unit :default) t
+ (extract-units unit) (extract time-config t unit)
+ (truncate-units unit) (truncate time-config t unit)
+ :else (throw (Exception. (tru "Invalid unit: {0}" unit)))))
(mu/defn range :- [:map
[:start TemporalInstance]
@@ -372,19 +376,20 @@
"Get a start (by default, inclusive) and end (by default, exclusive) pair of instants for a `unit` span of time
containing `t`. e.g.
- (range (t/zoned-date-time \"2019-11-01T15:29:00Z[UTC]\") :week)
+ (range {:start-of-week :sunday} (t/zoned-date-time \"2019-11-01T15:29:00Z[UTC]\") :week)
->
{:start (t/zoned-date-time \"2019-10-27T00:00Z[UTC]\")
- :end (t/zoned-date-time \"2019-11-03T00:00Z[UTC]\")}"
- ([unit :- (into [:enum] add-units)]
- (range (t/zoned-date-time) unit))
+ :end (t/zoned-date-time \"2019-11-03T00:00Z[UTC]\")}
- ([t :- TemporalInstance
- unit :- (into [:enum] add-units)]
- (range t unit nil))
+ `time-config` controls the beginning of a week."
+ ([time-config :- TimeConfig
+ t :- TemporalInstance
+ unit :- (into [:enum] add-units)]
+ (range time-config t unit nil))
- ([t :- TemporalInstance
- unit :- (into [:enum] add-units)
+ ([time-config :- TimeConfig
+ t :- TemporalInstance
+ unit :- (into [:enum] add-units)
{:keys [start end resolution]
:or {start :inclusive
end :exclusive
@@ -393,7 +398,7 @@
[:start {:optional true} [:enum :inclusive :exclusive]]
[:end {:optional true} [:enum :inclusive :exclusive]]
[:resolution {:optional true} (into [:enum] add-units)]]]]
- (let [t (truncate t unit)]
+ (let [t (truncate time-config t unit)]
{:start (case start
:inclusive t
:exclusive (add t resolution -1))
@@ -401,42 +406,52 @@
:inclusive (add (add t unit 1) resolution -1)
:exclusive (add t unit 1))})))
-(defn comparison-range
+(mu/defn comparison-range
"Generate an range that of instants that when bucketed by `unit` would be `=`, `<`, `<=`, `>`, or `>=` to the value of
an instant `t` bucketed by `unit`. (`comparison-type` is one of `:=`, `:<`, `:<=`, `:>`, or `:>=`.) By default, the
start of the resulting range is inclusive, and the end exclusive; this can be tweaked by passing `options`.
;; Generate range off instants that have the same MONTH as Nov 18th
- (comparison-range (t/local-date \"2019-11-18\") :month := {:resolution :day})
- ;; -> {:start (t/local-date \"2019-11-01\"), :end (t/local-date \"2019-12-01\")}"
- ([unit comparison-type]
- (comparison-range (t/zoned-date-time) unit comparison-type))
-
- ([t unit comparison-type]
- (comparison-range t unit comparison-type nil))
-
- ([t unit comparison-type {:keys [start end resolution]
- :or {start :inclusive
- end :exclusive
- resolution :millisecond}
- :as options}]
+ (comparison-range {:start-of-week :sunday}
+ (t/local-date \"2019-11-18\") :month := {:resolution :day})
+ ;; -> {:start (t/local-date \"2019-11-01\"), :end (t/local-date \"2019-12-01\")}
+
+ `time-config` controls the beginning of week-based ranges."
+ ([time-config :- TimeConfig
+ t :- TemporalInstance
+ unit :- (into [:enum] truncate-units)
+ comparison-type :- ComparisonType]
+ (comparison-range time-config t unit comparison-type nil))
+
+ ([time-config :- TimeConfig
+ t :- TemporalInstance
+ unit :- (into [:enum] truncate-units)
+ comparison-type :- ComparisonType
+ {:keys [start end resolution]
+ :or {start :inclusive
+ end :exclusive
+ resolution :millisecond}}
+ :- [:maybe [:map {:closed true}
+ [:start {:optional true} [:enum :inclusive :exclusive]]
+ [:end {:optional true} [:enum :inclusive :exclusive]]
+ [:resolution {:optional true} (into [:enum] add-units)]]]]
(case comparison-type
:< {:end (case end
- :inclusive (add (truncate t unit) resolution -1)
- :exclusive (truncate t unit))}
- :<= {:end (let [t (add (truncate t unit) unit 1)]
+ :inclusive (add (truncate time-config t unit) resolution -1)
+ :exclusive (truncate time-config t unit))}
+ :<= {:end (let [t (add (truncate time-config t unit) unit 1)]
(case end
:inclusive (add t resolution -1)
:exclusive t))}
- :> {:start (let [t (add (truncate t unit) unit 1)]
+ :> {:start (let [t (add (truncate time-config t unit) unit 1)]
(case start
:inclusive t
:exclusive (add t resolution -1)))}
- :>= {:start (let [t (truncate t unit)]
+ :>= {:start (let [t (truncate time-config t unit)]
(case start
:inclusive t
:exclusive (add t resolution -1)))}
- := (range t unit options))))
+ := (range time-config t unit {:start start, :end end, :resolution resolution}))))
;; Moving the type hints to the arg lists makes clj-kondo happy, but breaks eastwood (and maybe causes reflection
;; warnings) at the call sites.
diff --git a/src/metabase/util/experiment/init.clj b/src/metabase/util/experiment/init.clj
deleted file mode 100644
index e3a2ffae568..00000000000
--- a/src/metabase/util/experiment/init.clj
+++ /dev/null
@@ -1,3 +0,0 @@
-(ns metabase.util.experiment.init
- (:require
- [metabase.util.experiment.settings]))
diff --git a/src/metabase/util/experiment/settings.clj b/src/metabase/util/experiment/settings.clj
deleted file mode 100644
index 6176fe1f62d..00000000000
--- a/src/metabase/util/experiment/settings.clj
+++ /dev/null
@@ -1,18 +0,0 @@
-(ns metabase.util.experiment.settings
- (:require
- [metabase.settings.core :refer [defsetting]]
- [metabase.util.experiment :as experiment]
- [metabase.util.i18n :refer [deferred-tru]]))
-
-(defsetting experiments-enabled
- (deferred-tru "Enable or disable all code experiments. When disabled, only the production code path runs.")
- :type :boolean
- :default false
- :doc false
- :visibility :admin
- :export? false
- :audit :getter)
-
-;; Wire the setting into the experiment system. The function is called on every experiment
-;; invocation, so toggling the setting in the admin panel takes effect immediately.
-(experiment/set-experiments-enabled-fn! experiments-enabled)
diff --git a/src/metabase/util/formatting/date.cljc b/src/metabase/util/formatting/date.cljc
index 77b78475458..7352d829381 100644
--- a/src/metabase/util/formatting/date.cljc
+++ b/src/metabase/util/formatting/date.cljc
@@ -19,9 +19,10 @@
(defn ^:export format-for-parameter
"Returns a formatting date string for a datetime used as a parameter to a Card."
- [value options]
- (let [options (options/prepare-options options)
- t (u.time/coerce-to-timestamp value options)]
+ [time-config value options]
+ (let [options (options/prepare-options options)
+ time-options (merge options time-config)
+ t (u.time/coerce-to-timestamp value time-options)]
(if (not (u.time/valid? t))
;; Fall back to a basic string rendering if we couldn't parse it.
(str value)
@@ -29,7 +30,7 @@
;; A few units have special formats.
(fmt t)
;; Otherwise, render as a day or day range.
- (let [[start end] (u.time/to-range t options)]
+ (let [[start end] (u.time/to-range t time-options)]
(if (u.time/same-day? start end)
(formatters/big-endian-day start)
(str (formatters/big-endian-day start) "~" (formatters/big-endian-day end))))))))
@@ -56,21 +57,23 @@
(defn ^:export format-range-with-unit
"Returns a string with this datetime formatted as a range, rounded to the given `:unit`."
- [value options]
- (let [options (options/prepare-options options)
- t (u.time/coerce-to-timestamp value options)]
+ [time-config value options]
+ (let [options (options/prepare-options options)
+ time-options (merge options time-config)
+ t (u.time/coerce-to-timestamp value time-options)]
(if (u.time/valid? t)
- (format-range-with-unit-inner (u.time/to-range t options) options)
+ (format-range-with-unit-inner (u.time/to-range t time-options) options)
;; Best-effort fallback if we failed to parse - .toString the input.
(str value))))
;;; ---------------------------------------------- Format Single Date -----------------------------------------------
(defn ^:export format-datetime-with-unit
"Returns a string with this datetime formatted as a single value, rounded to the given `:unit`."
- [value options]
+ [time-config value options]
(let [{:keys [is-exclude no-range type unit]
:as options} (options/prepare-options options)
- t (u.time/coerce-to-timestamp value options)]
+ time-options (merge options time-config)
+ t (u.time/coerce-to-timestamp value time-options)]
(cond
is-exclude (case unit
:hour-of-day (formatters/hour-only t)
@@ -80,7 +83,7 @@
;; Weeks in tooltips and cells get formatted specially.
(and (= unit :week) (#{"tooltip" "cell"} type) (not no-range))
- (format-range-with-unit value options)
+ (format-range-with-unit time-config value options)
:else ((formatters/options->formatter options) t))))
diff --git a/src/metabase/util/time.cljc b/src/metabase/util/time.cljc
index 82610c6a01e..60c8100d95a 100644
--- a/src/metabase/util/time.cljc
+++ b/src/metabase/util/time.cljc
@@ -87,12 +87,11 @@
"Formats a temporal-value (iso date/time string, int for hour/minute) given the temporal-bucketing unit.
If unit is nil, formats the full date/time.
- If `locale` is provided, that locale will be used for localizing the formatter. In CLJ this should be a `Locale`. Not
- supported in CLJS since we have to rely on the browser's locale."
- ([temporal-value unit]
- (internal/format-unit temporal-value unit))
- ([temporal-value unit locale]
- (internal/format-unit temporal-value unit locale)))
+ `time-config` must include `:start-of-week`. `format-options` may include `:locale` to localize the formatter."
+ ([time-config temporal-value unit]
+ (format-unit time-config temporal-value unit {}))
+ ([time-config temporal-value unit format-options]
+ (internal/format-unit (common/require-time-config time-config) temporal-value unit format-options)))
(defn parse-unit
"Parses a string given the unit of time to parse by."
@@ -109,16 +108,21 @@
(defn format-relative-date-range
"Given a `n` `unit` time interval and the current date, return a string representing the date-time range.
+ `time-config` must contain `:start-of-week` as a weekday keyword.
+ When `n` is zero, return the current unit whether or not `:include-current` is true.
Provide an `offset-n` and `offset-unit` time interval to change the date used relative to the current date.
`options` is a map and supports `:include-current` to include the current given unit of time in the range."
- ([n unit]
- (format-relative-date-range n unit nil nil nil))
- ([n unit offset-n offset-unit]
- (format-relative-date-range n unit offset-n offset-unit nil))
- ([n unit offset-n offset-unit options]
- (internal/format-relative-date-range n unit offset-n offset-unit options))
- ([t n unit offset-n offset-unit options]
- (internal/format-relative-date-range (coerce-to-timestamp t) n unit offset-n offset-unit options)))
+ ([time-config n unit]
+ (format-relative-date-range time-config n unit nil nil nil))
+ ([time-config n unit offset-n offset-unit]
+ (format-relative-date-range time-config n unit offset-n offset-unit nil))
+ ([time-config n unit offset-n offset-unit options]
+ (internal/format-relative-date-range (common/require-time-config time-config) n unit offset-n offset-unit options))
+ ([time-config t n unit offset-n offset-unit options]
+ (let [time-config (common/require-time-config time-config)]
+ (internal/format-relative-date-range time-config
+ (coerce-to-timestamp t)
+ n unit offset-n offset-unit options))))
(defn yyyyMMddhhmmss->parts
"Generate parts vector for `yyyy-MM-ddThh:mm:ss` format `date-str`. Trailing parts, if not present in the string,
diff --git a/src/metabase/util/time/impl.clj b/src/metabase/util/time/impl.clj
index 66b97cad507..78d649dca89 100644
--- a/src/metabase/util/time/impl.clj
+++ b/src/metabase/util/time/impl.clj
@@ -61,16 +61,15 @@
(= (t/month d1) (t/month d2))))
;;; ---------------------------------------------- information -------------------------------------------------------
-(defn first-day-of-week
- "The first day of the week varies by locale, but Metabase has a setting that overrides it.
- In JVM, we can just read the setting directly."
- []
- ((requiring-resolve 'metabase.settings.core/get) :start-of-week))
-
(def default-options
"The default map of options."
{:locale (Locale/getDefault)})
+(defn- start-of-week [{:keys [start-of-week] :as time-config}]
+ (or start-of-week
+ (throw (ex-info "Week-based time operations require :start-of-week"
+ {:time-config time-config}))))
+
;;; ------------------------------------------------ to-range --------------------------------------------------------
(defn- minus-ms [value]
(t/minus value (t/millis 1)))
@@ -108,8 +107,8 @@
(t/truncate-to :days))]
[start (minus-ms (t/plus start (t/days n)))]))
-(defmethod common/to-range :week [value {:keys [n] :or {n 1}}]
- (let [first-day (first-day-of-week)
+(defmethod common/to-range :week [value {:keys [n] :or {n 1} :as options}]
+ (let [first-day (start-of-week options)
start (-> value
(t/truncate-to :days)
(t/adjust :previous-or-same-day-of-week first-day))]
@@ -124,7 +123,8 @@
(declare truncate add)
(defmethod common/to-range :quarter [value {:keys [n] :or {n 1}}]
- (let [value (truncate value :quarter)]
+ (let [value (-> (t/adjust value (u.date/adjuster :first-day-of-quarter))
+ (t/truncate-to :days))]
[value (minus-ms (add value :quarter n))]))
(defmethod common/to-range :year [value {:keys [n] :or {n 1}}]
@@ -186,11 +186,11 @@
(t/truncate-to :days)
(t/plus (t/days (dec value)))))
-(defmethod common/number->timestamp :day-of-week [value _]
- ;; Metabase uses 1 to mean the start of the week, based on the Metabase setting for the first day of the week.
+(defmethod common/number->timestamp :day-of-week [value options]
+ ;; Metabase numbers weekdays from 1, starting on the first day of the week in `options`.
;; Moment uses 0 as the first day of the week in its configured locale.
- ;; For Java, get the first day of the week from the setting, and offset by `(dec value)` for the current day.
- (number->timestamp value (first-day-of-week)))
+ ;; For Java, find that first day and add `(dec value)` days.
+ (number->timestamp value (start-of-week options)))
(defmethod common/number->timestamp :day-of-week-iso [value _]
(number->timestamp value :monday))
@@ -203,11 +203,11 @@
;; We force the initial date to be in a leap year (2016).
(t/plus magic-base-date (t/days (dec value))))
-(defmethod common/number->timestamp :week-of-year [value _]
+(defmethod common/number->timestamp :week-of-year [value options]
(-> (now)
(t/truncate-to :days)
(t/adjust :first-day-of-year)
- (t/adjust :previous-or-same-day-of-week (first-day-of-week))
+ (t/adjust :previous-or-same-day-of-week (start-of-week options))
(t/plus (t/weeks (dec value)))))
(defmethod common/number->timestamp :month-of-year [value _]
@@ -309,18 +309,20 @@
(long (/ (unit-diff :day before after) 7))
:month
- (let [diff-months (- (u.date/extract after :month-of-year)
- (u.date/extract before :month-of-year))
- diff-years (- (u.date/extract after :year)
- (u.date/extract before :year))]
+ (let [options {:start-of-week :sunday}
+ diff-months (- (u.date/extract options after :month-of-year)
+ (u.date/extract options before :month-of-year))
+ diff-years (- (u.date/extract options after :year)
+ (u.date/extract options before :year))]
(+ diff-months (* diff-years 12)))
:quarter
(long (/ (unit-diff :month before after) 3))
:year
- (- (u.date/extract after :year)
- (u.date/extract before :year)))))
+ (let [options {:start-of-week :sunday}]
+ (- (u.date/extract options after :year)
+ (u.date/extract options before :year))))))
(defn day-diff
"Returns the time elapsed between `before` and `after` in days (an integer)."
@@ -349,7 +351,7 @@
(defn ^:private format-extraction-unit
"Formats a date-time value given the temporal extraction unit.
If unit is not supported, returns nil."
- [t unit ^Locale locale]
+ [t unit {:keys [locale]}]
(when-let [^DateTimeFormatter formatter (some-> unit
unit-formats
t/formatter
@@ -359,8 +361,9 @@
(defn format-unit
"Formats a temporal-value (iso date/time string, int for extraction units) given the temporal-bucketing unit.
If unit is nil, formats the full date/time"
- ([input unit] (format-unit input unit nil))
- ([input unit locale]
+ ([time-config input unit]
+ (format-unit time-config input unit {}))
+ ([time-config input unit format-options]
(cond
(string? input)
(let [time? (common/matches-time? input)
@@ -372,7 +375,7 @@
date-time? (coerce-local-date-time input))]
(if t
(or
- (format-extraction-unit t unit locale)
+ (format-extraction-unit t unit format-options)
(cond
time? (t/format "h:mm a" t)
date? (t/format "MMM d, yyyy" t)
@@ -380,15 +383,19 @@
input))
(number? input)
- (if (= unit :hour-of-day)
- (str (cond (zero? input) "12" (<= input 12) input :else (- input 12)) " " (if (<= input 11) "AM" "PM"))
+ (case (keyword unit)
+ :hour-of-day (str (cond (zero? input) "12" (<= input 12) input :else (- input 12))
+ " "
+ (if (<= input 11) "AM" "PM"))
(or
- (format-extraction-unit (common/number->timestamp input {:unit unit}) unit locale)
+ (format-extraction-unit (common/number->timestamp input (assoc time-config :unit unit))
+ unit
+ format-options)
(str input)))
(instance? java.time.temporal.TemporalAccessor input)
(let [input ^java.time.temporal.TemporalAccessor input]
- (or (format-extraction-unit input unit locale)
+ (or (format-extraction-unit input unit format-options)
(cond
;; no hour, must be date
(not (.isSupported input (t/field :hour-of-day)))
@@ -418,15 +425,19 @@
"Formats a time difference between two temporal values.
Drops redundant information."
[temporal-value-1 temporal-value-2]
- (let [default-format #(str (format-unit temporal-value-1 nil)
+ ;; This is a placeholder, not the instance's real setting.
+ ;; Formatting a diff never resolves a week-based unit, but format-unit's schema still requires a full
+ ;; time-config map.
+ (let [time-config {:start-of-week :sunday}
+ default-format #(str (format-unit time-config temporal-value-1 nil)
" – "
- (format-unit temporal-value-2 nil))]
+ (format-unit time-config temporal-value-2 nil))]
(cond
(some (complement string?) [temporal-value-1 temporal-value-2])
(default-format)
(= temporal-value-1 temporal-value-2)
- (format-unit temporal-value-1 nil)
+ (format-unit time-config temporal-value-1 nil)
(and (common/matches-time? temporal-value-1)
(common/matches-time? temporal-value-2))
@@ -474,34 +485,38 @@
(defn format-relative-date-range
"Given a `n` `unit` time interval and the current date, return a string representing the date-time range.
+ When `n` is zero, return the current unit whether or not `:include-current` is true.
Provide an `offset-n` and `offset-unit` time interval to change the date used relative to the current date.
`options` is a map and supports `:include-current` to include the current given unit of time in the range."
- ([n unit offset-n offset-unit opts]
- (format-relative-date-range (now) n unit offset-n offset-unit opts))
- ([t n unit offset-n offset-unit {:keys [include-current]}]
+ ([time-config n unit offset-n offset-unit options]
+ (format-relative-date-range time-config (now) n unit offset-n offset-unit options))
+ ([time-config t n unit offset-n offset-unit {:keys [include-current] :as options}]
(let [offset-now (cond-> t
(neg? n) (apply-offset n unit)
(and (pos? n) (not include-current)) (apply-offset 1 unit)
(and offset-n offset-unit) (apply-offset offset-n offset-unit))
- pos-n (cond-> (abs n)
- include-current inc)
+ pos-n (max 1 (cond-> (abs n)
+ include-current inc))
date-ranges (map (if (#{:hour :minute} unit)
#(t/format "yyyy-MM-dd'T'HH:mm" (t/local-date-time %))
#(str (t/local-date %)))
(common/to-range offset-now
- {:unit unit
- :n pos-n
- :offset-n offset-n
- :offset-unit offset-unit}))]
+ (merge time-config
+ options
+ {:unit unit
+ :n pos-n
+ :offset-n offset-n
+ :offset-unit offset-unit})))]
(apply format-diff date-ranges))))
(defn truncate
"Clojure implementation of [[metabase.util.time/truncate]]; basically the same as [[u.date/truncate]] but also
handles ISO-8601 strings."
- [t unit]
- (if (string? t)
- (str (truncate (u.date/parse t) unit))
- (u.date/truncate t unit)))
+ [time-config t unit]
+ (let [unit (keyword unit)]
+ (if (string? t)
+ (str (truncate time-config (u.date/parse t) unit))
+ (u.date/truncate time-config t unit))))
(defn add
"Clojure implementation of [[metabase.util.time/add]]; basically the same as [[u.date/add]] but also handles
@@ -539,5 +554,5 @@
(defn extract
"Extract a field such as `:minute-of-hour` from a temporal value `t`."
- [t unit]
- (u.date/extract t unit))
+ [time-config t unit]
+ (u.date/extract time-config t unit))
diff --git a/src/metabase/util/time/impl.cljs b/src/metabase/util/time/impl.cljs
index 2d8e5cef1e4..1f00700488c 100644
--- a/src/metabase/util/time/impl.cljs
+++ b/src/metabase/util/time/impl.cljs
@@ -51,7 +51,6 @@
;; cljfmt reorders these namespaces to be out of order, then kondo complains about it.
;; so let's just live with the 1 unordered namespace require for now. :skull:
^{:clj-kondo/ignore [:unsorted-required-namespaces]}
- ["dayjs/plugin/weekday" :as weekday]
["dayjs/plugin/weekOfYear" :as weekOfYear]
[metabase.util.time.impl-common :as common]))
@@ -64,7 +63,6 @@
(dayjs/extend objectSupport)
(dayjs/extend quarterOfYear)
(dayjs/extend utc)
-(dayjs/extend weekday)
(dayjs/extend weekOfYear)
(defn- now [] (dayjs))
@@ -111,17 +109,29 @@
(.isSame d1 d2 "year"))
;;; ---------------------------------------------- information -------------------------------------------------------
-(defn first-day-of-week
- "The first day of the week varies by locale, but Metabase has a setting that overrides it.
- In CLJS, Day.js is already configured with that setting."
- []
- (nth [:sunday :monday :tuesday :wednesday :thursday :friday :saturday]
- (.firstDayOfWeek (dayjs/localeData))))
-
(def default-options
"The default map of options - empty in CLJS."
{})
+(def ^:private day-of-week->index
+ {:sunday 0
+ :monday 1
+ :tuesday 2
+ :wednesday 3
+ :thursday 4
+ :friday 5
+ :saturday 6})
+
+(defn- start-of-week-index [{:keys [start-of-week] :as time-config}]
+ (or (day-of-week->index start-of-week)
+ (throw (ex-info "Week-based time operations require :start-of-week"
+ {:time-config time-config}))))
+
+(defn- ^dayjs truncate-to-week [time-config ^dayjs value]
+ (let [days-since-start (mod (- (.day value) (start-of-week-index time-config)) 7)
+ ^dayjs shifted (.subtract value days-since-start "day")]
+ (.startOf shifted "day")))
+
;;; ------------------------------------------------ to-range --------------------------------------------------------
(defn- apply-offset
[value offset-n offset-unit]
@@ -130,14 +140,16 @@
offset-n
(name offset-unit)))
-(defmethod common/to-range :default [^dayjs value {:keys [n unit]}]
- (let [^dayjs adjusted (if (> n 1)
- (.add value (dec n) (name unit))
- value)]
- [(.startOf value (name unit))
- (.endOf adjusted (name unit))]))
-
-;; NB: Only the :default for to-range is needed in CLJS, since Day.js's startOf and endOf methods are doing the work.
+(defmethod common/to-range :default [^dayjs value {:keys [n unit] :or {n 1} :as options}]
+ (if (= (keyword unit) :week)
+ (let [^dayjs start (truncate-to-week options value)
+ ^dayjs end (.add start n "week")]
+ [start (.subtract end 1 "millisecond")])
+ (let [^dayjs adjusted (if (> n 1)
+ (.add value (dec n) (name unit))
+ value)]
+ [(.startOf value (name unit))
+ (.endOf adjusted (name unit))])))
;;; -------------------------------------------- string->timestamp ---------------------------------------------------
(defn- valid-date-string?
@@ -211,10 +223,10 @@
(defmethod common/number->timestamp :hour-of-day [value _]
(-> (now) (.hour value) (.startOf "hour")))
-(defmethod common/number->timestamp :day-of-week [value _]
+(defmethod common/number->timestamp :day-of-week [value options]
;; Metabase uses 1 to mean the start of the week, based on the Metabase setting for the first day of the week.
- ;; Day.js's weekday() uses 0 as the first day of the week in its configured locale.
- (-> (now) (.weekday (dec value)) (.startOf "day")))
+ (-> (truncate-to-week options (now))
+ (.add (dec value) "day")))
(defmethod common/number->timestamp :day-of-week-iso [value _]
(-> (now) (.isoWeekday value) (.startOf "day")))
@@ -290,7 +302,7 @@
"Constructs a platform date value (eg. Day.js, LocalDate) for the given year, month and day.
Day is 1-31. January = 1, or you can specify keywords like `:jan`, `:jun`."
- ([] (truncate (dayjs) :day))
+ ([] (truncate {:start-of-week :sunday} (dayjs) :day))
([year month day]
(dayjs #js {:year year
:date day
@@ -372,11 +384,10 @@
(defn ^:private format-extraction-unit
"Formats a date-time value given the temporal extraction unit.
If unit is not supported, returns nil."
- [^dayjs t unit locale]
- ;; Special case for day-of-year: use the dayOfYear() method instead of format
- ;; because DDD produces zero-padded output
- (if (= unit :day-of-year)
- (str (.dayOfYear t))
+ [^dayjs t unit {:keys [locale]}]
+ (case unit
+ ;; DDD produces zero-padded output, so use the plugin method instead.
+ :day-of-year (str (.dayOfYear t))
(when-some [format (get unit-formats unit)]
(if locale
(-> t
@@ -410,9 +421,9 @@
"Formats a temporal-value (iso date/time string, int for extraction units) given the temporal-bucketing unit.
If unit is nil, formats the full date/time.
Time input formatting is only defined with time units."
- ;; This third argument is needed for the JVM side; it can be ignored here.
- ([input unit] (format-unit input unit nil))
- ([input unit locale]
+ ([time-config input unit]
+ (format-unit time-config input unit {}))
+ ([time-config input unit format-options]
(cond
(string? input)
(let [time? (common/matches-time? input)
@@ -425,7 +436,7 @@
(or date? date-time?) (coerce-local-date-time input))]
(if (and t (.isValid t))
(or
- (format-extraction-unit t unit locale)
+ (format-extraction-unit t unit format-options)
;; no locale for default formats
(cond
time? (.format t "h:mm A")
@@ -434,14 +445,18 @@
input))
(number? input)
- (if (= unit :hour-of-day)
- (str (cond (zero? input) "12" (<= input 12) input :else (- input 12)) " " (if (<= input 11) "AM" "PM"))
+ (case (keyword unit)
+ :hour-of-day (str (cond (zero? input) "12" (<= input 12) input :else (- input 12))
+ " "
+ (if (<= input 11) "AM" "PM"))
(or
- (format-extraction-unit (common/number->timestamp input {:unit unit}) unit locale)
+ (format-extraction-unit (common/number->timestamp input (assoc time-config :unit unit))
+ unit
+ format-options)
(str input)))
(dayjs/isDayjs input)
- (or (format-extraction-unit input unit locale)
+ (or (format-extraction-unit input unit format-options)
;; no locale for default formats
(cond
;; no hour, minute, or seconds, must be date
@@ -509,15 +524,16 @@
"Formats a time difference between two temporal values.
Drops redundant information."
[temporal-value-1 temporal-value-2]
- (let [default-format #(str (format-unit temporal-value-1 nil)
+ (let [time-config {:start-of-week :sunday}
+ default-format #(str (format-unit time-config temporal-value-1 nil)
" – "
- (format-unit temporal-value-2 nil))]
+ (format-unit time-config temporal-value-2 nil))]
(cond
(some (complement string?) [temporal-value-1 temporal-value-2])
(default-format)
(= temporal-value-1 temporal-value-2)
- (format-unit temporal-value-1 nil)
+ (format-unit time-config temporal-value-1 nil)
(and (common/matches-time? temporal-value-1)
(common/matches-time? temporal-value-2))
@@ -563,23 +579,26 @@
(defn format-relative-date-range
"Given a `n` `unit` time interval and the current date, return a string representing the date-time range.
+ When `n` is zero, return the current unit whether or not `:include-current` is true.
Provide an `offset-n` and `offset-unit` time interval to change the date used relative to the current date.
`options` is a map and supports `:include-current` to include the current given unit of time in the range."
- ([n unit offset-n offset-unit opts]
- (format-relative-date-range (now) n unit offset-n offset-unit opts))
- ([t n unit offset-n offset-unit {:keys [include-current]}]
+ ([time-config n unit offset-n offset-unit options]
+ (format-relative-date-range time-config (now) n unit offset-n offset-unit options))
+ ([time-config t n unit offset-n offset-unit {:keys [include-current] :as options}]
(let [offset-now (cond-> t
(neg? n) (apply-offset n unit)
(and (pos? n) (not include-current)) (apply-offset 1 unit)
(and offset-n offset-unit) (apply-offset offset-n offset-unit))
- pos-n (cond-> (abs n)
- include-current inc)
+ pos-n (max 1 (cond-> (abs n)
+ include-current inc))
date-ranges (map #(.format % (if (#{:hour :minute} unit) "YYYY-MM-DDTHH:mm" "YYYY-MM-DD"))
(common/to-range offset-now
- {:unit unit
- :n pos-n
- :offset-n offset-n
- :offset-unit offset-unit}))]
+ (merge time-config
+ options
+ {:unit unit
+ :n pos-n
+ :offset-n offset-n
+ :offset-unit offset-unit})))]
(apply format-diff date-ranges))))
(def ^:private temporal-formats
@@ -684,9 +703,13 @@
(defn truncate
"ClojureScript implementation of [[metabase.util.time/truncate]]; supports both Day.js instances and ISO-8601
strings."
- [t unit]
- (with-string-preservation t (fn [^dayjs parsed]
- (.startOf parsed (name unit)))))
+ [time-config t unit]
+ (let [time-config (common/require-time-config time-config)
+ unit (keyword unit)]
+ (with-string-preservation t (fn [^dayjs parsed]
+ (if (= unit :week)
+ (truncate-to-week time-config parsed)
+ (.startOf parsed (name unit)))))))
(defn add
"ClojureScript implementation of [[metabase.util.time/add]]; supports both Day.js instances and ISO-8601 strings."
@@ -725,19 +748,20 @@
(defn extract
"Extract a field such as `:minute-of-hour` from a temporal value `t`."
- [^dayjs t unit]
- (case unit
- :second-of-minute (.second t)
- :minute-of-hour (.minute t)
- :hour-of-day (.hour t)
- :day-of-week (inc (.weekday t)) ;; `weekday` is 0-6, where 0 corresponds to the first day of week
- :day-of-week-iso (.isoWeekday t)
- :day-of-month (.date t)
- :day-of-year (.dayOfYear t)
- :week-of-year (.week t)
- :month-of-year (inc (.month t)) ;; `month` is 0-11
- :quarter-of-year (.quarter t)
- :year (.year t)))
+ [time-config ^dayjs t unit]
+ (let [time-config (common/require-time-config time-config)]
+ (case unit
+ :second-of-minute (.second t)
+ :minute-of-hour (.minute t)
+ :hour-of-day (.hour t)
+ :day-of-week (inc (mod (- (.day t) (start-of-week-index time-config)) 7))
+ :day-of-week-iso (.isoWeekday t)
+ :day-of-month (.date t)
+ :day-of-year (.dayOfYear t)
+ :week-of-year (.week t)
+ :month-of-year (inc (.month t)) ;; `month` is 0-11
+ :quarter-of-year (.quarter t)
+ :year (.year t))))
(defn dayjs-utc->local-date
"Convert a dayjs UTC value to a JavaScript Date in local time, preserving the time values.
diff --git a/src/metabase/util/time/impl_common.cljc b/src/metabase/util/time/impl_common.cljc
index f4d6e368c64..7e3c72471d5 100644
--- a/src/metabase/util/time/impl_common.cljc
+++ b/src/metabase/util/time/impl_common.cljc
@@ -4,6 +4,14 @@
(defn- by-unit [_ {:keys [unit]}] (keyword unit))
+(defn require-time-config
+ "Return `time-config`, or throw if it has no `:start-of-week`."
+ [{:keys [start-of-week] :as time-config}]
+ (when-not start-of-week
+ (throw (ex-info "Date operations require :start-of-week"
+ {:time-config time-config})))
+ time-config)
+
(defmulti to-range
"Given a datetime and a unit (eg. \"hour\"), returns an *inclusive* datetime range as a pair of datetimes.
For a unit of an hour, and a datetime for 13:49:28, that means [13:00:00 13:59:59.999], ie. 1 ms before the end."
diff --git a/src/metabase/xrays/automagic_dashboards/names.clj b/src/metabase/xrays/automagic_dashboards/names.clj
index 2e5fa9f31cc..d1733afb374 100644
--- a/src/metabase/xrays/automagic_dashboards/names.clj
+++ b/src/metabase/xrays/automagic_dashboards/names.clj
@@ -155,30 +155,31 @@
(defn- humanize-datetime
"Convert a time data type into a human friendly string."
[t unit]
- (let [dt (if (integer? t)
- (u.time/coerce-to-timestamp t {:unit unit})
- (u.date/parse t))]
+ (let [options (lib-be/time-config)
+ dt (if (integer? t)
+ (u.time/coerce-to-timestamp t (assoc options :unit unit))
+ (u.date/parse t))]
(case unit
:second (tru "at {0}" (t/format "h:mm:ss a, MMMM d, YYYY" dt))
:minute (tru "at {0}" (t/format "h:mm a, MMMM d, YYYY" dt))
:hour (tru "at {0}" (t/format "h a, MMMM d, YYYY" dt))
:day (tru "on {0}" (t/format "MMMM d, YYYY" dt))
:week (tru "in {0} week - {1}"
- (pluralize (u.date/extract dt :week-of-year))
- (str (u.date/extract dt :year)))
+ (pluralize (u.date/extract options dt :week-of-year))
+ (str (u.date/extract options dt :year)))
:month (tru "in {0}" (t/format "MMMM YYYY" dt))
:quarter (tru "in Q{0} - {1}"
- (u.date/extract dt :quarter-of-year)
- (str (u.date/extract dt :year)))
+ (u.date/extract options dt :quarter-of-year)
+ (str (u.date/extract options dt :year)))
:year (t/format "YYYY" dt)
:day-of-week (t/format "EEEE" dt)
:hour-of-day (tru "at {0}" (t/format "h a" dt))
:month-of-year (t/format "MMMM" dt)
- :quarter-of-year (tru "Q{0}" (u.date/extract dt :quarter-of-year))
+ :quarter-of-year (tru "Q{0}" (u.date/extract options dt :quarter-of-year))
(:minute-of-hour
:day-of-month
:day-of-year
- :week-of-year) (u.date/extract dt unit))))
+ :week-of-year) (u.date/extract options dt unit))))
(mu/defmethod humanize-filter-value :=
[root :- ::ads/root
diff --git a/test/metabase/agent_lib/representations/repair_test.clj b/test/metabase/agent_lib/representations/repair_test.clj
index eec516be3f8..d7773381c76 100644
--- a/test/metabase/agent_lib/representations/repair_test.clj
+++ b/test/metabase/agent_lib/representations/repair_test.clj
@@ -7,6 +7,7 @@
[clojure.test.check.properties :as prop]
[metabase.agent-lib.representations :as repr]
[metabase.agent-lib.representations.repair :as repair]
+ [metabase.lib-be.core :as lib-be]
[metabase.lib.test-util :as lib.tu]
[metabase.util.date-2 :as u.date]))
@@ -727,7 +728,7 @@
namespaces mutate it, and the tests below are `^:parallel`. Under the default Sunday `2025-01-01`
gives `2024-12-29`."
[literal]
- (str (u.date/truncate (u.date/parse literal) :week)))
+ (str (u.date/truncate (lib-be/time-config) (u.date/parse literal) :week)))
(defn- repair-in-stage
"Run `repair` on a query carrying `stage-kvs`, returning the repaired first stage. The hoist pass
diff --git a/test/metabase/util/markdown_test.clj b/test/metabase/channel/render/markdown_test.clj
similarity index 99%
rename from test/metabase/util/markdown_test.clj
rename to test/metabase/channel/render/markdown_test.clj
index ba8a1e94435..5573a2ce393 100644
--- a/test/metabase/util/markdown_test.clj
+++ b/test/metabase/channel/render/markdown_test.clj
@@ -1,9 +1,9 @@
-(ns metabase.util.markdown-test
+(ns metabase.channel.render.markdown-test
(:require
[clojure.string :as str]
[clojure.test :refer :all]
- [metabase.util :as u]
- [metabase.util.markdown :as markdown]))
+ [metabase.channel.render.markdown :as markdown]
+ [metabase.util :as u]))
(defn- slack
([markdown]
diff --git a/test/metabase/lib/fe_util_test.cljc b/test/metabase/lib/fe_util_test.cljc
index 5df7a741ad0..13304e47bac 100644
--- a/test/metabase/lib/fe_util_test.cljc
+++ b/test/metabase/lib/fe_util_test.cljc
@@ -1193,7 +1193,8 @@
"2024-05-13T16:35"]]
(testing "Expandable temporal units"
(are [unit start end] (=? [:between map? [:field {:temporal-unit unit} int?] start end]
- (#'lib.fe-util/expand-temporal-expression (update-temporal-unit expr unit)))
+ (#'lib.fe-util/expand-temporal-expression {:start-of-week :sunday}
+ (update-temporal-unit expr unit)))
:hour "2024-05-13T16:00:00" "2024-05-13T16:59:59"
:week "2024-05-12" "2024-05-18"
:month "2024-05-01" "2024-05-31"
@@ -1216,7 +1217,7 @@
(field-with-unit unit) value])]
(are [unit value start end]
(=? [:between map? [:field {:temporal-unit unit} int?] start end]
- (#'lib.fe-util/expand-temporal-expression (expr-with unit value)))
+ (#'lib.fe-util/expand-temporal-expression {:start-of-week :sunday} (expr-with unit value)))
:day "2024-05-13T00:00:00Z" "2024-05-13" "2024-05-13"
:day "2024-05-13T00:00:00+08:00" "2024-05-13" "2024-05-13"
:day "2024-05-13T00:00:00-08:00" "2024-05-13" "2024-05-13"
diff --git a/test/metabase/lib/filter/desugar/jvm_test.clj b/test/metabase/lib/filter/desugar/jvm_test.clj
index f9b93951e68..9da55b86614 100644
--- a/test/metabase/lib/filter/desugar/jvm_test.clj
+++ b/test/metabase/lib/filter/desugar/jvm_test.clj
@@ -107,19 +107,27 @@
(deftest ^:parallel desugar-host-and-domain-test-1
(testing "`host` should desugar to a `regex-match-first` clause with the host regex"
(is (=? [:regex-match-first {} [:field {} 1] (str @#'lib.filter.desugar.jvm/host-regex)]
- (#'lib.filter.desugar/desugar-expression [:host (opts) [:field (opts) 1]])))))
+ (#'lib.filter.desugar/desugar-expression
+ {:start-of-week :sunday}
+ [:host (opts) [:field (opts) 1]])))))
(deftest ^:parallel desugar-host-and-domain-test-2
(testing "`domain` should desugar to a `regex-match-first` clause with the domain regex"
(is (=? [:regex-match-first {} [:field {} 1] (str @#'lib.filter.desugar.jvm/domain-regex)]
- (#'lib.filter.desugar/desugar-expression [:domain (opts) [:field (opts) 1]])))))
+ (#'lib.filter.desugar/desugar-expression
+ {:start-of-week :sunday}
+ [:domain (opts) [:field (opts) 1]])))))
(deftest ^:parallel desugar-host-and-domain-test-3
(testing "`subdomain` should desugar to a `regex-match-first` clause with the subdomain regex"
(is (=? [:regex-match-first {} [:field {} 1] (str @#'lib.filter.desugar.jvm/subdomain-regex)]
- (#'lib.filter.desugar/desugar-expression [:subdomain (opts) [:field (opts) 1]])))))
+ (#'lib.filter.desugar/desugar-expression
+ {:start-of-week :sunday}
+ [:subdomain (opts) [:field (opts) 1]])))))
(deftest ^:parallel desugar-host-and-domain-test-4
(testing "`path` should desugar to a `regex-match-first` clause with the path regex"
(is (=? [:regex-match-first {} [:field {} 1] (str @#'lib.filter.desugar.jvm/path-regex)]
- (#'lib.filter.desugar/desugar-expression [:path (opts) [:field (opts) 1]])))))
+ (#'lib.filter.desugar/desugar-expression
+ {:start-of-week :sunday}
+ [:path (opts) [:field (opts) 1]])))))
diff --git a/test/metabase/lib/filter/desugar_test.cljc b/test/metabase/lib/filter/desugar_test.cljc
index 3aecf89b1ec..cb611da1f11 100644
--- a/test/metabase/lib/filter/desugar_test.cljc
+++ b/test/metabase/lib/filter/desugar_test.cljc
@@ -12,13 +12,19 @@
(defn- opts [& {:as kvs}]
(merge {:lib/uuid (str (random-uuid))} kvs))
+(defn- desugar-filter-clause [clause]
+ (lib.filter.desugar/desugar-filter-clause {:start-of-week :sunday} clause))
+
+(defn- desugar-expression [expression]
+ (#'lib.filter.desugar/desugar-expression {:start-of-week :sunday} expression))
+
(deftest ^:parallel desugar-time-interval-test-1
(testing "`time-interval` with value > 1 or < -1 should generate a `between` clause"
(is (=? [:between {}
[:expression {:temporal-unit :month} "CC"]
[:relative-datetime {} 1 :month]
[:relative-datetime {} 2 :month]]
- (lib.filter.desugar/desugar-filter-clause [:time-interval (opts) [:expression (opts) "CC"] 2 :month])))))
+ (desugar-filter-clause [:time-interval (opts) [:expression (opts) "CC"] 2 :month])))))
(deftest ^:parallel desugar-time-interval-test-2
(testing "test the `include-current` option -- interval should start or end at `0` instead of `1`"
@@ -26,7 +32,7 @@
[:expression {:temporal-unit :month} "CC"]
[:relative-datetime {} 0 :month]
[:relative-datetime {} 2 :month]]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:time-interval (opts :include-current true) [:expression (opts) "CC"] 2 :month])))))
(deftest ^:parallel desugar-time-interval-test-3
@@ -34,7 +40,7 @@
(is (=? [:= {}
[:expression {:temporal-unit :month} "CC"]
[:relative-datetime {} 1 :month]]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:time-interval (opts) [:expression (opts) "CC"] 1 :month])))))
(deftest ^:parallel desugar-time-interval-test-4
@@ -42,7 +48,7 @@
(is (=? [:= {}
[:expression {:temporal-unit :week} "CC"]
[:relative-datetime {} -1 :week]]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:time-interval (opts) [:expression (opts) "CC"] -1 :week])))))
(deftest ^:parallel desugar-time-interval-test-5
@@ -52,7 +58,7 @@
[:expression {:temporal-unit :month} "CC"]
[:relative-datetime {} 0 :month]
[:relative-datetime {} 1 :month]]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:time-interval (opts :include-current true)
[:expression (opts) "CC"]
1 :month]))))))
@@ -64,7 +70,7 @@
[:expression {:temporal-unit :day} "CC"]
[:relative-datetime {} -1 :day]
[:relative-datetime {} 0 :day]]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:time-interval (opts :include-current true)
[:expression (opts) "CC"]
-1 :day]))))))
@@ -74,7 +80,7 @@
(is (=? [:= {}
[:expression {:temporal-unit :week} "CC"]
[:relative-datetime {} 0 :week]]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:time-interval (opts)
[:expression (opts) "CC"]
:current :week])))))
@@ -97,7 +103,7 @@
[:+ {}
[:relative-datetime {} 0 bucket]
[:interval {} offset-value offset-bucket]]]]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:relative-time-interval (opts) [:expression (opts) "cc"] value bucket offset-value offset-bucket]))))
(testing "field reference is transformed correctly"
(is (=? [:and {}
@@ -111,7 +117,7 @@
[:+ {}
[:relative-datetime {} 0 bucket]
[:interval {} offset-value offset-bucket]]]]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:relative-time-interval (opts)
[:field (opts :temporal-unit :default) 100]
value
@@ -129,7 +135,7 @@
(is (=? [:and {}
[:>= {} [:expression {} "cc"] [:+ {} [:relative-datetime {} 1 bucket] [:interval {} offset-value offset-bucket]]]
[:< {} [:expression {} "cc"] [:+ {} [:relative-datetime {} (inc value) bucket] [:interval {} offset-value offset-bucket]]]]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:relative-time-interval (opts)
[:expression (opts) "cc"]
value bucket offset-value offset-bucket]))))
@@ -137,7 +143,7 @@
(is (=? [:and {}
[:>= {} [:field {:temporal-unit :default} 100] [:+ {} [:relative-datetime {} 1 bucket] [:interval {} offset-value offset-bucket]]]
[:< {} [:field {:temporal-unit :default} 100] [:+ {} [:relative-datetime {} (inc value) bucket] [:interval {} offset-value offset-bucket]]]]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:relative-time-interval (opts)
[:field (opts :temporal-unit :default) 100]
value bucket offset-value offset-bucket])))))))
@@ -168,20 +174,20 @@
(is (=? [:and {}
[:>= {} [:expression {} "cc"] expected-lower]
[:< {} [:expression {} "cc"] expected-upper]]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:during (opts) [:expression (opts) "cc"] value unit]))))
(testing (str "field reference is transformed correctly for unit " unit)
(is (=? [:and {}
[:>= {} [:field {:temporal-unit :default} 100] expected-lower]
[:< {} [:field {:temporal-unit :default} 100] expected-upper]]
- (lib.filter.desugar/desugar-filter-clause [:during (opts) [:field (opts) 100] value unit]))))))))
+ (desugar-filter-clause [:during (opts) [:field (opts) 100] value unit]))))))))
(deftest ^:parallel desugar-if-test-1
(testing "Desugaring if produces expected [:case ..] expression"
(is (=? [:case {}
[[[:< {} [:field {} 1] 1] 2]
[[:< {} [:field {} 3] 4] 5]]]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:if (opts)
[[[:< (opts) [:field (opts) 1] 1] 2]
[[:< (opts) [:field (opts) 3] 4] 5]]])))))
@@ -190,7 +196,7 @@
(testing "Desugaring if produces expected [:case ..] expression"
(is (=? [:case {:default 3}
[[[:< {} [:field {} 1] 1] 2]]]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:if (opts :default 3)
[[[:< (opts) [:field (opts) 1] 1] 2]]])))))
@@ -217,7 +223,7 @@
[:field {} 6]
6]
7]]]]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:if (opts)
[[[:if (opts)
[[[:< (opts) [:field (opts) 1] 1]
@@ -241,7 +247,7 @@
[:field {:lib/uuid "00000000-0000-0000-0000-000000000004"} 255] 2]
"Second"]]
"Other"]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:if {:lib/uuid "00000000-0000-0000-0000-000000000000", :lib/expression-name "If"}
[[[:= {:lib/uuid "00000000-0000-0000-0000-000000000001"}
[:field {:lib/uuid "00000000-0000-0000-0000-000000000002"} 255] 1]
@@ -254,7 +260,7 @@
(deftest ^:parallel desugar-in-test
(testing "Desugaring in and not-in produces expected [:= ..] and [:!= ..] expressions"
(are [clause expected] (=? expected
- (lib.filter.desugar/desugar-filter-clause clause))
+ (desugar-filter-clause clause))
[:in (opts) [:field (opts) 1] 2]
[:= {} [:field {} 1] 2]
@@ -293,7 +299,7 @@
(is (=? [:= {}
[:field {:temporal-unit :minute} 1]
[:relative-datetime {} 0 :minute]]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:= (opts)
[:field (opts :temporal-unit :minute) 1]
[:relative-datetime (opts) :current]])))))
@@ -303,7 +309,7 @@
(is (=? [:= {}
[:field {} 1]
[:relative-datetime {} 0 :default]]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:= (opts)
[:field (opts) 1]
[:relative-datetime (opts) :current]])))))
@@ -313,7 +319,7 @@
(is (=? [:= {}
[:field {:temporal-unit :week, :binning {:strategy :default}} 1]
[:relative-datetime {} 0 :week]]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:= (opts)
[:field (opts :temporal-unit :week, :binning {:strategy :default}) 1]
[:relative-datetime (opts) :current]])))))
@@ -335,7 +341,7 @@
[:field {:temporal-unit unit} 1]
(expected x unit)
(expected y unit)]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:between
(opts)
[:field (opts :temporal-unit unit) 1]
@@ -350,7 +356,7 @@
[:= {} [:field {} 1] 3]
[:= {} [:field {} 1] 4]
[:= {} [:field {} 1] 5]]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:= (opts)
[:field (opts) 1] 2 3 4 5]))))))
@@ -362,7 +368,7 @@
[:!= {} [:field {} 1] 3]
[:!= {} [:field {} 1] 4]
[:!= {} [:field {} 1] 5]]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:!= (opts) [:field (opts) 1] 2 3 4 5]))))))
(deftest ^:parallel desugar-other-filter-clauses-test-3
@@ -370,25 +376,25 @@
(is (=? [:and {}
[:between {} [:field {} 1] -10.0 10.0]
[:between {} [:field {} 2] -20.0 20.0]]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:inside (opts) [:field (opts) 1] [:field (opts) 2] 10.0 -20.0 -10.0 20.0])))))
(deftest ^:parallel desugar-other-filter-clauses-test-4
(testing "desugaring :is-null"
(is (=? [:= {} [:field {} 1] nil]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:is-null (opts) [:field (opts) 1]])))))
(deftest ^:parallel desugar-other-filter-clauses-test-5
(testing "desugaring :not-null"
(is (=? [:!= {} [:field {} 1] nil]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:not-null (opts) [:field (opts) 1]])))))
(deftest ^:parallel desugar-other-filter-clauses-test-6
(testing "desugaring :is-empty of nil base-type"
(is (=? [:= {} [:field {} 1] nil]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:is-empty (opts) [:field (opts) 1]])))))
(deftest ^:parallel desugar-other-filter-clauses-test-7
@@ -396,7 +402,7 @@
(is (=? [:or {}
[:= {} [:field {:base-type :type/Text} 1] nil]
[:= {} [:field {:base-type :type/Text} 1] ""]]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:is-empty (opts) [:field (opts :base-type :type/Text) 1]])))))
(deftest ^:parallel desugar-other-filter-clauses-test-8
@@ -408,7 +414,7 @@
[:= {}
[:regex-match-first {} "foo" "bar"]
""]]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:is-empty (opts) [:regex-match-first (opts) "foo" "bar"]])))))
(deftest ^:parallel desugar-other-filter-clauses-test-9
@@ -416,7 +422,7 @@
(is (=? [:= {}
[:field {:base-type :type/DateTime} 1]
nil]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:is-empty (opts) [:field (opts :base-type :type/DateTime) 1]])))))
(deftest ^:parallel desugar-other-filter-clauses-test-10
@@ -424,7 +430,7 @@
(is (=? [:= {}
[:field {:base-type :type/PostgresEnum} 1]
nil]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:is-empty (opts) [:field (opts :base-type :type/PostgresEnum) 1]])))))
(deftest ^:parallel desugar-other-filter-clauses-test-11
@@ -432,7 +438,7 @@
(is (=? [:!= {}
[:field {} 1]
nil]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:not-empty (opts) [:field (opts) 1]])))))
(deftest ^:parallel desugar-other-filter-clauses-test-12
@@ -440,7 +446,7 @@
(is (=? [:and {}
[:!= {} [:field {:base-type :type/Text} 1] nil]
[:!= {} [:field {:base-type :type/Text} 1] ""]]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:not-empty (opts) [:field (opts :base-type :type/Text) 1]])))))
(deftest ^:parallel desugar-other-filter-clauses-test-13
@@ -448,7 +454,7 @@
(is (=? [:and {}
[:!= {} [:regex-match-first {} "foo" "bar"] nil]
[:!= {} [:regex-match-first {} "foo" "bar"] ""]]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:not-empty (opts) [:regex-match-first (opts) "foo" "bar"]])))))
(deftest ^:parallel desugar-other-filter-clauses-test-14
@@ -456,7 +462,7 @@
(is (=? [:!= {}
[:field {:base-type :type/DateTime} 1]
nil]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:not-empty (opts) [:field (opts :base-type :type/DateTime) 1]])))))
(deftest ^:parallel desugar-other-filter-clauses-test-15
@@ -464,7 +470,7 @@
(is (=? [:!= {}
[:field {:base-type :type/PostgresEnum} 1]
nil]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:not-empty (opts) [:field (opts :base-type :type/PostgresEnum) 1]])))))
(deftest ^:parallel desugar-does-not-contain-test-1
@@ -472,7 +478,7 @@
(testing "without options"
(is (=? [:not {}
[:contains {} [:field {} 1] "ABC"]]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:does-not-contain (opts) [:field (opts) 1] "ABC"]))))))
(deftest ^:parallel desugar-does-not-contain-test-2
@@ -480,7 +486,7 @@
(testing "*with* options"
(is (=? [:not {}
[:contains {:case-sensitive false} [:field {} 1] "ABC"]]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:does-not-contain (opts :case-sensitive false)
[:field (opts) 1]
"ABC"]))))))
@@ -494,7 +500,7 @@
[:contains {} [:field {} 1] "ABC"]]
[:not {}
[:contains {} [:field {} 1] "XYZ"]]]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:does-not-contain (opts) [:field (opts) 1] "ABC" "XYZ"])))))))
(deftest ^:parallel desugar-does-not-contain-test-4
@@ -505,7 +511,7 @@
[:not {} [:contains {} [:field {} 1] "ABC"]]
[:not {} [:contains {} [:field {} 1] "XYZ"]]
[:not {} [:contains {} [:field {} 1] "LMN"]]]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:does-not-contain (opts) [:field (opts) 1] "ABC" "XYZ" "LMN"])))))))
(deftest ^:parallel desugar-does-not-contain-test-5
@@ -515,7 +521,7 @@
(is (=? [:and {}
[:not {} [:contains {:case-sensitive false} [:field {} 1] "ABC"]]
[:not {} [:contains {:case-sensitive false} [:field {} 1] "XYZ"]]]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:does-not-contain (opts :case-sensitive false) [:field (opts) 1] "ABC" "XYZ"])))))))
(deftest ^:parallel desugar-does-not-contain-test-6
@@ -526,7 +532,7 @@
[:not {:case-sensitive false} [:contains {} [:field {} 1] "ABC"]]
[:not {:case-sensitive false} [:contains {} [:field {} 1] "XYZ"]]
[:not {:case-sensitive false} [:contains {} [:field {} 1] "LMN"]]]
- (lib.filter.desugar/desugar-filter-clause
+ (desugar-filter-clause
[:does-not-contain (opts :case-sensitive false) [:field (opts) 1] "ABC" "XYZ" "LMN"])))))))
(deftest ^:parallel desugar-temporal-extract-test
@@ -544,7 +550,7 @@
(deftest ^:parallel desugar-divide-with-extra-args-test-1
(testing '#'lib.filter.desugar/desugar-expression
- (are [expression expected] (=? expected (#'lib.filter.desugar/desugar-expression expression))
+ (are [expression expected] (=? expected (desugar-expression expression))
[:/ (opts) 1 2]
[:/ {} 1 2]
@@ -555,8 +561,8 @@
[:/ {} [:/ {} [:/ {} 1 2] 3] 4])))
(deftest ^:parallel desugar-divide-with-extra-args-test-2
- (testing 'lib.filter.desugar/desugar-filter-clause
- (are [expression expected] (=? expected (lib.filter.desugar/desugar-filter-clause expression))
+ (testing 'desugar-filter-clause
+ (are [expression expected] (=? expected (desugar-filter-clause expression))
[:= (opts) 1 [:/ (opts) 1 2]]
[:= {} 1 [:/ {} 1 2]]
@@ -589,7 +595,7 @@
[[:= {} [:field {} 1] 10] "Oct"]
[[:= {} [:field {} 1] 11] "Nov"]
[[:= {} [:field {} 1] 12] "Dec"]]]
- (#'lib.filter.desugar/desugar-expression [:month-name (opts) [:field (opts) 1]])))))
+ (desugar-expression [:month-name (opts) [:field (opts) 1]])))))
(deftest ^:parallel desugar-month-quarter-day-name-test-2
(testing "`quarter-name` should desugar to a `:case` clause with values for each quarter"
@@ -598,7 +604,7 @@
[[:= {} [:field {} 1] 2] "Q2"]
[[:= {} [:field {} 1] 3] "Q3"]
[[:= {} [:field {} 1] 4] "Q4"]]]
- (#'lib.filter.desugar/desugar-expression [:quarter-name (opts) [:field (opts) 1]])))))
+ (desugar-expression [:quarter-name (opts) [:field (opts) 1]])))))
(deftest ^:parallel desugar-month-quarter-day-name-test-3
(testing "`day-name` should desugar to a `:case` clause with values for each weekday"
@@ -610,7 +616,7 @@
[[:= {} [:field {} 1] 5] "Thursday"]
[[:= {} [:field {} 1] 6] "Friday"]
[[:= {} [:field {} 1] 7] "Saturday"]]]
- (#'lib.filter.desugar/desugar-expression [:day-name (opts) [:field (opts) 1]])))))
+ (desugar-expression [:day-name (opts) [:field (opts) 1]])))))
#?(:clj
(deftest ^:synchronized desugar-month-quarter-day-name-i18n-test
(metabase.test.util.i18n/with-user-locale "es"
@@ -631,7 +637,7 @@
[[:= {} [:field {} 1] 10] #(#{"oct" "oct."} %)]
[[:= {} [:field {} 1] 11] #(#{"nov" "nov."} %)]
[[:= {} [:field {} 1] 12] #(#{"dic" "dic."} %)]]]
- (#'lib.filter.desugar/desugar-expression [:month-name (opts) [:field (opts) 1]])))))))
+ (desugar-expression [:month-name (opts) [:field (opts) 1]])))))))
#?(:clj
(deftest ^:synchronized desugar-month-quarter-day-name-i18n-test-2
@@ -642,7 +648,7 @@
[[:= {} [:field {} 1] 2] "Q2"]
[[:= {} [:field {} 1] 3] "Q3"]
[[:= {} [:field {} 1] 4] "Q4"]]]
- (#'lib.filter.desugar/desugar-expression [:quarter-name (opts) [:field (opts) 1]])))))))
+ (desugar-expression [:quarter-name (opts) [:field (opts) 1]])))))))
#?(:clj
(deftest ^:synchronized desugar-month-quarter-day-name-i18n-test-3
@@ -656,4 +662,4 @@
[[:= {} [:field {} 1] 5] "jueves"]
[[:= {} [:field {} 1] 6] "viernes"]
[[:= {} [:field {} 1] 7] "sábado"]]]
- (#'lib.filter.desugar/desugar-expression [:day-name (opts) [:field (opts) 1]])))))))
+ (desugar-expression [:day-name (opts) [:field (opts) 1]])))))))
diff --git a/test/metabase/lib/filter/negate_test.cljc b/test/metabase/lib/filter/negate_test.cljc
index 050b5cf100d..d38b6fd0db7 100644
--- a/test/metabase/lib/filter/negate_test.cljc
+++ b/test/metabase/lib/filter/negate_test.cljc
@@ -8,7 +8,7 @@
#?(:cljs (comment metabase.test-runner.assert-exprs.approximately-equal/keep-me))
(defn- negate-boolean-expression [expr]
- (lib.filter.negate/negate-boolean-expression (lib/normalize expr)))
+ (lib.filter.negate/negate-boolean-expression {:start-of-week :sunday} (lib/normalize expr)))
(deftest ^:parallel negate-simple-filter-clause-test-1
(testing :=
diff --git a/test/metabase/lib/js_test.cljs b/test/metabase/lib/js_test.cljs
index ac97cfd859e..d8f07b3c516 100644
--- a/test/metabase/lib/js_test.cljs
+++ b/test/metabase/lib/js_test.cljs
@@ -1,5 +1,6 @@
(ns metabase.lib.js-test
(:require
+ ["dayjs" :as dayjs]
[clojure.test :refer [are deftest is testing]]
[goog.object :as gobject]
[medley.core :as m]
@@ -14,10 +15,21 @@
[metabase.lib.test-util :as lib.tu]
[metabase.test-runner.assert-exprs.approximately-equal]
[metabase.test.util.js :as test.js]
- [metabase.util.malli.registry :as mr]))
+ [metabase.util.malli.registry :as mr]
+ [metabase.util.time.impl :as u.time.impl]))
(comment metabase.test-runner.assert-exprs.approximately-equal/keep-me)
+(deftest ^:parallel format-relative-date-range-defaults-start-of-week-test
+ (is (string? (lib.js/format-relative-date-range 0 "week" nil nil #js {}))))
+
+(deftest ^:synchronized format-relative-date-range-uses-start-of-week-test
+ (with-redefs [u.time.impl/now (fn [] (dayjs "2023-01-01T12:00:00"))]
+ (is (= "Jan 1–7, 2023"
+ (lib.js/format-relative-date-range 0 "week" nil nil #js {"start-of-week" "sunday"})))
+ (is (= "Dec 26, 2022 – Jan 1, 2023"
+ (lib.js/format-relative-date-range 0 "week" nil nil #js {"start-of-week" "monday"})))))
+
(deftest ^:parallel query=-test
(doseq [q1 [nil js/undefined]
q2 [nil js/undefined]]
diff --git a/test/metabase/lib/test_metadata.cljc b/test/metabase/lib/test_metadata.cljc
index 37cee52b8ef..850396bc6d3 100644
--- a/test/metabase/lib/test_metadata.cljc
+++ b/test/metabase/lib/test_metadata.cljc
@@ -3997,7 +3997,8 @@
:name "test-data"
:settings {:breakout-bin-width 10.0
:breakout-bins-num 8
- :enable-xrays true}
+ :enable-xrays true
+ :start-of-week :sunday}
:caveats nil
:tables [(table-metadata-method :categories)
(table-metadata-method :checkins)
diff --git a/test/metabase/lib/test_util/generators/filters.cljc b/test/metabase/lib/test_util/generators/filters.cljc
index 83338faaf45..6ee7b05d749 100644
--- a/test/metabase/lib/test_util/generators/filters.cljc
+++ b/test/metabase/lib/test_util/generators/filters.cljc
@@ -183,7 +183,7 @@
(take 7 (iterate #(u.time/add % :day 1) (u.time/local-date))))
(defn- jan1 []
- (u.time/truncate (u.time/local-date) :year))
+ (u.time/truncate {:start-of-week :sunday} (u.time/local-date) :year))
(defmethod gen-filter:exclude-date-options :month-of-year [_unit]
(->> (jan1)
diff --git a/test/metabase/mcp/v2/api_test.clj b/test/metabase/mcp/v2/api_test.clj
index 1225fdac0a7..fd0e36f1fee 100644
--- a/test/metabase/mcp/v2/api_test.clj
+++ b/test/metabase/mcp/v2/api_test.clj
@@ -5,6 +5,7 @@
[metabase.ai-tracing.core :as ait]
[metabase.auth-identity.core :as auth-identity]
[metabase.mcp.db :as mcp.db]
+ [metabase.mcp.http-handler :as mcp.http-handler]
[metabase.mcp.paths :as mcp.paths]
[metabase.mcp.session :as mcp.session]
[metabase.mcp.settings :as mcp.settings]
@@ -678,6 +679,7 @@
{:request-options {:headers (assoc headers "mcp-session-id" session-id)}})))))
(testing "the request it authenticates is stamped `::scope/mcp-ui`, never unrestricted"
(let [info (#'mw.session/current-user-info-for-mcp-ui-credential
+ (:mcp-ui-credentials mcp.http-handler/options)
{:request-method :get
:uri "/api/embed-mcp/bootstrap"
:headers {"x-metabase-mcp-ui-auth" credential}})]
@@ -688,6 +690,7 @@
(testing "a route the credential's scope claim does not cover is authenticated but not scope-checked"
(is (false? (:token-scopes-checked
(#'mw.session/current-user-info-for-mcp-ui-credential
+ (:mcp-ui-credentials mcp.http-handler/options)
{:request-method :post
:uri "/api/dataset"
:headers {"x-metabase-mcp-ui-auth"
diff --git a/test/metabase/mcp/v2/tools/definitions_test.clj b/test/metabase/mcp/v2/tools/definitions_test.clj
index 7cff65080eb..b049d78ce32 100644
--- a/test/metabase/mcp/v2/tools/definitions_test.clj
+++ b/test/metabase/mcp/v2/tools/definitions_test.clj
@@ -3,7 +3,7 @@
[[metabase.mcp.v2.registry/call-tool]] — the same seam the JSON-RPC route uses — so scope
gating, nil-arg stripping, Malli validation, and teaching-error conversion are exercised for
free. Segment/measure domain semantics (definition normalization, revision diffs, the
- permission predicates themselves) are owned by `metabase.segments.api-test`,
+ permission predicates themselves) are owned by `metabase.segments.rest.api-test`,
`metabase.measures.api-test`, and the model tests; this suite pins the tools' contract on
top of them."
(:require
@@ -21,7 +21,7 @@
[metabase.mcp.v2.tools.definitions :as tools.definitions]
[metabase.measures.api :as measures.api]
[metabase.permissions.core :as perms]
- [metabase.segments.api :as segments.api]
+ [metabase.segments.rest.api :as segments.api]
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]
[metabase.util.json :as json]
diff --git a/test/metabase/query_processor/date_bucketing_test.clj b/test/metabase/query_processor/date_bucketing_test.clj
index c1c37e25cf8..6c0d8e34773 100644
--- a/test/metabase/query_processor/date_bucketing_test.clj
+++ b/test/metabase/query_processor/date_bucketing_test.clj
@@ -1460,7 +1460,8 @@
[int]
(mt/run-mbql-query checkins
{:aggregation [[:count]]
- :filter [:= [:field $timestamp nil] (t/format "yyyy-MM-dd" (u.date/truncate :day))]})))))))
+ :filter [:= [:field $timestamp nil]
+ (t/format "yyyy-MM-dd" (t/zoned-date-time))]})))))))
(deftest ^:parallel default-bucketing-test-2
;; this is basically the same test as above, but using the office-checkins dataset instead of the dynamically
@@ -1507,7 +1508,7 @@
[int]
(mt/run-mbql-query checkins
{:aggregation [[:count]]
- :filter [:= [:field $timestamp nil] (str (t/format "yyyy-MM-dd" (u.date/truncate :day))
+ :filter [:= [:field $timestamp nil] (str (t/format "yyyy-MM-dd" (t/zoned-date-time))
"T14:16:00Z")]}))))))))
(def ^:private addition-unit-filtering-vals
diff --git a/test/metabase/query_processor/date_time_zone_functions_test.clj b/test/metabase/query_processor/date_time_zone_functions_test.clj
index d3b1f27eca1..1f183644b37 100644
--- a/test/metabase/query_processor/date_time_zone_functions_test.clj
+++ b/test/metabase/query_processor/date_time_zone_functions_test.clj
@@ -8,6 +8,7 @@
[metabase.driver :as driver]
[metabase.driver.sql.util :as sql.u]
[metabase.driver.util :as driver.u]
+ [metabase.lib-be.core :as lib-be]
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
[metabase.lib.metadata.result-metadata :as lib.metadata.result-metadata]
@@ -103,7 +104,7 @@
(defn- extract
[x op]
- (u.date/extract x (temporal-extraction-op->unit op)))
+ (u.date/extract {:start-of-week (lib-be/start-of-week)} x (temporal-extraction-op->unit op)))
(def ^:private extraction-test-cases
[{:expected-fn (fn [op] [(extract #t "2004-03-19 09:19:09" op) (extract #t "2008-06-20 10:20:10" op)
diff --git a/test/metabase/query_processor/timezones_test.clj b/test/metabase/query_processor/timezones_test.clj
index a387022a015..38a71859e01 100644
--- a/test/metabase/query_processor/timezones_test.clj
+++ b/test/metabase/query_processor/timezones_test.clj
@@ -10,6 +10,7 @@
[metabase.driver :as driver]
[metabase.driver.sql.query-processor :as sql.qp]
[metabase.driver.util :as driver.u]
+ [metabase.lib-be.core :as lib-be]
[metabase.lib.metadata :as lib.metadata]
;; binds mock metadata providers via the ambient store, which the code under test reads
^{:clj-kondo/ignore [:deprecated-namespace]} [metabase.query-processor.store :as qp.store]
@@ -285,7 +286,7 @@
(let [extract-units (cond-> (disj u.date/extract-units :day-of-year)
(not (driver.u/supports? driver/*driver* ::extract-week-of-year-us (mt/db)))
(disj :week-of-year))
- ;; :week-of-year-instance is the behavior of u.date/extract (based on public-settings start-of-week)
+ ;; :week-of-year-instance is the behavior of u.date/extract with the instance start-of-week setting
extract-translate {:year :year-of-era :week-of-year :week-of-year-us}
trunc-units (disj u.date/truncate-units :millisecond :second)
cols (concat
@@ -301,11 +302,12 @@
(into {}
cat
[(for [extract-unit extract-units]
- [extract-unit (u.date/extract in-tz extract-unit)])
+ [extract-unit (u.date/extract {:start-of-week (lib-be/start-of-week)}
+ in-tz extract-unit)])
(for [trunc-unit trunc-units]
[trunc-unit
- (-> in-tz
- (u.date/truncate trunc-unit)
+ (-> (u.date/truncate {:start-of-week (lib-be/start-of-week)}
+ in-tz trunc-unit)
u.date/format-sql
(str/replace #" " "T"))])
[[:dt_tz
@@ -342,7 +344,8 @@
(mt/test-drivers (set/intersection (mt/normal-drivers-with-feature :test/dynamic-dataset-loading)
(set-timezone-drivers))
(testing "Relative to current date"
- (let [expected-datetime (u.date/truncate (t/zoned-date-time) :second)]
+ (let [expected-datetime (u.date/truncate {:start-of-week (lib-be/start-of-week)}
+ (t/zoned-date-time) :second)]
(mt/with-temp-test-data [["relative_filter"
[{:field-name "created", :base-type :type/DateTimeWithTZ}]
[[expected-datetime]]]]
@@ -367,7 +370,8 @@
(mt/test-drivers (filter #(driver/database-supports? % :test/dynamic-dataset-loading nil)
(set-timezone-drivers))
(testing "Relative to days since"
- (let [expected-datetime (u.date/truncate (u.date/add (t/zoned-date-time) :day -1) :second)]
+ (let [expected-datetime (u.date/truncate {:start-of-week (lib-be/start-of-week)}
+ (u.date/add (t/zoned-date-time) :day -1) :second)]
(mt/with-temp-test-data [["relative_filter"
[{:field-name "created", :base-type :type/DateTimeWithTZ}]
[[expected-datetime]]]]
diff --git a/test/metabase/segments/api_test.clj b/test/metabase/segments/rest/api_test.clj
similarity index 99%
rename from test/metabase/segments/api_test.clj
rename to test/metabase/segments/rest/api_test.clj
index aa5ad5b10d2..41b99f82652 100644
--- a/test/metabase/segments/api_test.clj
+++ b/test/metabase/segments/rest/api_test.clj
@@ -1,6 +1,6 @@
-(ns metabase.segments.api-test
+(ns metabase.segments.rest.api-test
"Tests for /api/segment endpoints."
- {:clj-kondo/config '{:linters {:deprecated-var {:exclude {metabase.test.data/mbql-query {:namespaces [metabase.segments.api-test]}}}}}}
+ {:clj-kondo/config '{:linters {:deprecated-var {:exclude {metabase.test.data/mbql-query {:namespaces [metabase.segments.rest.api-test]}}}}}}
(:require
[clojure.test :refer :all]
[metabase.api.response :as api.response]
diff --git a/test/metabase/server/handler_test.clj b/test/metabase/server/handler_test.clj
new file mode 100644
index 00000000000..1e7d596c2c5
--- /dev/null
+++ b/test/metabase/server/handler_test.clj
@@ -0,0 +1,42 @@
+(ns metabase.server.handler-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase.mcp.http-handler :as mcp.http-handler]
+ [metabase.server.handler :as server.handler]
+ [metabase.test.fixtures :as fixtures]
+ [metabase.tiles.settings]))
+
+;; The security middleware reads `map-tile-server-url`, which this namespace defines.
+(comment metabase.tiles.settings/keep-me)
+
+(use-fixtures :once (fixtures/initialize :db))
+
+(defn- cors-options [origin]
+ (assoc mcp.http-handler/options :cors {:origins-fn (constantly origin)
+ :sandbox-origin?-fn (constantly false)}))
+
+(def ^:private options
+ (cors-options "https://a.example"))
+
+(defn- allowed-origin [handler origin]
+ (let [response (promise)]
+ (handler {:request-method :get, :uri "/api/anything", :headers {"origin" origin}}
+ #(deliver response %)
+ #(deliver response %))
+ (get-in (deref response 10000 ::timed-out) [:headers "Access-Control-Allow-Origin"])))
+
+(deftest dev-handler-rebuilds-when-options-var-changes-test
+ (let [handler (#'server.handler/dev-handler (fn [_request respond _raise]
+ (respond {:status 200, :headers {}, :body "ok"}))
+ #'options)]
+ (is (= "https://a.example" (allowed-origin handler "https://a.example")))
+ (with-redefs [options (cors-options "https://b.example")]
+ (is (= "https://b.example" (allowed-origin handler "https://b.example")))
+ (is (nil? (allowed-origin handler "https://a.example"))))))
+
+(deftest handler-options-require-credential-fns-test
+ ;; `make-handler` checks this explicitly, since its `mu/defn` schema is not checked in prod.
+ (doseq [k [:oauth-bearer :mcp-ui-credentials]]
+ (testing k
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"does not match schema"
+ (#'server.handler/current-options (dissoc mcp.http-handler/options k)))))))
diff --git a/test/metabase/server/middleware/body_limit_test.clj b/test/metabase/server/middleware/body_limit_test.clj
index 07b7cf4014c..abf06c741ea 100644
--- a/test/metabase/server/middleware/body_limit_test.clj
+++ b/test/metabase/server/middleware/body_limit_test.clj
@@ -2,10 +2,10 @@
(:require
[clojure.test :refer :all]
[metabase.server.middleware.body-limit :as mw.body-limit]
- [metabase.server.test-handler :as server.test-handler]
[metabase.test :as mt]
[metabase.test.data.users :as test.users]
- [metabase.test.fixtures :as fixtures])
+ [metabase.test.fixtures :as fixtures]
+ [metabase.test.server.handler :as test.server.handler])
(:import
(java.io ByteArrayInputStream InputStream)))
@@ -149,7 +149,7 @@
[headers body-bytes & {:keys [declare-length? uri], :or {uri "/api/card"}}]
(let [counter (atom 0)
response (promise)]
- ((server.test-handler/test-handler)
+ ((test.server.handler/test-handler)
(cond-> {:request-method :post
:uri uri
:headers headers
diff --git a/test/metabase/server/middleware/exceptions_test.clj b/test/metabase/server/middleware/exceptions_test.clj
index d1df5b4098e..513e7e2e246 100644
--- a/test/metabase/server/middleware/exceptions_test.clj
+++ b/test/metabase/server/middleware/exceptions_test.clj
@@ -213,6 +213,19 @@
(is (not (contains? (:body @captured-response) :trace))
"Response should not include stacktrace"))))))
+(deftest catch-api-exceptions-middleware-includes-configured-cors-test
+ (let [origin "https://mcp.example"
+ cors {:origins-fn (constantly origin)
+ :sandbox-origin?-fn (constantly false)}
+ handler (mw.exceptions/catch-api-exceptions
+ (fn [_request _respond raise]
+ (raise (Exception. "boom")))
+ cors)
+ response (handler {:headers {"origin" origin}}
+ identity
+ #(throw %))]
+ (is (= origin (get-in response [:headers "Access-Control-Allow-Origin"])))))
+
(deftest catch-api-exceptions-middleware-eof-exception-logs-request-info-test
(testing "EofException (request canceled) log line includes the HTTP method, URI, and client IP"
(let [handler (mw.exceptions/catch-api-exceptions
diff --git a/test/metabase/server/middleware/json_test.clj b/test/metabase/server/middleware/json_test.clj
index a1a453afbfd..0cc690bca44 100644
--- a/test/metabase/server/middleware/json_test.clj
+++ b/test/metabase/server/middleware/json_test.clj
@@ -3,8 +3,8 @@
[clojure.java.io :as io]
[clojure.test :refer :all]
[metabase.server.middleware.json :as mw.json]
- [metabase.server.test-handler :as server.test-handler]
[metabase.test.http-client]
+ [metabase.test.server.handler :as test.server.handler]
[metabase.util.json :as json]))
(comment mw.json/keep-me) ; so custom Cheshire encoders are loaded
@@ -21,7 +21,7 @@
(defn- raw-json-req
"Kind of `mt/http-request`, but is less picky about body :)"
[method url ^String body]
- ((server.test-handler/test-handler)
+ ((test.server.handler/test-handler)
{:method method
:uri (str metabase.test.http-client/*url-prefix* url)
:headers {"content-type" "application/json"}
diff --git a/test/metabase/server/middleware/offset_paging_test.clj b/test/metabase/server/middleware/offset_paging_test.clj
index 9fc707788f6..ffd4454559b 100644
--- a/test/metabase/server/middleware/offset_paging_test.clj
+++ b/test/metabase/server/middleware/offset_paging_test.clj
@@ -2,6 +2,7 @@
(:require
[clojure.java.io :as io]
[clojure.test :refer :all]
+ [metabase.mcp.http-handler :as mcp.http-handler]
[metabase.request.core :as request]
[metabase.server.handler :as handler]
[metabase.tiles.settings]
@@ -19,7 +20,7 @@
:offset (request/offset)
:paged? (request/paged?)
:params (:params request)})))
- handler* (#'handler/apply-middleware handler)
+ handler* (#'handler/apply-middleware handler mcp.http-handler/options)
respond identity
raise (fn [e] (throw e))]
(handler* request respond raise)))
diff --git a/test/metabase/server/middleware/security_mcp_test.clj b/test/metabase/server/middleware/security_mcp_test.clj
index 69d46061980..cd5d8a3c984 100644
--- a/test/metabase/server/middleware/security_mcp_test.clj
+++ b/test/metabase/server/middleware/security_mcp_test.clj
@@ -2,16 +2,22 @@
(:require
[clojure.string :as str]
[clojure.test :refer :all]
+ [metabase.mcp.http-handler :as mcp.http-handler]
[metabase.mcp.settings :as mcp.settings]
+ [metabase.server.handler :as server.handler]
[metabase.server.middleware.security :as mw.security]
[metabase.test :as mt]))
+(deftest make-handler-accepts-mcp-options-test
+ (is (ifn? (server.handler/make-handler (fn [_request _respond _raise]) #'mcp.http-handler/options))))
+
(defn- get-cors-origin-header
"Returns the Access-Control-Allow-Origin header value for a given request origin."
[request-origin]
(let [wrapped-handler (mw.security/add-security-headers
(fn [_request respond _raise]
- (respond {:status 200 :headers {} :body "ok"})))
+ (respond {:status 200, :headers {}, :body "ok"}))
+ (:cors mcp.http-handler/options))
response (wrapped-handler {:headers {"origin" request-origin}
:uri "/api/dashboard/1"}
identity identity)]
@@ -32,7 +38,8 @@
[request-origin]
(let [wrapped-handler (mw.security/add-security-headers
(fn [_request respond _raise]
- (respond {:status 200 :headers {} :body "ok"})))
+ (respond {:status 200, :headers {}, :body "ok"}))
+ (:cors mcp.http-handler/options))
response (wrapped-handler {:headers {"origin" request-origin}
:uri "/api/metabase-mcp"}
identity identity)]
diff --git a/test/metabase/server/middleware/session_oauth_test.clj b/test/metabase/server/middleware/session_oauth_test.clj
index 300a2f1cde6..6d54572ab1a 100644
--- a/test/metabase/server/middleware/session_oauth_test.clj
+++ b/test/metabase/server/middleware/session_oauth_test.clj
@@ -11,6 +11,7 @@
[metabase.agent-api.api]
[metabase.api.macros.scope :as scope]
[metabase.initialization-status.core :as init-status]
+ [metabase.mcp.http-handler :as mcp.http-handler]
[metabase.oauth-server.core :as oauth-server]
[metabase.oauth-server.events.revoke-on-deactivation] ; for side effects: revokes tokens on deactivation
[metabase.oauth-server.test-util :as oauth-server.tu]
@@ -26,8 +27,11 @@
;; the isolated test runner never boots the web server, so mark init complete as session_test does.
(init-status/set-complete!)
-(def ^:private merge-current-user-info #'mw.session/merge-current-user-info)
-(def ^:private oauth-token->token-scopes #'mw.session/oauth-token->token-scopes)
+(def ^:private merge-current-user-info
+ (partial #'mw.session/merge-current-user-info mcp.http-handler/options))
+
+(def ^:private oauth-token->token-scopes
+ (partial #'mw.session/oauth-token->token-scopes oauth-server/full-access-scope))
(defn- bearer-request [token]
{:headers {"authorization" (str "Bearer " token)}})
diff --git a/test/metabase/server/middleware/session_test.clj b/test/metabase/server/middleware/session_test.clj
index f6c6cc83db4..51e654d7670 100644
--- a/test/metabase/server/middleware/session_test.clj
+++ b/test/metabase/server/middleware/session_test.clj
@@ -189,7 +189,7 @@
(let [request (-> (ring.mock/request :get "/anyurl")
(ring.mock/header session-header header-session-key)
(assoc :cookies {session-cookie {:value cookie-session-key}}))
- request' (#'mw.session/merge-current-user-info (wrapped-handler request))]
+ request' (#'mw.session/merge-current-user-info nil (wrapped-handler request))]
(is (= (mt/user->id :lucky)
(:metabase-user-id request')))
(testing "\nthe request carries the header's session, not the cookie's"
@@ -207,7 +207,7 @@
(let [request (-> (ring.mock/request :get "/anyurl")
(ring.mock/header session-header header-session-key)
(assoc :cookies {session-cookie {:value stale-cookie-key}}))
- request' (#'mw.session/merge-current-user-info (wrapped-handler request))]
+ request' (#'mw.session/merge-current-user-info nil (wrapped-handler request))]
(is (= (mt/user->id :lucky)
(:metabase-user-id request')))
(is (= header-session-key (:metabase-session-key request')))))))))
@@ -223,7 +223,7 @@
(let [request (-> (ring.mock/request :get "/anyurl")
(ring.mock/header session-header stale-header-key)
(assoc :cookies {session-cookie {:value cookie-session-key}}))
- request' (#'mw.session/merge-current-user-info (wrapped-handler request))]
+ request' (#'mw.session/merge-current-user-info nil (wrapped-handler request))]
(is (nil? (:metabase-user-id request')))))))))
(deftest cookie-used-when-no-session-header-test
@@ -235,7 +235,7 @@
(fn []
(let [request (assoc (ring.mock/request :get "/anyurl")
:cookies {session-cookie {:value cookie-session-key}})
- request' (#'mw.session/merge-current-user-info (wrapped-handler request))]
+ request' (#'mw.session/merge-current-user-info nil (wrapped-handler request))]
(is (= (mt/user->id :crowberto)
(:metabase-user-id request')))
(is (= :normal (:metabase-session-type request')))))))))
@@ -246,7 +246,7 @@
(let [request (-> (ring.mock/request :get "/anyurl")
(ring.mock/header session-header (str (random-uuid)))
(assoc :cookies {session-cookie {:value (str (random-uuid))}}))
- request' (#'mw.session/merge-current-user-info (wrapped-handler request))]
+ request' (#'mw.session/merge-current-user-info nil (wrapped-handler request))]
(is (nil? (:metabase-user-id request'))))))
(deftest current-user-info-for-api-key-test
@@ -264,7 +264,7 @@
:is-data-analyst? false
:user-locale nil
:embedding/auth-method "api-key"})
- (#'mw.session/merge-current-user-info req)))))
+ (#'mw.session/merge-current-user-info nil req)))))
(testing "Include :is-group-manager? if we have EE + :advanced-permissions "
(when config/ee-available?
(mt/with-premium-features #{:advanced-permissions}
@@ -274,7 +274,7 @@
:is-group-manager? false
:user-locale nil
:embedding/auth-method "api-key"})
- (#'mw.session/merge-current-user-info req))))))))))
+ (#'mw.session/merge-current-user-info nil req))))))))))
(deftest api-key-hash-encrypted-at-rest-test
;; isolated app DB: runs with an encryption key active, so nothing here may touch the shared test DB
@@ -295,12 +295,12 @@
"it should decrypt to the (plaintext) bcrypt hash")))
(testing "a valid key still authenticates (middleware decrypts the raw hash before the bcrypt compare)"
(is (= (mt/user->id :lucky)
- (:metabase-user-id (#'mw.session/merge-current-user-info {:headers {"x-api-key" "mb_encrypted123"}})))))
+ (:metabase-user-id (#'mw.session/merge-current-user-info nil {:headers {"x-api-key" "mb_encrypted123"}})))))
(testing "a plaintext bcrypt hash injected via direct SQL is rejected, even though it is a correct hash of the key"
(t2/query {:update :api_key
:set {:key (u.password/hash-bcrypt "mb_encrypted123")}
:where [:= :id api-key-id]})
- (is (nil? (:metabase-user-id (#'mw.session/merge-current-user-info {:headers {"x-api-key" "mb_encrypted123"}})))
+ (is (nil? (:metabase-user-id (#'mw.session/merge-current-user-info nil {:headers {"x-api-key" "mb_encrypted123"}})))
"strict decrypt rejects the unencrypted hash")
;; restore a properly-encrypted hash so `with-temp` cleanup (whose before-delete reads the row) doesn't hit the
;; strict decrypt on the corrupted plaintext value
@@ -310,7 +310,7 @@
(deftest ^:parallel current-user-info-for-api-key-test-1b
(testing "Various invalid API keys do not modify the request"
- (are [req] (= req (#'mw.session/merge-current-user-info req))
+ (are [req] (= req (#'mw.session/merge-current-user-info nil req))
;; a matching prefix, invalid key
{:headers {"x-api-key" "mb_fooby"}}
@@ -323,7 +323,7 @@
(deftest ^:parallel current-user-info-for-api-key-log-errors-test
(testing "Log an error about invalid API keys"
(mt/with-log-messages-for-level [messages [metabase.server.middleware.session :error]]
- (#'mw.session/merge-current-user-info {:headers {"x-api-key" "mb_fooby"}})
+ (#'mw.session/merge-current-user-info nil {:headers {"x-api-key" "mb_fooby"}})
(is (= [{:namespace 'metabase.server.middleware.session
:level :error
:e nil
@@ -333,7 +333,7 @@
(deftest ^:parallel current-user-info-for-api-key-log-errors-test-2
(testing "Do not include the key itself in the error message -- fall back to a generic error message"
(mt/with-log-messages-for-level [messages [metabase.server.middleware.session :error]]
- (#'mw.session/merge-current-user-info {:headers {"x-api-key" "characters"}})
+ (#'mw.session/merge-current-user-info nil {:headers {"x-api-key" "characters"}})
(is (= [{:namespace 'metabase.server.middleware.session
:level :error
:e nil
@@ -351,7 +351,7 @@
::api-key/unhashed-key (u.secret/secret "mb_foobar123")}]
(let [authed? (fn [] (mt/with-premium-features #{}
(boolean (:metabase-user-id
- (#'mw.session/merge-current-user-info {:headers {"x-api-key" "mb_foobar123"}})))))]
+ (#'mw.session/merge-current-user-info nil {:headers {"x-api-key" "mb_foobar123"}})))))]
(testing "authenticates while its synthetic user is active"
(is (authed?)))
(testing "deactivating the creator does NOT revoke the key — creator_id is attribution only"
@@ -369,7 +369,7 @@
::api-key/unhashed-key (u.secret/secret "mb_foobar123")}]
(testing "An API key without an internal user (e.g. a SCIM key) should not modify the request"
(let [req {:headers {"x-api-key" "mb_foobar123"}}]
- (is (= req (#'mw.session/merge-current-user-info req)))))))
+ (is (= req (#'mw.session/merge-current-user-info nil req)))))))
(defn- simple-auth-handler
"A handler that just does authentication and returns a map from the dynamic variables that are bound as a result."
diff --git a/test/metabase/server/auth_wrapper_test.clj b/test/metabase/sso/auth_wrapper_test.clj
similarity index 96%
rename from test/metabase/server/auth_wrapper_test.clj
rename to test/metabase/sso/auth_wrapper_test.clj
index 3a0c69f7925..9f0d21401e9 100644
--- a/test/metabase/server/auth_wrapper_test.clj
+++ b/test/metabase/sso/auth_wrapper_test.clj
@@ -1,4 +1,4 @@
-(ns metabase.server.auth-wrapper-test
+(ns metabase.sso.auth-wrapper-test
(:require
[clojure.test :refer :all]
[metabase.config.core :as config]
diff --git a/test/metabase/sync/task/sync_databases_test.clj b/test/metabase/sync/task/sync_databases_test.clj
index 84cc77785fb..a73ea144bc8 100644
--- a/test/metabase/sync/task/sync_databases_test.clj
+++ b/test/metabase/sync/task/sync_databases_test.clj
@@ -271,7 +271,7 @@
:ran-update-field-values? update-field-values-ran?})))))))
#_(defn- cron-schedule-for-next-year []
- (format "0 15 10 * * ? %d" (inc (u.date/extract :year))))
+ (format "0 15 10 * * ? %d" (inc (u.date/extract {:start-of-week :sunday} (t/zoned-date-time) :year))))
;; this test fails all the time -- disabled for now until I figure out how to fix it - Cam
#_(deftest check-sync-tasks-run-test
diff --git a/test/metabase/task/secure_delegate_test.clj b/test/metabase/task/secure_delegate/core_test.clj
similarity index 94%
rename from test/metabase/task/secure_delegate_test.clj
rename to test/metabase/task/secure_delegate/core_test.clj
index 6fa9d0082fe..bbf4d6f3729 100644
--- a/test/metabase/task/secure_delegate_test.clj
+++ b/test/metabase/task/secure_delegate/core_test.clj
@@ -1,8 +1,8 @@
-(ns metabase.task.secure-delegate-test
+(ns metabase.task.secure-delegate.core-test
(:require
[clojure.test :refer :all]
[metabase.classloader.core :as classloader]
- [metabase.task.secure-delegate :as secure-delegate]
+ [metabase.task.secure-delegate.core :as secure-delegate]
[metabase.util.deserialization-allowlist :as dal])
(:import
(java.io ByteArrayInputStream ByteArrayOutputStream ObjectOutputStream)
@@ -73,7 +73,8 @@
(deftest getObjectFromBlob-override-canary-test
(testing "each secure delegate declares its OWN getObjectFromBlob(ResultSet, String) — if a Quartz
bump renames or re-signs that method our override silently stops overriding, and this fails"
- (doseq [class-name ["metabase.task.SecureStdDelegate" "metabase.task.SecurePostgresDelegate"]]
+ (doseq [class-name ["metabase.task.secure_delegate.SecureStdDelegate"
+ "metabase.task.secure_delegate.SecurePostgresDelegate"]]
(let [k (Class/forName class-name true (classloader/the-classloader))
m (.getMethod k "getObjectFromBlob" (into-array Class [ResultSet String]))]
(is (= k (.getDeclaringClass m))
diff --git a/test/metabase/test/data/dataset_definitions.clj b/test/metabase/test/data/dataset_definitions.clj
index 7d0a9ee3ad4..debaa2b08de 100644
--- a/test/metabase/test/data/dataset_definitions.clj
+++ b/test/metabase/test/data/dataset_definitions.clj
@@ -81,8 +81,8 @@
LocalTime (throw (Exception. "Cannot convert a time to a date"))
OffsetTime (throw (Exception. "Cannot convert a time to a date"))
;; since there is no `OffsetDate` class use `OffsetDateTime`, but truncated to day
- OffsetDateTime (u.date/truncate :day)
- ZonedDateTime (u.date/truncate :day))))
+ OffsetDateTime (u.date/truncate {:start-of-week :sunday} t :day)
+ ZonedDateTime (u.date/truncate {:start-of-week :sunday} t :day))))
(defn- time-only
"Convert time or datetime temporal value to `t` to an appropriate time type, discarding date information."
diff --git a/test/metabase/test/http_client.clj b/test/metabase/test/http_client.clj
index b225282270d..92932644164 100644
--- a/test/metabase/test/http_client.clj
+++ b/test/metabase/test/http_client.clj
@@ -15,9 +15,9 @@
[metabase.server.instance :as server.instance]
[metabase.server.middleware.session :as mw.session]
[metabase.server.streaming-response :as streaming-response]
- [metabase.server.test-handler :as server.test-handler]
[metabase.test-runner.assert-exprs :as test-runner.assert-exprs]
[metabase.test.initialize :as initialize]
+ [metabase.test.server.handler :as test.server.handler]
[metabase.util :as u]
[metabase.util.date-2 :as u.date]
[metabase.util.json :as json]
@@ -419,7 +419,7 @@
_ (log/debug method-name (pr-str url) (pr-str request))
thunk (fn []
(try
- ((server.test-handler/test-handler) request coerce-mock-response-body (fn raise [e] (throw e)))
+ ((test.server.handler/test-handler) request coerce-mock-response-body (fn raise [e] (throw e)))
(catch clojure.lang.ExceptionInfo e
(log/debug e method-name url)
(ex-data e))
diff --git a/test/metabase/test/initialize/db.clj b/test/metabase/test/initialize/db.clj
index 4cd74fdae10..7d920df32bc 100644
--- a/test/metabase/test/initialize/db.clj
+++ b/test/metabase/test/initialize/db.clj
@@ -2,7 +2,7 @@
(:require
[metabase.app-db.connection :as mdb.connection]
[metabase.app-db.core :as mdb]
- [metabase.task.bootstrap :as task.bootstrap]
+ [metabase.app-db.quartz :as app-db.quartz]
[metabase.util :as u]
[metabase.util.log :as log]
[toucan2.core :as t2]))
@@ -16,7 +16,7 @@
[]
(binding [mdb.connection/*application-db* (.getRawRoot ^clojure.lang.Var #'mdb.connection/*application-db*)]
(log/info (u/format-color 'blue "Setting up %s test DB and running migrations..." (mdb/db-type)))
- (task.bootstrap/set-jdbc-backend-properties! (mdb/db-type))
+ (app-db.quartz/set-jdbc-backend-properties! (mdb/db-type))
(mdb/setup-db! :create-sample-content? false) ; skip sample content for speedy tests. this doesn't reflect production
(log/info (t2/with-connection [^java.sql.Connection conn]
(let [metadata (.getMetaData conn)]
diff --git a/test/metabase/test/initialize/web_server.clj b/test/metabase/test/initialize/web_server.clj
index 13bc156bfc9..5115745de6d 100644
--- a/test/metabase/test/initialize/web_server.clj
+++ b/test/metabase/test/initialize/web_server.clj
@@ -3,15 +3,15 @@
[metabase.config.core :as config]
[metabase.initialization-status.core :as init-status]
[metabase.server.core :as server]
- [metabase.server.test-handler :as server.test-handler]
[metabase.settings.core :as setting]
+ [metabase.test.server.handler :as test.server.handler]
[metabase.util.log :as log]))
(set! *warn-on-reflection* true)
(defn init! []
(try
- (server/start-web-server! (server.test-handler/test-handler))
+ (server/start-web-server! (test.server.handler/test-handler))
(log/infof "Started test server on port %d" (server/server-port))
(catch Throwable e
(log/fatal e "Web server failed to start")
diff --git a/test/metabase/server/test_handler.clj b/test/metabase/test/server/handler.clj
similarity index 50%
rename from test/metabase/server/test_handler.clj
rename to test/metabase/test/server/handler.clj
index d0c20af5f4c..654df3ba090 100644
--- a/test/metabase/server/test_handler.clj
+++ b/test/metabase/test/server/handler.clj
@@ -1,16 +1,22 @@
-(ns metabase.server.test-handler
+(ns metabase.test.server.handler
(:require
[metabase.api.macros :as api.macros]
+ [metabase.mcp.http-handler :as mcp.http-handler]
+ [metabase.oauth-server.api :as oauth-server.api]
[metabase.server.core :as server]
+ [metabase.sso.auth-wrapper :as auth-wrapper]
[metabase.util.log :as log]
[metabase.util.malli :as mu]))
(mu/defn- make-test-handler :- ::api.macros/handler
[]
- ;; late-bound: a static require here would drag the whole API route tree into the server module
- (let [api-routes #_{:clj-kondo/ignore [:metabase/modules]} (requiring-resolve 'metabase.api-routes.core/routes)
- server-routes (server/make-routes api-routes)
- handler (server/make-handler server-routes)]
+ ;; Resolved here because a static require would make loading `metabase.test` load every API namespace.
+ (let [api-routes (requiring-resolve 'metabase.api-routes.core/routes)
+ server-routes (server/make-routes {:api api-routes
+ :auth #'auth-wrapper/routes
+ :oauth #'oauth-server.api/oauth-routes
+ :well-known #'oauth-server.api/well-known-routes})
+ handler (server/make-handler server-routes #'mcp.http-handler/options)]
(fn [request respond raise]
(letfn [(raise' [e]
(log/errorf "ERROR HANDLING REQUEST! <async raise> %s" request)
diff --git a/test/metabase/test/server/handler_test.clj b/test/metabase/test/server/handler_test.clj
new file mode 100644
index 00000000000..35ccb6a762e
--- /dev/null
+++ b/test/metabase/test/server/handler_test.clj
@@ -0,0 +1,17 @@
+(ns metabase.test.server.handler-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase.mcp.http-handler :as mcp.http-handler]
+ [metabase.server.core :as server]
+ [metabase.test :as mt]
+ [metabase.test.server.handler]))
+
+(deftest make-test-handler-configures-mcp-test
+ (let [handler (fn [_request _respond _raise])
+ handler-options (atom nil)]
+ (mt/with-dynamic-fn-redefs [server/make-routes (fn [_routes] handler)
+ server/make-handler (fn [server-routes options]
+ (reset! handler-options options)
+ server-routes)]
+ (#'metabase.test.server.handler/make-test-handler))
+ (is (= #'mcp.http-handler/options @handler-options))))
diff --git a/test/metabase/tracing/quartz_test.clj b/test/metabase/tracing/quartz_test.clj
index 615288cfb1a..65e2e09f3d6 100644
--- a/test/metabase/tracing/quartz_test.clj
+++ b/test/metabase/tracing/quartz_test.clj
@@ -1,7 +1,7 @@
(ns metabase.tracing.quartz-test
(:require
[clojure.test :refer [deftest is testing]]
- [metabase.task.bootstrap :as task.bootstrap]
+ [metabase.app-db.quartz :as app-db.quartz]
[metabase.tracing.core :as tracing]
[metabase.tracing.quartz :as tracing.quartz])
(:import
@@ -247,12 +247,12 @@
(deftest set-connection-interceptor-test
(testing "set-connection-interceptor! installs and removes interceptors"
- (let [the-atom @#'task.bootstrap/connection-interceptor
+ (let [the-atom @#'app-db.quartz/connection-interceptor
original @the-atom]
(try
- (task.bootstrap/set-connection-interceptor! identity)
+ (app-db.quartz/set-connection-interceptor! identity)
(is (some? @the-atom))
- (task.bootstrap/set-connection-interceptor! nil)
+ (app-db.quartz/set-connection-interceptor! nil)
(is (nil? @the-atom))
(finally
(reset! the-atom original))))))
diff --git a/test/metabase/util/date_2_test.clj b/test/metabase/util/date_2_test.clj
index b0e895af68c..ec3521b4894 100644
--- a/test/metabase/util/date_2_test.clj
+++ b/test/metabase/util/date_2_test.clj
@@ -12,6 +12,8 @@
(set! *warn-on-reflection* true)
+(def ^:private time-config {:start-of-week :sunday})
+
(deftest parse-test
;; system timezone should not affect the way strings are parsed
(doseq [system-timezone-id ["UTC" "US/Pacific"]]
@@ -231,17 +233,17 @@
(let [now (t/zoned-date-time "2019-12-10T17:17:00-08:00[US/Pacific]")]
(testing "adjust temporal value to first day of week (Sunday)"
(is (= (t/zoned-date-time "2019-12-08T17:17-08:00[US/Pacific]")
- (t/adjust now (u.date/adjuster :first-day-of-week)))))
+ (t/adjust now (u.date/adjuster :first-day-of-week :sunday)))))
(testing "adjust temporal value to first day of first week of year (previous or same Sunday as first day of year)"
(is (= (t/zoned-date-time "2018-12-30T17:17-08:00[US/Pacific]")
- (t/adjust now (u.date/adjuster :first-week-of-year))
- (t/adjust now (u.date/adjuster :week-of-year 1)))))
+ (t/adjust now (u.date/adjuster :first-week-of-year :sunday))
+ (t/adjust now (u.date/adjuster :week-of-year 1 :sunday)))))
(testing "adjust temporal value to the 50th week of the year"
(is (= (t/zoned-date-time "2019-12-08T17:17-08:00[US/Pacific]")
- (t/adjust now (u.date/adjuster :week-of-year 50)))))))
+ (t/adjust now (u.date/adjuster :week-of-year 50 :sunday)))))))
(deftest ^:parallel extract-test
- (testing "u.date/extract with 2 args"
+ (testing "u.date/extract with an explicit temporal value"
;; everything is at `Sunday October 27th 2019 2:03:40.555 PM` or subset thereof
(let [temporal-category->sample-values {:dates [(t/local-date 2019 10 27)]
:times [(t/local-time 14 3 40 (* 555 1000000))
@@ -261,30 +263,25 @@
t (get temporal-category->sample-values category)
[unit expected] unit->expected]
(is (= expected
- (u.date/extract t unit))
- (format "Extract %s from %s %s should be %s" unit (class t) t expected)))))
- (testing "u.date/extract with 1 arg (extract from now)"
- (mt/with-clock (t/mock-clock (t/instant "2019-11-18T22:31:00Z"))
- (is (= 2
- (u.date/extract :day-of-week))))))
-
-(deftest extract-start-of-week-test
- (testing "`extract` `:day-of-week` and `:week-of-year` should respect the `start-of-week` Setting (#14294)"
- (doseq [[first-day-of-week unit->expected] {"sunday" {:week-of-year 9, :day-of-week 3}
- "monday" {:week-of-year 9, :day-of-week 2}
- "tuesday" {:week-of-year 9, :day-of-week 1}
- "wednesday" {:week-of-year 8, :day-of-week 7}
- "thursday" {:week-of-year 8, :day-of-week 6}
- "friday" {:week-of-year 8, :day-of-week 5}
- "saturday" {:week-of-year 9, :day-of-week 4}}
+ (u.date/extract time-config t unit))
+ (format "Extract %s from %s %s should be %s" unit (class t) t expected))))))
+
+(deftest ^:parallel extract-start-of-week-test
+ (testing "`extract` `:day-of-week` and `:week-of-year` should respect the supplied `:start-of-week` (#14294)"
+ (doseq [[first-day-of-week unit->expected] {:sunday {:week-of-year 9, :day-of-week 3}
+ :monday {:week-of-year 9, :day-of-week 2}
+ :tuesday {:week-of-year 9, :day-of-week 1}
+ :wednesday {:week-of-year 8, :day-of-week 7}
+ :thursday {:week-of-year 8, :day-of-week 6}
+ :friday {:week-of-year 8, :day-of-week 5}
+ :saturday {:week-of-year 9, :day-of-week 4}}
unit [:week-of-year :day-of-week]]
- (mt/with-temporary-setting-values [start-of-week first-day-of-week]
- (testing (pr-str (list 'u.date/extract (symbol "#_Tuesday") #t "2021-02-23" unit))
- (is (= (get unit->expected unit)
- (u.date/extract #t "2021-02-23" unit))))))))
+ (testing (pr-str (list 'u.date/extract (symbol "#_Tuesday") #t "2021-02-23" unit first-day-of-week))
+ (is (= (get unit->expected unit)
+ (u.date/extract {:start-of-week first-day-of-week} #t "2021-02-23" unit)))))))
(deftest ^:parallel truncate-test
- (testing "u.date/truncate with 2 args"
+ (testing "u.date/truncate with an explicit temporal value"
(let [t->unit->expected
{(t/local-date 2019 10 27)
{:second (t/local-date 2019 10 27)
@@ -328,29 +325,24 @@
(doseq [[t unit->expected] t->unit->expected
[unit expected] unit->expected]
(is (= expected
- (u.date/truncate t unit))
- (format "Truncate %s %s to %s should be %s" (class t) t unit expected)))))
- (testing "u.date/truncate with 1 arg (truncate now)"
- (mt/with-clock (t/mock-clock (t/instant "2019-11-18T22:31:00Z"))
- (is (= (t/zoned-date-time "2019-11-18T00:00Z[UTC]")
- (u.date/truncate :day))))))
-
-(deftest truncate-start-of-week-test
- (testing "`truncate` to `:week` should respect the `start-of-week` Setting (#14294)"
- (doseq [[first-day-of-week expected] {"sunday" #t "2021-02-21"
- "monday" #t "2021-02-22"
- "tuesday" #t "2021-02-23"
- "wednesday" #t "2021-02-17"
- "thursday" #t "2021-02-18"
- "friday" #t "2021-02-19"
- "saturday" #t "2021-02-20"}]
- (mt/with-temporary-setting-values [start-of-week first-day-of-week]
- (is (= expected
- (u.date/truncate #_Tuesday #t "2021-02-23" :week)))))))
+ (u.date/truncate time-config t unit))
+ (format "Truncate %s %s to %s should be %s" (class t) t unit expected))))))
+
+(deftest ^:parallel truncate-start-of-week-test
+ (testing "`truncate` to `:week` should respect the supplied `:start-of-week` (#14294)"
+ (doseq [[first-day-of-week expected] {:sunday #t "2021-02-21"
+ :monday #t "2021-02-22"
+ :tuesday #t "2021-02-23"
+ :wednesday #t "2021-02-17"
+ :thursday #t "2021-02-18"
+ :friday #t "2021-02-19"
+ :saturday #t "2021-02-20"}]
+ (is (= expected
+ (u.date/truncate {:start-of-week first-day-of-week} #_Tuesday #t "2021-02-23" :week))))))
(deftest ^:parallel bucket-test
(are [unit expected] (= expected
- (u.date/bucket #t "2024-01-03" unit))
+ (u.date/bucket time-config #t "2024-01-03" unit))
:month #t "2024-01-01"
:month-of-year 1))
@@ -378,26 +370,34 @@
(is (= {:start (t/zoned-date-time "2019-11-17T00:00Z[UTC]")
:end (t/zoned-date-time "2019-11-24T00:00Z[UTC]")}
(mt/with-clock (t/mock-clock (t/instant "2019-11-18T22:31:00Z"))
- (u.date/range :week)))))
+ (u.date/range time-config (t/zoned-date-time) :week)))))
(testing "with 2 args"
(is (= {:start (t/zoned-date-time "2019-10-27T00:00Z[UTC]")
:end (t/zoned-date-time "2019-11-03T00:00Z[UTC]")}
- (u.date/range (t/zoned-date-time "2019-11-01T15:29:00Z[UTC]") :week))))
+ (u.date/range time-config (t/zoned-date-time "2019-11-01T15:29:00Z[UTC]") :week))))
(testing "with 3 args (start/end inclusitivity options)"
(testing "exclusive start"
(is (= {:start (t/local-date-time "2019-10-31T23:59:59.999"), :end (t/local-date-time "2019-12-01T00:00")}
- (u.date/range (t/local-date-time "2019-11-18T00:00") :month {:start :exclusive}))))
+ (u.date/range time-config
+ (t/local-date-time "2019-11-18T00:00") :month
+ {:start :exclusive}))))
(testing "inclusive end"
(is (= {:start (t/local-date-time "2019-11-01T00:00"), :end (t/local-date-time "2019-11-30T23:59:59.999")}
- (u.date/range (t/local-date-time "2019-11-18T00:00") :month {:end :inclusive}))))
+ (u.date/range time-config
+ (t/local-date-time "2019-11-18T00:00") :month
+ {:end :inclusive}))))
(testing ":day resolution + inclusive end"
(is (= {:start (t/local-date "2019-11-01"), :end (t/local-date "2019-11-30")}
- (u.date/range (t/local-date "2019-11-18") :month {:end :inclusive, :resolution :day}))))))
+ (u.date/range time-config
+ (t/local-date "2019-11-18") :month
+ {:end :inclusive, :resolution :day}))))))
(deftest ^:parallel comparison-range-test
(testing "Comparing MONTH"
(letfn [(comparison-range [comparison-type options]
- (u.date/comparison-range (t/local-date "2019-11-18") :month comparison-type (merge {:resolution :day} options)))]
+ (u.date/comparison-range time-config
+ (t/local-date "2019-11-18") :month comparison-type
+ (merge {:resolution :day} options)))]
(testing "Month = November"
(is (= {:start (t/local-date "2019-11-01"), :end (t/local-date "2019-12-01")}
(comparison-range := nil)))
@@ -435,7 +435,9 @@
(deftest ^:parallel comparison-range-test-2
(testing "Comparing DAY"
(letfn [(comparison-range [comparison-type options]
- (u.date/comparison-range (t/local-date-time "2019-11-18T12:00") :day comparison-type (merge {:resolution :minute} options)))]
+ (u.date/comparison-range time-config
+ (t/local-date-time "2019-11-18T12:00") :day comparison-type
+ (merge {:resolution :minute} options)))]
(testing "Day = November 18th"
(is (= {:start (t/local-date-time "2019-11-18T00:00"), :end (t/local-date-time "2019-11-19T00:00")}
(comparison-range := nil)))
@@ -470,21 +472,22 @@
(is (= {:start (t/local-date-time "2019-11-17T23:59")}
(comparison-range :>= {:start :exclusive}))))))))
-(deftest comparison-range-start-of-week-test
- (testing "`comparison-range` for week should respect the `start-of-week` Setting (#14294)"
- (doseq [[first-day-of-week expected] {"sunday" {:start #t "2021-02-21", :end #t "2021-02-27"}
- "monday" {:start #t "2021-02-22", :end #t "2021-02-28"}
- "tuesday" {:start #t "2021-02-23", :end #t "2021-03-01"}
- "wednesday" {:start #t "2021-02-17", :end #t "2021-02-23"}
- "thursday" {:start #t "2021-02-18", :end #t "2021-02-24"}
- "friday" {:start #t "2021-02-19", :end #t "2021-02-25"}
- "saturday" {:start #t "2021-02-20", :end #t "2021-02-26"}}]
- (mt/with-temporary-setting-values [start-of-week first-day-of-week]
- (let [t #t "2021-02-23"]
- (is (= expected
- (merge
- (u.date/comparison-range t :week :>= {:resolution :day})
- (u.date/comparison-range t :week :<= {:resolution :day, :end :inclusive})))))))))
+(deftest ^:parallel comparison-range-start-of-week-test
+ (testing "`comparison-range` for week should respect the supplied `:start-of-week` (#14294)"
+ (doseq [[first-day-of-week expected] {:sunday {:start #t "2021-02-21", :end #t "2021-02-27"}
+ :monday {:start #t "2021-02-22", :end #t "2021-02-28"}
+ :tuesday {:start #t "2021-02-23", :end #t "2021-03-01"}
+ :wednesday {:start #t "2021-02-17", :end #t "2021-02-23"}
+ :thursday {:start #t "2021-02-18", :end #t "2021-02-24"}
+ :friday {:start #t "2021-02-19", :end #t "2021-02-25"}
+ :saturday {:start #t "2021-02-20", :end #t "2021-02-26"}}
+ :let [t #t "2021-02-23"
+ time-config {:start-of-week first-day-of-week}
+ options {:resolution :day}]]
+ (is (= expected
+ (merge
+ (u.date/comparison-range time-config t :week :>= options)
+ (u.date/comparison-range time-config t :week :<= (assoc options :end :inclusive))))))))
(deftest ^:parallel period-duration-test
(testing "Creating a period duration from a string"
diff --git a/test/metabase/util/formatting/date_test.cljc b/test/metabase/util/formatting/date_test.cljc
index 48589077560..599296d160e 100644
--- a/test/metabase/util/formatting/date_test.cljc
+++ b/test/metabase/util/formatting/date_test.cljc
@@ -15,9 +15,21 @@
(def ^:private locale
#?(:cljs nil :clj (Locale. "en")))
+(def ^:private time-config {:start-of-week :sunday})
+
+(defn- format-for-parameter [value options]
+ (date/format-for-parameter time-config value options))
+
+(defn- format-range-with-unit [value options]
+ (date/format-range-with-unit time-config value options))
+
+(defn- format-datetime-with-unit [value options]
+ (date/format-datetime-with-unit time-config value options))
+
(deftest ^:parallel format-for-parameter-test
(testing "some units have custom formatting"
- (are [exp date unit] (= exp (date/format-for-parameter (u.time/coerce-to-timestamp date) {:unit unit}))
+ (are [exp date unit] (= exp (format-for-parameter (u.time/coerce-to-timestamp date)
+ {:unit unit}))
;; Years
"2022-01-01~2022-12-31" "2022-12-19T12:03:19" "year"
;; Months
@@ -36,9 +48,8 @@
(deftest ^:parallel format-for-parameter-test-2
(testing "other units are treated as days or day ranges"
- (are [exp date unit] (= exp (date/format-for-parameter (u.time/coerce-to-timestamp date)
- {:unit unit
- :locale locale}))
+ (are [exp date unit] (= exp (format-for-parameter (u.time/coerce-to-timestamp date)
+ {:unit unit, :locale locale}))
;; Hour and minute are treated as days.
"2022-12-19" "2022-12-19T12:03:19" "hour"
"2022-12-19" "2022-12-19T00:03:19" "hour"
@@ -52,13 +63,13 @@
(deftest ^:parallel format-range-with-unit-test
(letfn [(week-of [d]
- (date/format-range-with-unit d {:unit "week"
- :compact true
- :locale locale}))]
+ (format-range-with-unit d {:unit "week"
+ :compact true
+ :locale locale}))]
(testing "full form (M d, Y - M d Y)"
(testing "when not abbreviated"
(is (= (str "November 1, 2022" date/range-separator "November 30, 2022")
- (date/format-range-with-unit "2022-11-16T11:19:04" {:unit "month"}))))
+ (format-range-with-unit "2022-11-16T11:19:04" {:unit "month"}))))
(testing "in different years, even with :compact true"
(is (= (str "Dec 29, 2019" date/range-separator "Jan 4, 2020")
(week-of "2019-12-31T11:19:04")))))
@@ -67,13 +78,19 @@
(week-of "2022-08-31T11:19:04"))))
(testing "shared month and year (M d - d, Y)"
(is (= (str "Dec 11" date/range-separator "17, 2022")
- (week-of "2022-12-14T11:19:04"))))))
+ (week-of "2022-12-14T11:19:04"))))
+ (testing "uses the configured start of week"
+ (is (= (str "Dec 12" date/range-separator "18, 2022")
+ (date/format-range-with-unit
+ {:start-of-week :monday}
+ "2022-12-14T11:19:04"
+ {:unit "week", :compact true, :locale locale}))))))
(deftest ^:parallel format-datetime-with-unit-test-1a1
(testing "special cases"
(testing "is-exclude"
(testing "for hour-of-day renders only the hour"
- (are [exp date] (= exp (date/format-datetime-with-unit date {:unit "hour-of-day" :is-exclude true}))
+ (are [exp date] (= exp (format-datetime-with-unit date {:unit "hour-of-day" :is-exclude true}))
"11 AM" "2022-11-20T11:19:04"
"3 PM" "2022-11-20T15:19:04"
"12 AM" "2022-11-20T00:19:04"
@@ -84,7 +101,7 @@
(testing "is-exclude"
(testing "for day-of-week renders eg. Monday"
(testing "from ISO date strings"
- (are [exp date] (= exp (date/format-datetime-with-unit date {:unit "day-of-week" :is-exclude true}))
+ (are [exp date] (= exp (format-datetime-with-unit date {:unit "day-of-week" :is-exclude true}))
"Sunday" "2022-12-18T11:19:04"
"Monday" "2022-12-19T11:19:04"
"Tuesday" "2022-12-20T11:19:04"
@@ -98,7 +115,7 @@
(testing "is-exclude"
(testing "for day-of-week renders eg. Monday"
(testing "from weekday numbers"
- (are [exp date] (= exp (date/format-datetime-with-unit date {:unit "day-of-week" :is-exclude true}))
+ (are [exp date] (= exp (format-datetime-with-unit date {:unit "day-of-week" :is-exclude true}))
"Saturday" 0
"Sunday" 1
"Monday" 2
@@ -114,7 +131,7 @@
(testing "is-exclude"
(testing "for day-of-week renders eg. Monday"
(testing "from short weekday names"
- (are [exp date] (= exp (date/format-datetime-with-unit date {:unit "day-of-week" :is-exclude true}))
+ (are [exp date] (= exp (format-datetime-with-unit date {:unit "day-of-week" :is-exclude true}))
"Sunday" "Sun"
"Monday" "Mon"
"Tuesday" "Tue"
@@ -129,7 +146,7 @@
(testing "is-exclude"
(testing "for day-of-week renders eg. Monday"
(testing "from full weekday names"
- (are [exp date] (= exp (date/format-datetime-with-unit date {:unit "day-of-week" :is-exclude true}))
+ (are [exp date] (= exp (format-datetime-with-unit date {:unit "day-of-week" :is-exclude true}))
"Sunday" "Sunday"
"Monday" "Monday"
"Tuesday" "Tuesday"
@@ -144,32 +161,32 @@
(testing "weeks in tooltips (condensed ranges, not abbreviated)"
(testing "that fit in one month are formatted December 18 - 24, 2022"
(is (= (str "December 18" date/range-separator "24, 2022")
- (date/format-datetime-with-unit "2022-12-20T11:19:04" {:unit "week"
- :type "tooltip"
- :locale locale})))))))
+ (format-datetime-with-unit "2022-12-20T11:19:04" {:unit "week"
+ :type "tooltip"
+ :locale locale})))))))
(deftest ^:parallel format-datetime-with-unit-test-1b2
(testing "special cases"
(testing "weeks in tooltips (condensed ranges, not abbreviated)"
(testing "that span months are formatted November 27 - December 3, 2022"
(is (= (str "November 27" date/range-separator "December 3, 2022")
- (date/format-datetime-with-unit "2022-11-30T11:19:04" {:unit "week"
- :type "tooltip"
- :locale locale})))))))
+ (format-datetime-with-unit "2022-11-30T11:19:04" {:unit "week"
+ :type "tooltip"
+ :locale locale})))))))
(deftest ^:parallel format-datetime-with-unit-test-1b3
(testing "special cases"
(testing "weeks in tooltips (condensed ranges, not abbreviated)"
(testing "that span years are formatted December 29, 2019 - January 4, 2020"
(is (= (str "December 29, 2019" date/range-separator "January 4, 2020")
- (date/format-datetime-with-unit "2019-12-30T11:19:04" {:unit "week"
- :type "tooltip"
- :locale locale})))))))
+ (format-datetime-with-unit "2019-12-30T11:19:04" {:unit "week"
+ :type "tooltip"
+ :locale locale})))))))
(deftest ^:parallel format-datetime-with-unit-test-2a
(testing "general dates"
(testing "with default style, unit-based"
- (are [exp unit] (= exp (date/format-datetime-with-unit "2022-12-07" {:unit unit}))
+ (are [exp unit] (= exp (format-datetime-with-unit "2022-12-07" {:unit unit}))
"2022" "year"
"Q4 - 2022" "quarter"
"Q4" "quarter-of-year"
@@ -184,9 +201,9 @@
(deftest ^:parallel format-datetime-with-unit-test-2b
(testing "general dates"
(testing "default formats for each date style"
- (are [exp style unit] (= exp (date/format-datetime-with-unit "2022-04-07T19:08:45.123" {:unit unit
- :date-style style
- :time-enabled false}))
+ (are [exp style unit] (= exp (format-datetime-with-unit "2022-04-07T19:08:45.123" {:unit unit
+ :date-style style
+ :time-enabled false}))
"4/7/2022" "M/D/YYYY" "day"
"7/4/2022" "D/M/YYYY" "hour"
"2022/4/7" "YYYY/M/D" "day"
@@ -197,9 +214,9 @@
(deftest ^:parallel format-datetime-with-unit-test-2c1
(testing "general dates"
(testing "unit overrides for various styles"
- (are [exp style unit] (= exp (date/format-datetime-with-unit "2022-04-07T19:08:45.123" {:unit unit
- :date-style style
- :time-enabled false}))
+ (are [exp style unit] (= exp (format-datetime-with-unit "2022-04-07T19:08:45.123" {:unit unit
+ :date-style style
+ :time-enabled false}))
"4/2022" "M/D/YYYY" "month"
"4/2022" "D/M/YYYY" "month"
"2022/4" "YYYY/M/D" "month"
@@ -213,9 +230,9 @@
(testing "general dates"
(testing "unit overrides for various styles"
(testing "use short forms in compact mode"
- (are [exp style unit] (= exp (date/format-datetime-with-unit "2022-04-07T19:08:45.123" {:unit unit
- :time-enabled false
- :compact true}))
+ (are [exp style unit] (= exp (format-datetime-with-unit "2022-04-07T19:08:45.123" {:unit unit
+ :time-enabled false
+ :compact true}))
"Apr, 2022" "MMMM D, YYYY" "month"
"Apr, 2022" "D MMMM, YYYY" "month"
"Apr 7, 2022" "dddd, MMMM D, YYYY" "week" ;; TODO is this actually right? check with existing code
@@ -225,11 +242,11 @@
(testing "general dates"
(testing "custom date separators"
(are [exp style separator unit]
- (= exp (date/format-datetime-with-unit "2022-04-07T19:08:45.123" {:unit unit
- :time-enabled false
- :date-style style
- :date-separator separator
- :compact true}))
+ (= exp (format-datetime-with-unit "2022-04-07T19:08:45.123" {:unit unit
+ :time-enabled false
+ :date-style style
+ :date-separator separator
+ :compact true}))
"Apr, 2022" "MMMM D, YYYY" "/" "month"
"Apr 7, 2022" "MMMM D, YYYY" "/" "day"
"Apr, 2022" "MMMM D, YYYY" "-" "month"
@@ -247,14 +264,14 @@
(testing "general dates and times"
(testing "with both styles left as defaults and a sub-day :unit"
(is (= "April 7, 2022, 7:08 PM"
- (date/format-datetime-with-unit "2022-04-07T19:08:45.123" {:unit "minute"}))))))
+ (format-datetime-with-unit "2022-04-07T19:08:45.123" {:unit "minute"}))))))
(deftest ^:parallel format-datetime-with-unit-test-3b
(testing "general dates and times"
(testing "setting the time style"
(are [exp style enabled]
- (= exp (date/format-datetime-with-unit "2022-04-07T19:08:45.123" {:time-enabled enabled
- :time-style style}))
+ (= exp (format-datetime-with-unit "2022-04-07T19:08:45.123" {:time-enabled enabled
+ :time-style style}))
"April 7, 2022, 7:08 PM" "h:mm A" "minutes"
"April 7, 2022, 19:08" "HH:mm" "minutes"
"April 7, 2022, 7:08:45 PM" "h:mm A" "seconds"
@@ -266,9 +283,9 @@
(testing "general dates and times"
(testing "setting both styles"
(are [exp date-style time-style enabled]
- (= exp (date/format-datetime-with-unit "2022-04-07T19:08:45.123" {:date-style date-style
- :time-style time-style
- :time-enabled enabled}))
+ (= exp (format-datetime-with-unit "2022-04-07T19:08:45.123" {:date-style date-style
+ :time-style time-style
+ :time-enabled enabled}))
"April 7, 2022, 7:08 PM" "MMMM D, YYYY" "h:mm A" "minutes"
"April 7, 2022, 19:08" "MMMM D, YYYY" "HH:mm" "minutes"
"4/7/2022, 7:08 PM" "M/D/YYYY" "h:mm A" "minutes"
@@ -281,15 +298,15 @@
(testing "setting a date style and unit that overrides, plus a time"
;; This is a weird thing to do, but it should work correctly.
(is (= "4/2022, 19:08:45.123"
- (date/format-datetime-with-unit "2022-04-07T19:08:45.123" {:date-style "M/D/YYYY"
- :time-style "HH:mm"
- :time-enabled "milliseconds"
- :unit "month"}))))))
+ (format-datetime-with-unit "2022-04-07T19:08:45.123" {:date-style "M/D/YYYY"
+ :time-style "HH:mm"
+ :time-enabled "milliseconds"
+ :unit "month"}))))))
(deftest ^:parallel format-datetime-with-unit-test-4
(testing "bare times"
- (are [exp arg unit time-style] (= exp (date/format-datetime-with-unit arg {:unit unit
- :time-style time-style}))
+ (are [exp arg unit time-style] (= exp (format-datetime-with-unit arg {:unit unit
+ :time-style time-style}))
"7:00 AM" 7 "hour-of-day" "h:mm A"
"12:00 PM" 12 "hour-of-day" "h:mm A"
"7:00 PM" 19 "hour-of-day" "h:mm A"
@@ -303,11 +320,11 @@
(testing "prepending weekdays"
(testing "works on any date format with days"
(are [exp date-style time-style unit]
- (= exp (date/format-datetime-with-unit "2022-04-07T19:08:45.123" {:date-style date-style
- :time-style time-style
- :time-enabled (when time-style "minutes")
- :unit unit
- :weekday-enabled true}))
+ (= exp (format-datetime-with-unit "2022-04-07T19:08:45.123" {:date-style date-style
+ :time-style time-style
+ :time-enabled (when time-style "minutes")
+ :unit unit
+ :weekday-enabled true}))
"Thu, April 7, 2022, 7:08 PM" "MMMM D, YYYY" "h:mm A" "minute"
"Thu, April 7, 2022, 19:08" "MMMM D, YYYY" "HH:mm" "minute"
"Thu, 4/7/2022, 7:08 PM" "M/D/YYYY" "h:mm A" "minute"
@@ -320,9 +337,9 @@
(testing "prepending weekdays"
(testing "is skipped if the unit does not have day resolution"
(are [exp date-style unit]
- (= exp (date/format-datetime-with-unit "2022-04-07T19:08:45.123" {:date-style date-style
- :unit unit
- :weekday-enabled true}))
+ (= exp (format-datetime-with-unit "2022-04-07T19:08:45.123" {:date-style date-style
+ :unit unit
+ :weekday-enabled true}))
"April, 2022" "MMMM D, YYYY" "month"
"Q2 - 2022" "MMMM D, YYYY" "quarter"
"2022" "MMMM D, YYYY" "year"))))
@@ -334,9 +351,9 @@
(reset! @#'formatters/options->formatter-cache {})
(log.capture/with-log-messages-for-level [messages :warn]
(reset! result
- (date/format-datetime-with-unit "2022-04-07T19:08:45.123" {:unit :asdf
- :date-style "asdf"
- :time-enabled false}))
+ (format-datetime-with-unit "2022-04-07T19:08:45.123" {:unit :asdf
+ :date-style "asdf"
+ :time-enabled false}))
(is (=? [{:level :warn, :message "Unrecognized date style {:date-style asdf, :unit :asdf}"}]
(messages))))
(is (= "2022-04-07T19:08:45" @result)))))
diff --git a/test/metabase/util/time_test.cljc b/test/metabase/util/time_test.cljc
index ea315039de7..9b3313d296a 100644
--- a/test/metabase/util/time_test.cljc
+++ b/test/metabase/util/time_test.cljc
@@ -60,10 +60,19 @@
"For consistency of testing we use an arbitrary time as \"now\"."
"2022-12-14T13:18:43")
+(def ^:private time-config {:start-of-week :sunday})
+
+(defn- format-unit
+ ([value unit]
+ (shared.ut/format-unit time-config value unit))
+ ([value unit locale]
+ (shared.ut/format-unit time-config value unit {:locale locale})))
+
(deftest string->timestamp-test
(testing "numbers are parsed into datetimes based on the unit"
(with-redefs [internal/now (fn [] (from test-epoch))]
- (are [exp-str input unit] (same? (from exp-str) (shared.ut/coerce-to-timestamp input {:unit unit}))
+ (are [exp-str input unit] (same? (from exp-str)
+ (shared.ut/coerce-to-timestamp input (assoc time-config :unit unit)))
"2022-12-14T13:00:00" 0 "minute-of-hour"
"2022-12-14T13:12:00" 12 "minute-of-hour"
"2022-12-14T13:59:00" 59 "minute-of-hour"
@@ -128,7 +137,9 @@
(testing "strings"
(testing "with unit=day-of-week get parsed as eg. Mon"
(with-redefs [internal/now (fn [] (from test-epoch))]
- (are [exp-str input] (same? (from exp-str) (shared.ut/coerce-to-timestamp input {:unit "day-of-week"}))
+ (are [exp-str input] (same? (from exp-str)
+ (shared.ut/coerce-to-timestamp input
+ (assoc time-config :unit "day-of-week")))
;; 2022-12-14 (the test epoch) is a Wednesday.
"2022-12-12T00:00:00" "Mon"
"2022-12-13T00:00:00" "Tue"
@@ -200,11 +211,24 @@
["2019-12-29T00:00:00Z" "2020-01-04T23:59:59.999Z" "2019-12-30T00:00:00" "week"]
["2019-12-29T00:00:00Z" "2020-01-04T23:59:59.999Z" "2020-01-02T00:00:00" "week"]]
:let [[from to] (shared.ut/to-range (shared.ut/coerce-to-timestamp date nil)
- {:unit unit
- :locale #?(:cljs nil :clj (Locale/getDefault))})]]
+ (assoc time-config
+ :unit unit
+ :locale #?(:cljs nil :clj (Locale/getDefault))))]]
(is (same? (from-zulu exp-from) from) "start dates should be the same")
(is (same? (from-zulu exp-to) to) "end dates should be the same")))
+(deftest to-range-string-week-unit-respects-week-config-test
+ (let [[from to] (shared.ut/to-range (shared.ut/coerce-to-timestamp "2022-08-24T00:00:00" nil)
+ {:start-of-week :monday, :unit "week"})]
+ (is (same? (from-zulu "2022-08-22T00:00:00Z") from))
+ (is (same? (from-zulu "2022-08-28T23:59:59.999Z") to))))
+
+(deftest quarter-to-range-does-not-require-week-config-test
+ (let [[from to] (shared.ut/to-range (shared.ut/coerce-to-timestamp "2022-08-19T00:00:00" nil)
+ {:unit :quarter})]
+ (is (same? (from-zulu "2022-07-01T00:00:00Z") from))
+ (is (same? (from-zulu "2022-09-30T23:59:59.999Z") to))))
+
(defn- time-from [s]
#?(:cljs (dayjs s #js ["HH:mm:ss.SSS" "HH:mm:ss" "HH:mm"])
:clj (t/local-time s)))
@@ -235,7 +259,7 @@
(shared.ut/coerce-to-time 12)))))
(deftest format-string-test
- (are [exp u] (= exp (shared.ut/format-unit "2023-02-08" u))
+ (are [exp u] (= exp (format-unit "2023-02-08" u))
"Wednesday" :day-of-week
"Feb" :month-of-year
"8" :day-of-month
@@ -243,7 +267,7 @@
"6" :week-of-year
"Q1" :quarter-of-year
"Feb 8, 2023" nil)
- (are [exp u] (= exp (shared.ut/format-unit "2023-02-08" u "fr"))
+ (are [exp u] (= exp (format-unit "2023-02-08" u "fr"))
"mercredi" :day-of-week
"févr." :month-of-year
"8" :day-of-month
@@ -252,7 +276,7 @@
"Q1" :quarter-of-year
"Feb 8, 2023" nil) ;; no locale for default formats
- (are [exp u] (= exp (shared.ut/format-unit (from-local-date "2023-02-08") u))
+ (are [exp u] (= exp (format-unit (from-local-date "2023-02-08") u))
"Wednesday" :day-of-week
"Feb" :month-of-year
"8" :day-of-month
@@ -260,7 +284,7 @@
"6" :week-of-year
"Q1" :quarter-of-year
"Feb 8, 2023" nil)
- (are [exp u] (= exp (shared.ut/format-unit (from-local-date "2023-02-08") u "fr"))
+ (are [exp u] (= exp (format-unit (from-local-date "2023-02-08") u "fr"))
"mercredi" :day-of-week
"févr." :month-of-year
"8" :day-of-month
@@ -268,20 +292,21 @@
"6" :week-of-year
"Q1" :quarter-of-year
"Feb 8, 2023" nil)
- (is (= "12:00 PM" (shared.ut/format-unit "12:00:00.000" nil)))
- (is (= "12:00 PM" (shared.ut/format-unit (from-local-time "12:00:00.000") nil)))
- (is (= "Oct 3, 2023, 1:30 PM" (shared.ut/format-unit "2023-10-03T13:30:00" nil)))
- (is (= "Oct 3, 2023, 1:30 PM" (shared.ut/format-unit (from-local "2023-10-03T13:30:00") nil)))
- (is (= "30" (shared.ut/format-unit "2023-10-03T13:30:00" :minute-of-hour)))
- (is (= "1 PM" (shared.ut/format-unit "2023-10-03T13:30:00" :hour-of-day)))
- (is (= "30" (shared.ut/format-unit 30 :minute-of-hour)))
- (is (= "1 PM" (shared.ut/format-unit 13 :hour-of-day)))
- (is (= "12 AM" (shared.ut/format-unit 0 :hour-of-day))))
+ (is (= "12:00 PM" (format-unit "12:00:00.000" nil)))
+ (is (= "12:00 PM" (format-unit (from-local-time "12:00:00.000") nil)))
+ (is (= "Oct 3, 2023, 1:30 PM" (format-unit "2023-10-03T13:30:00" nil)))
+ (is (= "Oct 3, 2023, 1:30 PM" (format-unit (from-local "2023-10-03T13:30:00") nil)))
+ (is (= "30" (format-unit "2023-10-03T13:30:00" :minute-of-hour)))
+ (is (= "1 PM" (format-unit "2023-10-03T13:30:00" :hour-of-day)))
+ (is (= "30" (format-unit 30 :minute-of-hour)))
+ (is (= "1 PM" (format-unit 13 :hour-of-day)))
+ (is (= "12 AM" (format-unit 0 :hour-of-day)))
+ (is (= "1" (format-unit 1 :week-of-year))))
(deftest parse-unit-test
(are [exp input unit-in unit-out locale-in locale-out]
(= exp (-> (shared.ut/parse-unit input unit-in locale-in)
- (shared.ut/format-unit unit-out locale-out)))
+ (format-unit unit-out locale-out)))
"Wednesday" "Wed" :day-of-week-abbrev :day-of-week "en" "en"
"lundi" "Mon" :day-of-week-abbrev :day-of-week "en" "fr"
@@ -307,8 +332,12 @@
(deftest format-relative-date-range
(with-redefs [internal/now (fn [] (from test-epoch))]
- (are [exp n unit include-current] (= exp (shared.ut/format-relative-date-range n unit nil nil {:include-current include-current}))
+ (are [exp n unit include-current] (= exp (shared.ut/format-relative-date-range
+ {:start-of-week :sunday}
+ n unit nil nil
+ {:include-current include-current}))
"Jan 1 – Dec 31, 2022" 0 :year true
+ "Jan 1 – Dec 31, 2022" 0 :year false
"Jan 1, 2022 – Dec 31, 2023" 1 :year true
"Jan 1 – Dec 31, 2023" 1 :year false
@@ -372,7 +401,7 @@
(deftest ^:parallel truncate-datetime-test
(are [unit expected] (= expected
- (shared.ut/truncate "2024-02-02T12:02:12.345" unit))
+ (shared.ut/truncate time-config "2024-02-02T12:02:12.345" unit))
:millisecond "2024-02-02T12:02:12.345"
:second "2024-02-02T12:02:12"
:minute "2024-02-02T12:02"
@@ -383,9 +412,13 @@
:quarter "2024-01-01T00:00"
:year "2024-01-01T00:00"))
+(deftest ^:parallel truncate-string-week-unit-respects-week-config-test
+ (is (= "2024-01-29T00:00"
+ (shared.ut/truncate {:start-of-week :monday} "2024-02-02T12:02:12.345" "week"))))
+
(deftest ^:parallel truncate-date-test
(are [unit expected] (= expected
- (shared.ut/truncate "2024-02-02" unit))
+ (shared.ut/truncate time-config "2024-02-02" unit))
:day "2024-02-02"
:week "2024-01-28"
:month "2024-02-01"
@@ -394,7 +427,7 @@
(deftest ^:parallel truncate-time-test
(are [unit expected] (= expected
- (shared.ut/truncate "12:02:12.345" unit))
+ (shared.ut/truncate time-config "12:02:12.345" unit))
:millisecond "12:02:12.345"
:second "12:02:12"
:minute "12:02"
@@ -495,7 +528,7 @@
(deftest ^:parallel extract-test
(let [t (shared.ut/local-date-time 2024 12 06 10 20 30 500)]
- (are [unit expected] (= expected (shared.ut/extract t unit))
+ (are [unit expected] (= expected (shared.ut/extract time-config t unit))
:second-of-minute 30
:minute-of-hour 20
:day-of-week 6
diff --git a/test/metabase/xrays/automagic_dashboards/names_test.clj b/test/metabase/xrays/automagic_dashboards/names_test.clj
index b6aa36b0bdd..87a58dd5215 100644
--- a/test/metabase/xrays/automagic_dashboards/names_test.clj
+++ b/test/metabase/xrays/automagic_dashboards/names_test.clj
@@ -15,46 +15,51 @@
;;; ------------------- Datetime humanization (for chart and dashboard titles) -------------------
-(deftest ^:parallel temporal-humanization-test
+(defn- assert-temporal-humanization! []
(testing "Timestamp handling"
- (let [dt #t "1990-09-09T12:30"
- t-str "1990-09-09T12:30:00"]
+ (let [dt #t "1990-09-09T12:30"
+ t-str "1990-09-09T12:30:00"
+ options {:start-of-week :sunday}]
(doseq [[unit expected] {:minute (tru "at {0}" (t/format "h:mm a, MMMM d, YYYY" dt))
:hour (tru "at {0}" (t/format "h a, MMMM d, YYYY" dt))
:day (tru "on {0}" (t/format "MMMM d, YYYY" dt))
:week (tru "in {0} week - {1}"
- (#'names/pluralize (u.date/extract dt :week-of-year))
- (str (u.date/extract dt :year)))
+ (#'names/pluralize (u.date/extract options dt :week-of-year))
+ (str (u.date/extract options dt :year)))
:month (tru "in {0}" (t/format "MMMM YYYY" dt))
:quarter (tru "in Q{0} - {1}"
- (u.date/extract dt :quarter-of-year)
- (str (u.date/extract dt :year)))
+ (u.date/extract options dt :quarter-of-year)
+ (str (u.date/extract options dt :year)))
:year (t/format "YYYY" dt)
:day-of-week (t/format "EEEE" dt)
:hour-of-day (tru "at {0}" (t/format "h a" dt))
:month-of-year (t/format "MMMM" dt)
- :quarter-of-year (tru "Q{0}" (u.date/extract dt :quarter-of-year))
- :minute-of-hour (u.date/extract dt :minute-of-hour)
- :day-of-month (u.date/extract dt :day-of-month)
- :week-of-year (u.date/extract dt :week-of-year)}]
+ :quarter-of-year (tru "Q{0}" (u.date/extract options dt :quarter-of-year))
+ :minute-of-hour (u.date/extract options dt :minute-of-hour)
+ :day-of-month (u.date/extract options dt :day-of-month)
+ :week-of-year (u.date/extract options dt :week-of-year)}]
(testing (format "unit = %s" unit)
(is (= (str expected)
(str (#'names/humanize-datetime t-str unit)))))))))
-(deftest ^:parallel temporal-humanization-test-2
+(deftest temporal-humanization-test
+ (mt/with-temporary-setting-values [start-of-week :sunday]
+ (assert-temporal-humanization!)))
+
+(deftest temporal-humanization-test-2
(testing "Extracted unit handling"
- (is (= :sunday (#'u.date/start-of-week)) "adjust the test, it assumes Sunday as first day of the week")
- (let [t 3] ; t = 2 or t = 4 would also work
- (doseq [[unit expected] {:day-of-week (-> t dec t/day-of-week str/capitalize)
- :hour-of-day (str "at " t " AM")
- :month-of-year (-> t t/month str/capitalize)
- :quarter-of-year (str "Q" t)
- :minute-of-hour t
- :day-of-month t
- :week-of-year t}]
- (testing (format "unit = %s" unit)
- (is (= (str expected)
- (str (#'names/humanize-datetime t unit)))))))))
+ (mt/with-temporary-setting-values [start-of-week :sunday]
+ (let [t 3] ; t = 2 or t = 4 would also work
+ (doseq [[unit expected] {:day-of-week (-> t dec t/day-of-week str/capitalize)
+ :hour-of-day (str "at " t " AM")
+ :month-of-year (-> t t/month str/capitalize)
+ :quarter-of-year (str "Q" t)
+ :minute-of-hour t
+ :day-of-month t
+ :week-of-year t}]
+ (testing (format "unit = %s" unit)
+ (is (= (str expected)
+ (str (#'names/humanize-datetime t unit))))))))))
(deftest ^:parallel pluralize-test
(are [expected n] (= (str expected)