Compare commits

...

1928 Commits

Author SHA1 Message Date
Nicolò Pretto
7ca963d0eb hackathon: embedding sdk plugin 2024-03-07 09:20:41 +03:00
Denis Berezin
7eeae6f210 Working solution 2024-03-06 16:25:13 +03:00
Denis Berezin
cb53be1b17 Add api key env 2024-03-06 09:52:34 +03:00
Oisin Coveney
324dd8cf9a Add toggles + switchers for themes, parameters, and styling options 2024-03-01 18:51:43 +03:00
Oisin Coveney
bfb46008a9 remove location from SDK Dashboard 2024-03-01 12:45:00 +03:00
Oisin Coveney
2cb07d3734 Continue static dashboards 2024-02-28 19:43:03 +01:00
Oisin Coveney
3984950693 Continue moving location props out of dashboard components 2024-02-28 12:51:02 +01:00
Oisin Coveney
5e6b42b4ee Move types around on EmbedFrame 2024-02-27 18:52:32 +01:00
Oisin Coveney
e8813d5d09 Add really dirty version of dashboards 2024-02-27 18:16:30 +01:00
Oisin Coveney
1ed70d8c6b save progress on dashboard 2024-02-27 09:53:17 +01:00
Oisin Coveney
da41baa8c5 Formatting and make the style leak flag more useful 2024-02-23 12:38:39 +00:00
Oisin Coveney
ba5940934d Formatting 2024-02-22 12:23:42 +00:00
Oisin Coveney
27007c93ef Quick font adjustment 2024-02-22 10:55:06 +00:00
Oisin Coveney
2c8396318c Add style leak flag to indicate whether a font is leaky 2024-02-21 21:02:11 +00:00
Oisin Coveney
5b14bfa69a Add tailwind and modify app to show off a little more 2024-02-21 20:36:30 +00:00
Oisin Coveney
a03ffb1059 Ensure that public hooks are exposed 2024-02-21 13:39:34 +00:00
Oisin Coveney
1a16919b24 Remove apiUrl from EmbeddingContext 2024-02-21 11:16:34 +00:00
Oisin Coveney
10df8c09f3 Separate hooks and components into public and private folders 2024-02-21 11:04:32 +00:00
Oisin Coveney
a82d370f78 Remove log file from font util API 2024-02-21 10:17:02 +00:00
Oisin Coveney
2228762fa2 Add font selector component to host app and hook for getting and setting fonts within the EmbeddingContext 2024-02-20 18:55:51 +00:00
Oisin Coveney
c129197c6a Reconcile new auth loading, fonts, and config 2024-02-20 09:36:58 +00:00
Oisin Coveney
3502e49eb3 Hide JWT 2024-02-19 20:27:41 +00:00
Denis Berezin
6f37b13e85 Update for default settings 2024-02-15 00:57:25 +07:00
Denis Berezin
96a76bf8d0 Add dynamic api key / jwt usage based on env 2024-02-14 21:27:31 +07:00
Oisin Coveney
66aa4e7da3 Move backend folder to new repo and return files to their rightful place 2024-02-13 17:18:07 +01:00
Oisin Coveney
b7b7d56ab7 Add simple README and redux 2024-02-13 11:06:58 +01:00
Oisin Coveney
69700f56fd Add backend 2024-02-12 17:19:44 +01:00
Oisin Coveney
97d9792dda Add backend 2024-02-12 17:16:20 +01:00
Oisin Coveney
52771825f6 Add embedding check for auth/sso endpoint 2024-02-12 14:39:01 +01:00
Oisin Coveney
51d4b37074 Merge remote-tracking branch 'origin/master' into embedding-sdk-poc-denis 2024-02-12 13:13:42 +01:00
Mahatthana (Kelvin) Nomsawadi
19334990ce Fix custom destination to public dashboard not working on static embedding (#38647)
* Fix linking to public or embed resource on dashboards not working

* Update embedding test name to use a snazzier term

* Add tests
2024-02-12 11:26:38 +00:00
Chris Truter
48c4377775 Revert breaking change to the active-tables driver method (#38562) 2024-02-12 08:59:35 +00:00
Nick Fitzpatrick
c4115828c0 Don't lower dashboard/question title when there is no last edit info (#38629)
* don't lower dashboard title when there is no last edit info

* same with questions
2024-02-11 10:51:00 -04:00
Nick Fitzpatrick
0b06c1daee Usage insight links on questions and dashboards (#38573)
* adding links with hardcoded IDs

* add audit-info endpoint

* fix perms

* Fetching Dashboard IDs from the API

* e2e tests

* add BE tests

* kinda busted

* InstanceAnalyticsButton

* removing unused file

* Update enterprise/backend/src/metabase_enterprise/audit_app/api/user.clj

Co-authored-by: Noah Moss <32746338+noahmoss@users.noreply.github.com>

---------

Co-authored-by: Jerry Huang <jhuang37050@gmail.com>
Co-authored-by: Jerry Huang <34140255+qwef@users.noreply.github.com>
Co-authored-by: Noah Moss <32746338+noahmoss@users.noreply.github.com>
2024-02-11 10:50:38 -04:00
Ryan Laurie
0492a88b74 Connection Impersonation UI for Redshift (#38530)
* Connection Impersonation for Redshift

* redshift test based on the existing postgres one

* fix test

* fix test

* change impersonation UI for redshift

* copy/style updates

* update tests for new copy

* update copy

* lets tweak it even more

---------

Co-authored-by: Noah Moss <noahbmoss@gmail.com>
2024-02-11 02:24:26 +00:00
Jerry Huang
cc28ee6041 Add BE for routing billing status (#38153)
* add BE for billing status

* add BE for billing status

* fix whitespace

* fix english

* address comments

* fix whitespace

* fix comments

* update design

* update design

* add test

* consume json error

* address comments

* update url
2024-02-09 23:19:18 +00:00
Jeff Bruemmer
eeda0a8769 docs - json unfolding (#37827) 2024-02-09 17:01:54 -05:00
John Swanson
25d2e619fa Force reload in ensure-audit-db-installed! (#38626)
Sometimes analytics bits get removed by other tests (e.g. deleting all
cards, dashboards, users, etc.). When we run
`ensure-audit-db-installed!`, though, the checksum hasn't changed (since
the underlying analytics files didn't change), so we skip reloading the
data.

This sets `last-analytics-checksum` to `-1` (meaning: skip the checksum
and just load the analytics data) when running
`ensure-audit-db-installed!` in the tests that we've seen flake.
2024-02-09 14:58:24 -06:00
Jeff Bruemmer
b8890a844c remove in-line toc (#38630) 2024-02-09 15:38:38 -05:00
Braden Shepherdson
9e54403c88 [MLv2] Add drill-thru test coverage for nil-valued bins (#38472)
Zoom-in drills are not available for such bins, and this is now tested.

Also updates a few comments:
- Pivot drills work for **one** aggregation and 0 breakouts, not for 0.
- Legend clicks and pivot cell clicks look the same, so some tests
  cover both cases and this is now noted by comments.
2024-02-09 15:20:25 -05:00
bryan
a2e5557ab9 Analytics should load only when changed, via checksum (#38622)
* load analytics only when changed using a checksum

- over audit deserialization files

* update docstrings

* fix testing wording

* fix nil analytics-resource-dir

* in tests, when you delete the audit db, set the checksum back to 0

* add a comment

* WIP hashing ia content from inside a jar

* Do the unzip sooner, still hashes the file system

Co-authored-by: John Swanson <john.swanson@metabase.com>

* cleanup java-time -> java-time.api

---------

Co-authored-by: John Swanson <john.swanson@metabase.com>
2024-02-09 14:38:39 -05:00
Braden Shepherdson
692bb3e9c7 [MLv2] Add tests and fix a special case for fk-filter drills (#38297)
These were not adding an extra stage in order to filter queryies with
aggregations.

Progress towards #36253.
2024-02-09 14:03:49 -05:00
Ryan Laurie
bc5c478585 Allow appends from collection list (#38490)
* allow appends from collection list

* little type fixes

* fix existing unit tests

* possible one-character-catastrophe

* don't allow invalid form submission

* add appends test

* ❤️ enums

* design feedback

* update tests to match new design
2024-02-09 11:24:51 -07:00
Noah Moss
8cd5351263 Connection Impersonation for Redshift (#38475)
* Connection Impersonation for Redshift

* redshift test based on the existing postgres one

* fix test

* fix test
2024-02-09 12:58:12 -05:00
Oisin Coveney
d43863a2c1 Add snowplow events for embedding setup flow (#37617)
* Add snowplow events for embedding setup flow

* Fix dashboard model tests

* Fix dashboard tests

* Fix card tests

* Fix dashboard API tests

* Fix type error

* Implement analytics 2/7

1. public_link_copied
2. public_link_removed

* Fix snowplow schema enum

Removing null as we don't seem to put `null` in `enum`

* Complete the embed_flow snowplow schema

* Modify `initial_published_at` to not be overridden

* Implement analytics 4/7

1. public_link_copied
2. public_link_removed
3. public_embed_code_copied
4. static_embed_published
5. static_embed_unpublished

* Prevent accidental ESLint log in Cypress

* Differentiate `EmbeddingParametersSettings` from `EmbeddingParametersValues`

We were mixing the type before, as the former one are the type of the
setting values, not the actual values for the parameters.

* Fix dashboard and card types

* Fix `params` count for `static_embed_published` event

* fixup! Prevent accidental ESLint log in Cypress

* Fix ESlint from the result of upgrading ESLint package

* Fix Snowplow schema enum to include null

* Fully implement `static_embed_code_copied`

* Finish embed_flow snowplow 🎉

* Fix unit tests because markup change

* Fix E2E tests

* Fix E2E CI failure

Apparently using `.realClick()` on copy button could fail locally,
but pass on CI and vice-versa. I couldn't replicate this all the time.

I'm not sure why it would fail locally.

* Fix copy to clipboard not working on CI

* Improve test readability

* Remove extra test-id

* Fix refactor `*CodeOptionId`

* Restrict Snowplow schema

* Revert unnecessary change

* Apply Cal's suggestions for BE improvements

Co-authored-by: Cal Herries <39073188+calherries@users.noreply.github.com>

* Update src/metabase/util/embed.clj

Co-authored-by: Cal Herries <39073188+calherries@users.noreply.github.com>

* Fix backend linter error, hopefully.

---------

Co-authored-by: Mahatthana Nomsawadi <mahatthana.n@gmail.com>
Co-authored-by: Mahatthana (Kelvin) Nomsawadi <me@bboykelvin.dev>
Co-authored-by: Cal Herries <39073188+calherries@users.noreply.github.com>
Co-authored-by: Nicolò Pretto <info@npretto.com>
2024-02-09 12:57:46 -05:00
Noah Moss
48119c6025 Default enable-public-sharing to false for existing instances, and true for new ones (#38609)
* Default enable-public-sharing to false for existing instances, and true for new ones

* add rollback

* fix typo

* try to fix e2e test

* invert conditionals

* use derivedSettings instead
2024-02-09 12:57:20 -05:00
Chris Truter
b4e08f9b72 Scope find-root-test-failure! to same ns by default (#38600) 2024-02-09 19:33:29 +02:00
Jeff Bruemmer
e578f47b5a update command (#38371) 2024-02-09 10:52:53 -05:00
Jeff Bruemmer
8390b59f0b note on stopping when importing and exporting (#38415) 2024-02-09 10:52:06 -05:00
Oisin Coveney
d7a37b178c Move some files around and include the nodejs backend as a new folder 2024-02-09 16:44:50 +01:00
Luis Paolini
62d2bdcb90 Remove impersonation feature from Redshift driver (#38393) 2024-02-09 12:39:23 -03:00
Jesse Devaney
687b4033e4 Milestone 3A: Add fixed width behavior to dashboard filters (#38585)
* Migration adding 'width' to Dashboards

3 migrations:
 - 1st adding the width column with default value of 'fixed'
 - 2nd updating all existing dashboards to have width 'full', which corresponds to what the current behaviour is (will
 be the 'old' behaviour after the fixed-width project lands).
   - The rolloback here is necessary but we don't care what happens as the column will be dropped immediately in the
   next rollback anyway
 - 3rd sets the notNullableConstraint. DefaultNull is 'full' here, just in case there's an existing dashboard whose
 width value is not yet set from the 1st migration. Don't know how that could happen, but its here in case

* Dashboard PUT api endpoint accepts width changes and updates appdb

update-dashboard function now is aware of the :width key so those changes can end up in the transaction.

Also added a width test that asserts that the value's default is "fixed", it can be changed, eg. to "full", but cannot
be changed to other values.

* Add width to revision tests

* Fix dashboard revision tests.

:width key is now needed in some revision tests. As well we need a string communicating that the :width setting has
changed from 'full' to 'fixed' or vice-versa.

* Fix comments/remarks in migration to be accurate

* Attempt to fix default not working mysql/mariadb

* Set default in dashboard model

Signed-off-by: Adam James <adam.vermeer2@gmail.com>

* Revert default :width 'fixed' value.

* Explicitly add default value 'fixed' for MySQL/MariaDB

* dashboard fixed width FE implementation

* adjust popover shadow styling as the popover was blending in with the header

* adjust extra button popover offset

* add E2E to validate behavior

* add fixed width container to public dashboards

* fix public embedding not respecting dashboard width setting

* add test for public dashboards

* Fix embed test failures

* add fixed width to x-ray dashboards

* reduce code duplication

* move FixedWidthContainer into DashboardGridConnected

- We get the fixed-width w/o code duplication across AutomaticDashboardApp, PublicDashboard, and Dashboard

* update E2E tests to reflect actual intended behavior

* fix type errors

* tweak default width of cards to accomodate fixed width

* adjust tooltip button after merging changes from master

* fix bar chart test failure

* fix dashboard filters date test failure

- new ellipsis button in dashboard edit mode broke the test

* adjust test for new fixed width dashboards

* adjust test for new fixed width dashboards

* adjust test for new fixed width dashboards

* bump funnel default width

* adjust test for new fixed width dashboards

* Fix double overlay for LineAreaBarChart dash-cards

- No longer has an overlay that persists from editing mode to  viewing mode
- Adjust click-behavior tests to account for new grid-width. Old test relied on a dashcard being taller than they will now default to being. i.e. Move the chosen point/row to down an index.

* Merge FixedWidthContainer with dashboard grid div

* supress brush events while editing timeseries line charts on dashboard

* fix failing test

- test failed because I did not update this assertion based on previous changes

* fix broken link input in editing mode

* initial commit

* fix pointer events issue on text cards in edit mode

* update tests for new dash-card default sizes

* update tabs card moving test because of new default card sizes

* Include apply filters button in fixed width behavior

* tweak - do not need centering if full width

* fix apply filters button

* add fixed width behavior to dashboard filters in edit mode

* remove double border in edit mode

* evenly space parameters/filters in edit mode

* update test to account for moving location of edit mode filters

* Milestone 3B: Fix dashboard tabs and filters order on a public dashboard page (#38574)

* Add `className` prop to `DashboardTabs`

* Fix tab panel position in public dashboards

* adjust filters container padding

* Address feedback

---------

Co-authored-by: Jesse Devaney <22608765+JesseSDevaney@users.noreply.github.com>

---------

Signed-off-by: Adam James <adam.vermeer2@gmail.com>
Co-authored-by: Adam James <adam.vermeer2@gmail.com>
Co-authored-by: adam-james <21064735+adam-james-v@users.noreply.github.com>
Co-authored-by: Kyle Doherty <5248953+kdoh@users.noreply.github.com>
Co-authored-by: Aleksandr Lesnenko <alxnddr@gmail.com>
Co-authored-by: Anton Kulyk <kuliks.anton@gmail.com>
2024-02-09 10:34:28 -05:00
Noah Moss
5e8286c9cc v2 audit views and migrations (#38531)
* new audit views and migrations

* fix tests

* rename external users group to anonymous, handle api key users, and add query definition to query_execution table

* fix mysql user email field

* update yamls for 49

---------

Co-authored-by: Luiz Arakaki <luiz.arakaki@metabase.com>
2024-02-09 09:46:13 -05:00
John Swanson
7fad72cf47 Fix dispatch error in with-model-cleanup (#38584)
`with-model-cleanup` is called like so:

```
(with-model-cleanup [:model/User]
 ...)
```

This ends up calling:

```
(with-model-cleanup-additional-conditions model)
```

to get the additional conditions necessary when "cleaning up" the model.
This multimethod dispatched on `mi/model`.

But `(mi/model :model/User)` is `nil`. Instead, we *already have* the
model, not an instance of it, so we want to dispatch on that to
properly clean up after ourselves.
2024-02-09 09:41:58 -05:00
Cam Saul
c7f1ac93ee Redshift: drop session schema when test suite finishes (#38529)
* Redshift: drop session schema when test suite finishes [ci skip]

* Update Hawk version

* PR feedback

* Bump Hawk version

* Skip after-run for drivers that don't have test extensions

---------

Co-authored-by: Cal Herries <39073188+calherries@users.noreply.github.com>
2024-02-09 09:37:29 -05:00
Oleg Gromov
140a5322a8 Embedding + required params (#38395) 2024-02-09 14:04:40 +00:00
Thomas Schmidt
9d446f9cd8 Update devcontainer Dockerile (#38598) 2024-02-09 14:26:04 +01:00
Cal Herries
a250611d05 Remove handling MySQL <8 in table privileges test (#38546) 2024-02-09 14:10:29 +02:00
Cal Herries
8f16219718 Don't instrument any namespaces for mu.fn/fn in production (#38482) 2024-02-09 10:08:14 +00:00
Romeo Van Snick
9721ef80e1 Remove flaky timeout in DelayGroup test (#38593)
* Use greater than to assert timeout has elapsed

* Use fake timers to test delay group
2024-02-09 11:04:22 +01:00
Chris Truter
7eb7cd30b6 Various readability improvements around based_on_upload (#38507)
Co-authored-by: Callum Herries <calherries@gmail.com>
2024-02-09 08:03:03 +00:00
Chris Truter
425d570c15 Disable table-privileges feature for MySQL (#38552) 2024-02-09 08:01:52 +00:00
Cal Herries
118bcb166a Disable redshift support for uploads (#38583) 2024-02-09 08:17:24 +01:00
Braden Shepherdson
f47b0ae18a [MLv2] Use the provided column-ref for drills (#38047)
There are cases where the ref as provided is not the same as what a
fresh `(lib.ref/ref column)` would give. This seems mostly to affect
models, where the metadata leaks some of the underlying details like
joins.

Fixes #38034.
2024-02-09 02:10:23 +00:00
Kyle Doherty
5adf00bf5f add section icon and use in dashboard edit mode (#38575) 2024-02-08 17:51:33 -05:00
Kyle Doherty
d7c4fdd379 Update default sizes for new dash width (#38450)
* Migration adding 'width' to Dashboards

3 migrations:
 - 1st adding the width column with default value of 'fixed'
 - 2nd updating all existing dashboards to have width 'full', which corresponds to what the current behaviour is (will
 be the 'old' behaviour after the fixed-width project lands).
   - The rolloback here is necessary but we don't care what happens as the column will be dropped immediately in the
   next rollback anyway
 - 3rd sets the notNullableConstraint. DefaultNull is 'full' here, just in case there's an existing dashboard whose
 width value is not yet set from the 1st migration. Don't know how that could happen, but its here in case

* Dashboard PUT api endpoint accepts width changes and updates appdb

update-dashboard function now is aware of the :width key so those changes can end up in the transaction.

Also added a width test that asserts that the value's default is "fixed", it can be changed, eg. to "full", but cannot
be changed to other values.

* Add width to revision tests

* Fix dashboard revision tests.

:width key is now needed in some revision tests. As well we need a string communicating that the :width setting has
changed from 'full' to 'fixed' or vice-versa.

* Fix comments/remarks in migration to be accurate

* Attempt to fix default not working mysql/mariadb

* Set default in dashboard model

Signed-off-by: Adam James <adam.vermeer2@gmail.com>

* Revert default :width 'fixed' value.

* Explicitly add default value 'fixed' for MySQL/MariaDB

* dashboard fixed width FE implementation

* adjust popover shadow styling as the popover was blending in with the header

* adjust extra button popover offset

* add E2E to validate behavior

* add fixed width container to public dashboards

* fix public embedding not respecting dashboard width setting

* add test for public dashboards

* Fix embed test failures

* add fixed width to x-ray dashboards

* reduce code duplication

* move FixedWidthContainer into DashboardGridConnected

- We get the fixed-width w/o code duplication across AutomaticDashboardApp, PublicDashboard, and Dashboard

* update E2E tests to reflect actual intended behavior

* fix type errors

* tweak default width of cards to accomodate fixed width

* adjust tooltip button after merging changes from master

* fix bar chart test failure

* fix dashboard filters date test failure

- new ellipsis button in dashboard edit mode broke the test

* adjust test for new fixed width dashboards

* adjust test for new fixed width dashboards

* adjust test for new fixed width dashboards

* bump funnel default width

* adjust test for new fixed width dashboards

* Fix double overlay for LineAreaBarChart dash-cards

- No longer has an overlay that persists from editing mode to  viewing mode
- Adjust click-behavior tests to account for new grid-width. Old test relied on a dashcard being taller than they will now default to being. i.e. Move the chosen point/row to down an index.

* Merge FixedWidthContainer with dashboard grid div

* supress brush events while editing timeseries line charts on dashboard

* fix failing test

- test failed because I did not update this assertion based on previous changes

* fix broken link input in editing mode

* fix pointer events issue on text cards in edit mode

* update tests for new dash-card default sizes

* update tabs card moving test because of new default card sizes

---------

Signed-off-by: Adam James <adam.vermeer2@gmail.com>
Co-authored-by: Adam James <adam.vermeer2@gmail.com>
Co-authored-by: adam-james <21064735+adam-james-v@users.noreply.github.com>
Co-authored-by: Jesse Devaney <22608765+JesseSDevaney@users.noreply.github.com>
Co-authored-by: Aleksandr Lesnenko <alxnddr@gmail.com>
2024-02-08 15:29:16 -05:00
Anton Kulyk
83aeb32cf9 Fix card query endpoint usage on dashboards (#38547)
* Don't reload dashcards in edit mode

* Update and unskip repro

* Extend "duplicate tab" e2e test

* Fix implicit request body schema when fetching dashcard data

* Disable dashcard data refetching in edit mode

* Revert `Dashboard` useEffect changes

* Fix tests
2024-02-08 20:14:26 +00:00
Raphael Krut-Landau
0c96510fed Improve look of models in Browse data (#38518)
Co-authored-by: Kyle Doherty <5248953+kdoh@users.noreply.github.com>
Co-authored-by: Luiz Arakaki <luiz.arakaki@metabase.com>
2024-02-08 20:07:01 +00:00
Oisin Coveney
2a0f647c31 Add hooks for managing data and tokens 2024-02-08 20:39:48 +01:00
Nicolò Pretto
d88d32e5e0 Meet embedders - minimal version (#38520)
* refactor: prepare SettingsPage to have conditionally rendered steps (#38201)

* refactor: prepare SettingsPage to have conditionally rendered steps

* fix tests missing props

* Usage reason question (#38267)

* Invactive -> Inactive

* add question

* fix e2e test

* small refactor

* Update frontend/src/metabase/setup/components/UsageQuestionStep/UsageQuestionStep.tsx

Co-authored-by: Mahatthana (Kelvin) Nomsawadi <me@bboykelvin.dev>

---------

Co-authored-by: Mahatthana (Kelvin) Nomsawadi <me@bboykelvin.dev>

* Hide "Add your data" step for people interested in embedding (#38390)

* hide 'Add your data' step when user is interested in embedding

* add other test cases

* refactor: create selector

* address pr feedback

* adds minimal embed focused homepage (#38402)

* very minimal homepage

* fixed text color

* minimal e2e + actual logic that i forgot lol

* refactor the list to not have the numbers in the content

* rename util functions

* use button to have cursor when hovering + accessibility

* refactor: move the waitFor inside the submit step

* fix: make sure state is clean on multiple installs in a row

* test: check that the homepage persists reload + removed typos

* rename s to state

* moved util functions up to home/utils.ts

* adds key to avoid react warning

* refactor and tests for [meet embedders] (#38465)

* test: check all numbered steps during the setup flow

* refactor: introduce getSteps and start using the step name instead of a number to identify steps

* refactor: remove map of the steps, use step names directly

* refactor: getNextStep

* include 'hidden' steps in getSteps so that it won't mess up with analytics

* fix after rebase issue

* use full name instead of s, s -> step

* analytics for meet-embedders (#38521)

* refactor: extract schema version and onboarding version into constants

* remove old ga events

* trackUsageReasonSelected

* update trackStepSeen to send the correct index

* copy old schema for better diff

* adds new snowplow event for usage_reason step

* schema and e2e update for usage_reason_selected

* adds utm tag to the link in the minimal embed homepage

---------

Co-authored-by: Mahatthana (Kelvin) Nomsawadi <me@bboykelvin.dev>
2024-02-08 19:39:38 +00:00
Nemanja Glumac
98015a2d5f [QC] Remove unused methods from the StructuredQuery prototype (#38551) 2024-02-08 18:27:26 +01:00
bryan
9e1e8e8edd load analytics only when changed using a checksum (#38280)
* load analytics only when changed using a checksum

- over audit deserialization files

* update docstrings

* fix testing wording
2024-02-08 16:35:12 +00:00
Uladzimir Havenchyk
179a5d22df Avoid unnecessary re-renderings in because of getQuestions selector (#38548)
* Avoid unnecessary re-renderings in DashboardSharingEmbeddingModal

* Add deep equal selector

* drop underscore
2024-02-08 19:25:51 +03:00
Case Nelson
431764110a Fix time-interval against expressions (#38488)
* Fix time-interval against expressions

When simplifying time-interval filters, we forgot to place a
temporal-unit on expressions, which meant that the date-trunc used by
quarters had to match the date exactly rather than being in the interval
range.

* Update optimize temporal filters for expressions

There is a dependency with this middleware and mongo. Without
optimization mongo cannot compare the bucketed timestamps because
AFAICT mongo 4 doesn't have date truncation so we do so in clojure for
the compared literal but cannot do the lhs field/expression.
2024-02-08 09:20:04 -07:00
Nemanja Glumac
43c1895afa [QC] Remove setDatabase and setDatabaseID methods (#38550)
* Remove `setDatabaseID` method from the `StructuredQuery` prototype

* Remove `setDatabase` method from both Native and Structured queries
2024-02-08 16:58:53 +01:00
John Swanson
c141463ead bump toucan2 dependency (#38527)
pulling in https://github.com/camsaul/toucan2/pull/162 to fix #38516
2024-02-08 13:44:11 +00:00
Anton Kulyk
19ca99e1f4 Dashboard sections (#38463)
* Add `ADD_MANY_CARDS_TO_DASH` action

* Reuse `NewDashCardOpts` type

* Extract `DashboardCardLayoutAttrs` type

* Add basic `DashCardPlaceholder` viz

* Add section layouts

* Add `addSectionToDashboard` redux action

* Add `SectionLayoutPreview` component

* Add "Add section" button to dashboard header

* Allow placeholder cards in `replaceCard`

* Make heading cards transparent by default

* Fix layout fn usage

* Update mapping UI for placeholder cards

* Fix tooltips position

* Add `createMockPlaceholderDashboardCard`

* Test `replaceCard` works with placeholder cards

* Extract common `setup` from cards actions tests

* Add `createMockDashboardTab`

* Add unit tests for `addSectionToDashboard`

* Placeholder cards work for emails/pulses

Dashboards with placeholder cards now properly email rather than throwing an exception. Placeholder cards themselves are not sent as part of the email as they are empty.

* Merge remote-tracking branch 'origin/38209-dashboard-sections' into 38209-dashboard-sections

* Adding tests for placeholder cards and empty dashboards

* Fix parameter mappings UI

* Update section card sizes

* Clean up

* Add button label

* Add E2E test

* Revert

* Reorder

* Fix menu position

* Assert placeholder card doesn't have a button

* Fix menu tooltips

* Fixing unit tests

* Removed dangling code

* Fixing unit tests

* Remove virtual cards handling from `replaceCard`

---------

Co-authored-by: Mark Bastian <markbastian@gmail.com>
2024-02-08 12:06:18 +00:00
Alexander Solovyov
a5ce0ec528 serialization: snowplow events for export/import (#38487) 2024-02-08 10:18:13 +00:00
Nemanja Glumac
e7a12ce472 [QC] Remove isValid method from the StructuredQuery prototype (#38522) 2024-02-08 07:59:46 +00:00
Nemanja Glumac
1e560c397e [MLv2] Migrate usesSegment using new question filter from the GET /api/card endpoint (#38500)
* Rewrite `SegmentQuestions` to use new question filter

* Remove unused Question method

* Remove unused selector

* Convert `SegmentQuestions` to a functional component

* Remove unused underscore import

* Extract `getDescription()` to utils

* Fix unused vars

* Remove superfluous argument from `useQuestionListQuery` invocation
2024-02-08 07:50:01 +00:00
Nemanja Glumac
aa5dcd73fd [MLv2] Migrate usesMetric using new question filter from the GET /api/card endpoint (#38481)
* Rewrite `MetricQuestions` to use new question filter

* Remove unused selector

* Remove unused Question method

* Convert `MetricQuestions` to a functional component

* Expose new methods on the `Question` prototype

* Use new Question methods in `MetricQuestions`

* Fix implicit return

* Mark `metric` prop as required
2024-02-08 08:11:24 +01:00
Nemanja Glumac
707f14044b [QC] Remove hasAnyClauses method from StructuredQuery prototype (#38525)
* [QC] Remove `hasAnyClauses` method from the `StructuredQuery` prototype

* [QC] Remove `hasExpressions` method from the `StructuredQuery` prototype

* [QC] Remove `hasFilters` method from the `StructuredQuery` prototype

* [QC] Remove private `hasSorts` method from the `StructuredQuery` prototype

* [QC] Remove `hasLimit` method from the `StructuredQuery` prototype

* [QC] Remove private `indexOfField` method from the `StructuredQuery` prototype
2024-02-08 08:09:22 +01:00
Jesse Devaney
2c71bf0dcd Milestone 1: Default Dashboard Body to a Fixed Width (#38377)
* dashboard fixed width FE implementation

* adjust popover shadow styling as the popover was blending in with the header

* adjust extra button popover offset

* add E2E to validate behavior

* add fixed width container to public dashboards

* fix public embedding not respecting dashboard width setting

* add test for public dashboards

* Fix embed test failures

* add fixed width to x-ray dashboards

* reduce code duplication

* move FixedWidthContainer into DashboardGridConnected

- We get the fixed-width w/o code duplication across AutomaticDashboardApp, PublicDashboard, and Dashboard

* update E2E tests to reflect actual intended behavior

* fix type errors

* adjust tooltip button after merging changes from master

* fix bar chart test failure

* fix dashboard filters date test failure

- new ellipsis button in dashboard edit mode broke the test

* adjust test for new fixed width dashboards

* adjust test for new fixed width dashboards

* adjust test for new fixed width dashboards

* adjust test for new fixed width dashboards

* Fix double overlay for LineAreaBarChart dash-cards

- No longer has an overlay that persists from editing mode to  viewing mode
- Adjust click-behavior tests to account for new grid-width. Old test relied on a dashcard being taller than they will now default to being. i.e. Move the chosen point/row to down an index.

* Merge FixedWidthContainer with dashboard grid div

* supress brush events while editing timeseries line charts on dashboard

* fix failing test

- test failed because I did not update this assertion based on previous changes

---------

Co-authored-by: Aleksandr Lesnenko <alxnddr@gmail.com>
2024-02-08 04:44:52 +00:00
Mark Bastian
8dc7f17fd8 Update default Metabot model (#38491)
* Update default Metabot model

The default GPT-based Metabot model has been `"gpt-4"`. This model is no longer state of the art, has a limit of 8,192 tokens, and is priced at input: $0.03/ktoken and output: $0.06/ktoken.

`"gpt-4-turbo-preview"`, which points internally to `"gpt-4-0125-preview"` is the current state of the art, has a limit of 128,000 tokens, and is priced at input: $0.01/ktoken and output: $0.03/ktoken.

This should solve any issues of reasonable cases of token limit failures (e.g. [Metabot 2.0 failing when context length exceeded](https://github.com/metabase/metabase/issues/29932)) without needing to do any extra handling on the backend.

For more info on the models, token limits, and pricing, see:
- [OpenAI model docs](https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo)
- [OpenAI pricing](https://openai.com/pricing)

* whitespace

* Removing irrelevant settings test
2024-02-08 00:59:22 +00:00
Anton Kulyk
2d4ea25731 Convert cards dashboard actions to TypeScript (#38447)
* Convert `addDashCardToDashboard` to TypeScript

* Convert `addCardToDashboard` to TypeScript

* Convert `addMarkdownDashCardToDashboard` to TypeScript

* Convert `addHeadingDashCardToDashboard` to TypeScript

* Convert `addLinkDashCardToDashboard` to TypeScript

* Convert misc actions to TypeScript

* Fix types

* Move card utils to `metabase/dashboard/utils`

* Improve types

* Exclude `undefined` from `dashboard_tab_id` type
2024-02-07 20:27:59 +00:00
Emmad Usmani
7ae05d9c6b remove generic type from TabButton (#37945) 2024-02-07 19:48:21 +00:00
Oisin Coveney
efa83b6265 Add ability to use session tokens with JWT SSO 2024-02-07 19:05:01 +01:00
Uladzimir Havenchyk
80b5958943 Add questions caching layer to improve dashboard performance after migration to MLv2 (#38425)
* Apply performance tweaks during dashboard editing

* Revert one change for tests

* Fix unit test

* reapply fix

* Try another improvement

* Revert "Adding cache stats to metabase.lib.cache"

This reverts commit dc32be74c0.

* Fix unit test

* More question caching

* Revert "Revert "Adding cache stats to metabase.lib.cache""

This reverts commit 4eea6a12fa.

* Cache questions

* Pass object

* Reuse questions

* Fix unit tests

* Fix unit tests

* Resolve conflicts

* Reuse questions in autowire

* fix typecheck

* json.stringify -> toString

* naming cleanup

* Support multi-series dashboards

* cleanup

* cleanup

* Fix typecheck

* Use only unique targets

* Address comments
2024-02-07 20:40:10 +03:00
Romeo Van Snick
0002d2cadf Migrate info hover card to mantine (#38433)
Add HoverCard to metabase/ui and converts FieldInfoPopover to make use of it.

Add DelayGroup helper, which can be used to make sure there are no delays when hovering similar items in the same group.
2024-02-07 16:39:52 +00:00
Anton Kulyk
ea58331c29 Auto focus search input in question picker modal (#38514) 2024-02-07 14:27:30 +00:00
Nemanja Glumac
ff62088afb [QC] Remove unused clean method from the query prototype (#38508)
* Remove unused `canRemove` method from `Aggregation` prototype

* Remove unused `clean` method from the `StructuredQuery` prototype

* Remove unused `cleanNesting` method from the `StructuredQuery` prototype

* Remove unused `_cleanEmpty` method from the `StructuredQuery` prototype

* Remove unused private methods from the `StructuredQuery` prototype

- cleanJoins
- cleanExpressions
- cleanFilters
- cleanFields

And the underlying
- _cleanClauseList

* Remove `clean` method from `NativeQuery` and `Query` prototypes
2024-02-07 12:41:08 +01:00
Anton Kulyk
12db70dc24 Clean up dashboard card types (#38444)
* Add standalone `VirtualDashboardCard` type

* Rename `DashboardCard` to `QuestionDashboardCard`

* Add new `DashboardCard` type

* Move `ActionDashboardCard` type def to dashboard types file

* Rename `isQuestionDashCard` type guard

* Fix `isQuestionDashCard` type guard

* Avoid type-casting for `getVisualizationRaw`

* Use type guard for dashcard `series` attr

* Avoid type casting in parameter mapping utils

* Fix type casting
2024-02-07 10:43:29 +00:00
Nemanja Glumac
495e88a518 [QC] Remove unused metabase-lib (v1) utilities (#38504)
* Remove unused `clearSegments` utils

* Remove unused `clearFilters` utils

* Remove unused `clearAggregations` utils

* Remove unused `clearExpressions` utils

* Remove unused `hasValidBreakout` method from the `StructuredQuery`

The util with the same name was defined in `metabase-lib/queries/utils/`
2024-02-07 11:00:14 +01:00
Luis Paolini
ff092422d2 Update running-metabase-on-elastic-beanstalk.md (#38478)
add a comment about enterprise version
2024-02-07 10:17:54 +01:00
Mahatthana (Kelvin) Nomsawadi
8cd9b60414 Fix ESlint rules (#38458)
* Fix ESlint from the result of upgrading ESLint package

* Support `component` prop on Mantine

* Prevent accidental ESLint log in Cypress

* Upgrade ESLint rule
2024-02-07 08:46:28 +00:00
metamben
6cf9e243c2 Implement filtering cards by segment or metric ID (#38337)
* Implement filtering cards by segment or metric ID

Fixes #37688.
2024-02-06 21:02:28 +00:00
Uladzimir Havenchyk
64e99fcf86 [Dashboard] Do not update dashboard settings on every keypress in Heading (#38361) 2024-02-06 20:50:48 +00:00
Jeff Bruemmer
a922ecc39c update release list header (#38049) 2024-02-06 15:30:46 -05:00
Cam Saul
256e608315 Implement equality for MLv2 MetadataProviders (#38413)
* MLv2 MetadataProviders should know if they are equal

* PR feedback
2024-02-06 12:13:50 -08:00
Jeff Bruemmer
5db7e28a74 update releases (#38480) 2024-02-06 14:28:39 -05:00
Jeff Bruemmer
b93e91884a update list of releases (#38376) 2024-02-06 13:10:13 -05:00
Jeff Bruemmer
d6388313f9 docs - duplicate dashboard card (#38451) 2024-02-06 12:18:27 -05:00
Nemanja Glumac
4e36449558 [E2E] Overload the existing E2E visitDashboard helper to make it work with the alias (#38309)
* Add `visitDashboardAlias` E2E helper

* Overload `visitDashboard` helper

It should work with either dashboard id, or with a dashboard id alias.

* PoC: Use overloaded `visitDashboard` helper

* Update even more tests with the overloaded `visitDashboard` helper

* Use `cy.visit` for tests with `cy.clock` instead of a custom helper

* Rename non-exported functions
2024-02-06 16:50:44 +00:00
Alexander Solovyov
d5b923cbfa deserialization should happen inside a transaction (#38442) 2024-02-06 19:37:41 +03:00
Mahatthana (Kelvin) Nomsawadi
2664f101aa Keeps preview across different tabs (#38271)
* Keep preview when toggling between code/preview in each tab

* Persist preview across tabs

* [WIP] don't reload embed preview when changing appearance

TODO:
- Fix font loading

* Allow changing Static/public embedding font on the fly

* Use 2-way dashboard state/URL hash syncing to avoid failing tests

* Fix E2E tests after dashboard preview doesn't reload on every change

* Use an existing util

* Fix test name

* Add tests to ensure preview doesn't rerender unnecessarily

* Fix dashboard embed preview reload when it shows parameters

* Review: Comment code for clarity

* Fix tests after fixing the preview In Cypress
2024-02-06 15:42:46 +00:00
Cal Herries
a90125963d Fix redshift not supporting uploads (#37505) 2024-02-06 15:34:10 +00:00
Uladzimir Havenchyk
53db234530 [Dashboard] Do not update dashboard settings on every keypress in Text (#38360) 2024-02-06 15:00:24 +00:00
Nemanja Glumac
39fba6166a [QC] Remove unused newQuestionFlow function (#38459) 2024-02-06 13:22:57 +01:00
lbrdnk
113c05589b Mongo java driver upgrade (#38017)
* tmp: patched monger for 4.11.1 mongo java driver

* tmp: Update monger utils

Aggregation probably wont work now, but we are not using those from monger anyway. With this change in place I'm able to load needed namespaces and create test-data dataset successfully.

Commit contains lot of condo errors that should be resolved while porting.

* WIP: Monger removed in favor of java driver wrapper

* Update java driver wrapper

* Update srv test

* Update comments

* Use non keywordized run-command for `dbms-version`

* Fix according to e2e tests

* Cleanup

* Separate `java-driver-wrapper` into multiple namespaces

* Fix semantic type inference for serialized json

* Fix options for run-command

* Cleanup json namespace

* Cleanup conversion namespace

* Cleanup operators

* Update kondo in operators ns

* Cleanup connection namespace

* Cleanup mongo namespace

* Cleanup util namespace

* Add todo

* Move session related code to util

* Cleanup database namespace

* Update docstring for conn string generation

* Update docstrings

* Update tests

* Update linter for with macros

* Update modules/drivers/mongo/src/metabase/driver/mongo/connection.clj

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>

* Update modules/drivers/mongo/src/metabase/driver/mongo/connection.clj

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>

* Use transient in from-document for building a map

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>

* Update can-connect to use let form

- Avoid nested `with-mongo-database` call.
- Avoid creating a set used for searching for database name.

* Remove redundant set use from describe-database

* Change from-document keywordize default to false

* Remove log message translation

* Update maybe-add-ssl-context-to-builder! to always return builder

* Indent from-document

* Remove redundant ConvertToDocument extensions

* Use oredered-map in do-find's sort

* Use ex-info in details-normalized

* Add imports and update comment in execute ns

* Update fixme comment

* Pass opts instead of a selection to from-document in do-find

* Avoid unnecessary double dot call

* Update connection test ns according to review remarks

* Make tests parallel

* Docstring update

* Update docstring

---------

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>
2024-02-06 12:10:52 +01:00
Kamil Mielnik
2a70cd5df8 [MLv2] [FE] Migrate setDefaultDisplay to MLv2 (#38221)
* Add new Question.prototype.setDefaultDisplay boilerplate
- rename old one to _setDefaultDisplay

* Handle native queries

* Handle table & scalar displays

* Add aggregationColumn wrapper

* Add breakoutColumn wrapper

* Add semanticType to ColumnDisplayInfo

* Add skeleton for the rest of setDefaultDisplay

* Add effectiveType to ColumnDisplayInfo

* Extract getDefaultDisplay out of Question

* Add test suite for getDefaultDisplay

* Add a test case for simple queries

* Add a test case for 1 aggregation and no breakouts

* Add a test case for 1 aggregation, 1 breakout and state column

* Format code

* Update test query

* Add a test case for 1 aggregation, 1 breakout and country column

* Update test names

* Simplify setup

* Add date-related tests

* Extract isState, isCountry, deal with breakout info vs column info

* Handle dates

* Move helpers down

* Add tests for binning

* Add explanatory variable

* Handle 1 aggregation and 2 breakouts, at least 1 of which is date

* Handle 1 aggregation and 2 breakouts by coordinates

* Add a test case for default return

* Use parameterless aggregation

* Handle categories

* Optimize: do not call Lib.displayInfo for all breakouts

* Optimize: extract getBreakoutInfos and call it only when necessary

* Do not group tests

* Remove redundant createQueryWithClauses calls

* Rename getBreakoutInfos to getBreakoutColumnInfos

* Fix Question.prototype.updateSettings typing

* Simplify test setup

* Simplify code

* Use accounts table

* Remove Question.prototype._setDefaultDisplay

* Rename getDefaultDisplay to defaultDisplay and expose it in metabase-lib/v2

* Update test names

* Consolidate conditions

* Fully migrate Category and Date checks

* Fix typo

* Split unrelated conditions to make it look like in the original function

* Reorder arguments to match the convention

* Rename getBreakoutColumnInfos to getBreakoutsWithColumnInfo

* Prevent categorizing extraction of/truncation to year as temporal-extraction

Fixes #37172.

* Move display.ts to viz/display.ts

* Use existing Lib.is* functions

* Make a change to trigger CI

* Revert "Make a change to trigger CI"

This reverts commit 328becd8e6.

* Do the same for any display-info calculation

---------

Co-authored-by: Tamás Benkő <tamas@metabase.com>
2024-02-06 07:05:41 +00:00
Mark Bastian
d601f0e8df Adding geographic coordinate formatting to exports (#38441)
* Adding geographic coordinate formatting to exports

Prior to this PR, exports as csv, excel, and json files as well as html in emails all treated longitude and latitude values as plain floats while the UI rendered the coordinates as degrees NSEW. This PR adds a new function, `format-geographic-coordinates`, in `metabase.formatter` and applies it to these tabular exports.

The function is applied as follows:

- For everything but excel exports, a new case  in `metabase.formatter/create-formatter` was added that renders all `:type/Coordinate`s
- For excel exports, `metabase.query-processor.streaming.xlsx/maybe-parse-coordinate-value` was added in the `add-row!` function and follows the same pattern as `maybe-parse-temporal-value`

Unit tests were added to cover all three export formats as well as html rendering in pulses (emails).

* Fixing `metabase.pulse.render.body-test` for lon/lat formatting.
2024-02-06 04:37:09 +00:00
Mark Bastian
16b85351f6 Adding nil-safe code in model-hydrate-based-on-upload (#38448)
Commit 8201e5457f introduced failing tests (e.g. `clj -X:dev:ee:ee-dev:drivers:test :only metabase.api.card-test/update-card-with-type-and-dataset-test`).

They all seem to originate from NPEs in `model-hydrate-based-on-upload` on the first condition in the `and` clause in the `based-on-upload` anonymous function. This PR just makes that first condition null-safe with a `some->` threading macro.
2024-02-05 13:43:24 -08:00
Braden Shepherdson
ea05f6ff8d [MLv2] fk-details drill should preserve := filters for other PKs (#38296)
That is, **if** there is a table with multiple PKs, and another table with
multiple FKs for those PKs, **then** any `:=` filters for other PKs on
that table should be preserved.

This allows using 1 or more quick-filter drills to add `FOO_ID = 7` filters
for some of the foreign table's PKs, followed by a fk-details drill that
jumps to the filtered view of that table.

Progress towards #36253.
2024-02-05 17:11:58 +00:00
Anton Kulyk
b2b9e63704 Hide unmapped filters for public/embedded dashboards (#38368)
* Hide unmapped filters for public/embedded dashboards

* Add E2E tests

* Add missing null check

* Rename filters in E2E tests

* Make `hiddenParameterSlugs` consistent

* Use `selectedTabId` from state

* Remove newline

* Fix E2E tests

* Fix test setup

* Fix name shortcuts
2024-02-05 16:58:31 +00:00
Cal Herries
8201e5457f BE: add based_on_upload to GET /api/collections/:collection/items response (#38322) 2024-02-05 18:31:29 +02:00
Ryan Laurie
6f3f8d1d1d Add Hebrew Language Support (#38045)
* add Hebrew support
2024-02-05 08:55:40 -07:00
Ngoc Khuat
0e2f490960 Add report_card.type (#38074) 2024-02-05 15:53:36 +00:00
metamben
f8caa7ac0d Prevent categorizing extraction of/truncation to year as temporal-extraction (#38358)
* Prevent categorizing extraction of/truncation to year as temporal-extraction

Fixes #37172.
2024-02-05 18:22:14 +03:00
Uladzimir Havenchyk
63fcc71d0b Avoid recreating target question in auto-wire parameters handling (#38426) 2024-02-05 17:37:02 +03:00
Uladzimir Havenchyk
ee7463f1cd [Dashboard] Drop unused selector (#38427) 2024-02-05 17:00:27 +03:00
Nemanja Glumac
778e5cdf65 [QC] Organize ViewHeader component and its related files (#38421)
* Move all files related to the `ViewHeader` component to a separate folder

* Rename utils and convert to TS

* Move `View.jsx` back to the common top level folder

* Add `index.ts` to the `ViewHeader` structure

* Move `ExploreResultsLink` component

* Move `FilterHeaderButton` component

* Move `HeaderBreadcrumbs` component

* Move `QuestionNotebookButton` component

* Move `QuesitonDataSource` component

* Move `ConvertQueryButton` component

* Move `QuestionDescription` component

* Move `QuestionActions` component

* Move `QuestionSummarizeWidget` component

* Remove unused function

* Move `QuestionFilters` component

* Remove unused eslint directive

* Fix accidental empty export

* Export all components from a single `index.ts`
2024-02-05 14:14:33 +01:00
Chris Truter
448b07b83e Improve CSV upload filename uniqueness (#38353) 2024-02-05 15:06:53 +02:00
Oleg Gromov
08a3805ec0 Dashboard required params (#38203)
* Add required label to dashboard parameter settings pane
* Enable required behavior for parameter widgets on the dashboard
* Support reverting back to default value for all widget types
* Add and update e2e tests
2024-02-05 10:15:39 +00:00
Nemanja Glumac
c18aecb6ca [QC] Move canExploreResults out of the Question prototype (#38328)
* Move `canExploreResults` out of the Question prototype

* Move `canExplore` to `ViewHeaderUtils` file

* Add back unit tests for `canExplore`
2024-02-05 08:05:56 +01:00
Mark Bastian
ee1581fb6b Fixing static-viz exports of saved x-ray dashboards (#38379)
* Fixing static-viz exports of saved x-ray dashboards

When dashboards were generated with x-rays, the `:visualization_settings` were not properly filled in. In particular, the `:graph.dimensions` and `:graph.metrics` were being populated from either the raw template values or not at all. The following namespace demonstrates this:

```clojure
(ns tickets.38350-broken-xray-export
  (:require
    [dev.render-png :as render-png]
    [metabase.models :refer [Card]]
    [metabase.test :as mt]))

(mt/dataset test-data
  (mt/with-temp [Card {bad-card-id :id}
                 {:display :row
                  :dataset_query {:database (mt/id)
                                  :type     :query
                                  :query    {:source-table (mt/id :orders)
                                             :aggregation  [[:count]]
                                             :breakout     [[:field
                                                             (mt/id :products :category)
                                                             {:source-field (mt/id :orders :product_id)}]]}}
                  :visualization_settings {:graph.series_labels [nil]
                                           :graph.dimensions [{:ProductCategoryMedium {}}]
                                           :graph.colors ["#EF8C8C"]
                                           :graph.metrics [nil]}}
                 Card {good-card-id :id}
                 {:display :row
                  :dataset_query {:database (mt/id)
                                  :type     :query
                                  :query    {:source-table (mt/id :orders)
                                             :aggregation  [[:count]]
                                             :breakout     [[:field
                                                             (mt/id :products :category)
                                                             {:base-type :type/Text
                                                              :source-field (mt/id :orders :product_id)}]]}}
                  :visualization_settings {:graph.dimensions ["CATEGORY"]
                                           :graph.metrics ["count"]}}]
    (render-png/render-card-to-png bad-card-id)
    (render-png/render-card-to-png good-card-id)))
```

The FE seemed to have some level of error checking and was robust enough to recover from these bad `:visualization_settings`.

The solution is to correctly populate these values. This required updating the `:dimension-name->field` value in each card to include mappings derived from both metrics and dimensions and then using the right logic in the `visualization-settings` function.

* Removed unneeded `->legacy-MBQL` on values in `:mbql/query` dispatch
2024-02-02 23:08:32 +00:00
Mark Bastian
ab9ede8e1e Upload random replays from master only (#38414)
Adding `r.metadata.source.branch === "master" &&` to `randomlyUploadAll` for master-only uploads.

Also adding more info to log message.
2024-02-02 21:02:04 +00:00
Emmad Usmani
34c8eaf849 add dashcard replace event to snowplow schema and e2e test (#38411)
Part of https://github.com/metabase/metabase/issues/36497

### Description

In https://github.com/metabase/metabase/pull/36744 we tracked dashcard replacement with a new event name, but did not add this event name to the dashboard snowplow schema.

In this PR we add the name to the schema, and update an e2e test to ensure the event is being tracked.

### How to verify

Follow this [guide](https://www.notion.so/metabase/Snowplow-integration-5da1f874beda4153b4fccfa6c1e77caa) to run snowplow, then try replacing a dashcard locally, you should see the log in the console.

### Demo

https://github.com/metabase/metabase/assets/37751258/e8566f09-b9b8-47de-b215-fe0e25c7d920

### Checklist

- [x] Tests have been added/updated to cover changes in this PR
2024-02-02 12:51:33 -08:00
Jeff Bruemmer
4735d3bb39 docs - update api docs script (#38194) 2024-02-02 15:25:09 -05:00
Emmad Usmani
bf6d1e57a5 add snowplow event tracking for card and tab duplication (#38408)
Part of https://github.com/metabase/metabase/issues/38208

### Description

Adds snowplow event tracking for dashboard card and tab duplication. No snowplow schema changes were made, we just added a couple of new event names.

### How to verify

Follow this [guide](https://www.notion.so/metabase/Snowplow-integration-5da1f874beda4153b4fccfa6c1e77caa) on running snowplow locally, then go to a dashboard and duplicate some cards and tabs, confirm the logs appear.

### Demo

https://github.com/metabase/metabase/assets/37751258/db59337d-a3aa-4d5d-afd0-fdd9998b13ed


### Checklist

- [x] Tests have been added/updated to cover changes in this PR
2024-02-02 12:06:43 -08:00
Braden Shepherdson
21712d698b [MLv2] Add caching for the common case of visible-columns w/o options (#38409)
The options make caching
`metabase.lib.metadata.calculation/visible-columns` difficult, but the
common case is to call it without options on things like query stages.

That case is expensive, common, and reusable, so this is a great spot to
cache it.

Note that `metabase.lib.js/visible-columns` is also cached in the same
way, but this does not really overlap. The JS wrapper actually populates
the `selected: true` flags as well, and returns a JS array. This
slightly modified value is what gets cached there, and it's enough extra
work (calling `returned-columns` and `mark-selected`) that it's worth
having both. Structural sharing of the untouched or lightly-edited column
maps means the memory impact is modest.
2024-02-02 14:36:43 -05:00
metamben
3bc463df51 Return card__<id> for non-model cards and FK targets for tables (#38378)
Fixes #38312.
2024-02-02 22:35:31 +03:00
Mark Bastian
b5af8b9b70 Upload flakes to replay (#38407)
Adds additional logic per [this Slack thread](https://metaboat.slack.com/archives/C052LBPDAF3/p1706613621488479) to upload flake replays.
2024-02-02 12:13:36 -07:00
metamben
feb534e337 Make the MLv2 display-name include the path of nested fields (#38054)
* Make the MLv2 display-name include the path of nested fields
* Hide binning and bucketing info when displaying breakoutables

Fixes #35938.
2024-02-02 21:28:32 +03:00
Chris Truter
6b6fe582b5 Allow :base to be a map of inherited options for defsetting (#38088) 2024-02-02 17:53:29 +00:00
Cam Saul
b9229a7731 Sort drill should remove ALL existing order bys (#38380) 2024-02-02 09:49:16 -08:00
Braden Shepherdson
efa166cc62 [MLv2] Drill-thru coverage: Add a structured column and fix that case (#38295)
Most drills don't appear for structured (eg. JSON, XML) columns.

This adds a new canned query and canned clicks for such a column
(by lying in the metadata), then fixes a few test expectations
plus one broken drill.

Progress towards #36253.
2024-02-02 11:23:39 -05:00
Chris Truter
39e24ce31f Update fieldvalues in a transaction (#38388) 2024-02-02 17:33:44 +02:00
Braden Shepherdson
2c2fdc625f [MLv2] Fix some edge cases and add more unit tests for zoom in drills (#38275)
More progress towards #36253.
2024-02-02 10:26:08 -05:00
Kamil Mielnik
c8d86f7073 Repro #38354 - Not able to switch between databases after a question is created (#38387)
* Add e2e test for metabase#38354

* Rename file to match issue id

* Tag the test as external since it uses QA DBs

* Fix ORDERS_ID
2024-02-02 14:20:05 +00:00
Nemanja Glumac
7c1dd93bcf [CI] Upgrade dorny/paths-filter action to v3.0.0 (#38367)
Resolves #38301
2024-02-02 14:05:19 +01:00
Nemanja Glumac
d9f5be7577 [CI] Upgrade actions/github-script action to v7 (#38366) 2024-02-02 14:04:45 +01:00
Jeff Bruemmer
2049602ff2 docs - clarify collection perms (#38317) 2024-02-02 07:14:11 -05:00
Luis Paolini
4d56ed46b0 Revert redshift change to docs (#38382) 2024-02-02 07:10:23 -05:00
Alexander Polyankin
f04abae5de Migrate syncStructuredQueryColumnsAndSettings to MLv2 (#37693)
* Migrate syncStructuredQueryColumnsAndSettings to MLv2

* Migrate syncStructuredQueryColumnsAndSettings to MLv2

* Fix types

* Support converting aggregation references to legacy references

Fixes #37698.

* Update TS wrapper

* Pass query and stageIndex to legacyQuery

* Pass query and stageIndex to legacyQuery

* Remove no longer used columnDimensionWithName

* Update assertion in failing test

* Replace non-existing Question.prototype.isNative & Question.prototype.isStructured calls

---------

Co-authored-by: Tamás Benkő <tamas@metabase.com>
Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>
2024-02-02 18:27:25 +07:00
Chris Truter
5ec3e3b827 Evaluate all defsetting arguments at runtime (#38128) 2024-02-02 12:13:05 +02:00
Jesse Devaney
1c3f46a66b Display full-dates for trend charts backed by native queries (#38344)
* auto-adjust native query dates to be at the start of the date range

* re-work trend charts compute function to handle updated native query date formatting

* add test to validate the native query date formatting

* fix unit tests

* reorganize test
2024-02-02 02:14:14 +00:00
Denis Berezin
f9a3177314 Fix user loading, demo prep 2024-02-02 05:10:36 +07:00
Braden Shepherdson
2e76d41352 [MLv2] New "canned" queries and clicks for drill-thru testing (#38210)
This also adds a couple of hand-written test cases in addition to
testing the canned set of queries against most of the drills.

Progress towards #36253.
2024-02-01 21:32:01 +00:00
Braden Shepherdson
2d6d12c8d6 [MLv2] Cache JS -> CLJS metadata conversion (#38375)
This previous got rebuilt from scratch over and over, since different
queries being handed the same JS `Metadata` instance were returning
completely separate `MetadataProvider`s.

The FE replaces the `Metadata` instance as new metadata arrives from the
BE, so the `metabase.lib.cache/side-channel-cache` which is attached to
the input object is implicitly invalidated when the old `Metadata` is
thrown away.
2024-02-01 21:03:27 +00:00
Denis Berezin
ac53cf512f Merge branch 'embedding-sdk-poc-denis' of github.com:metabase/metabase into embedding-sdk-poc-denis
# Conflicts:
#	frontend/src/embedding-sdk/QueryVisualization.tsx
#	frontend/src/embedding-sdk/SdkProvider.tsx
#	host-app-example/src/App.css
#	host-app-example/src/App.js
#	host-app-example/src/ChooseQuestionInput.js
2024-02-02 03:50:06 +07:00
adam-james
ffd18732b8 Fixed width dashboard migration (#38247)
* Migration adding 'width' to Dashboards

3 migrations:
 - 1st adding the width column with default value of 'fixed'
 - 2nd updating all existing dashboards to have width 'full', which corresponds to what the current behaviour is (will
 be the 'old' behaviour after the fixed-width project lands).
   - The rolloback here is necessary but we don't care what happens as the column will be dropped immediately in the
   next rollback anyway
 - 3rd sets the notNullableConstraint. DefaultNull is 'full' here, just in case there's an existing dashboard whose
 width value is not yet set from the 1st migration. Don't know how that could happen, but its here in case

* Dashboard PUT api endpoint accepts width changes and updates appdb

update-dashboard function now is aware of the :width key so those changes can end up in the transaction.

Also added a width test that asserts that the value's default is "fixed", it can be changed, eg. to "full", but cannot
be changed to other values.

* Add width to revision tests

* Fix dashboard revision tests.

:width key is now needed in some revision tests. As well we need a string communicating that the :width setting has
changed from 'full' to 'fixed' or vice-versa.

* Fix comments/remarks in migration to be accurate

* Attempt to fix default not working mysql/mariadb

* Set default in dashboard model

Signed-off-by: Adam James <adam.vermeer2@gmail.com>

* Revert default :width 'fixed' value.

* Explicitly add default value 'fixed' for MySQL/MariaDB

---------

Signed-off-by: Adam James <adam.vermeer2@gmail.com>
2024-02-01 11:37:53 -08:00
Jeff Bruemmer
09e7c0449e add redshift to impersonation db list (#38369) 2024-02-01 16:37:00 -03:00
Denis Berezin
b10d5dab59 Update demo 2024-02-02 02:11:44 +07:00
Cal Herries
022201aaff CSV appends: Milestone 0, Merge 2 of 2: upload through model page (#37220)
Co-authored-by: Ryan Laurie <30528226+iethree@users.noreply.github.com>
2024-02-01 20:09:57 +01:00
Oisin Coveney
ac9b9620d8 Remove unneeded loads for settings + properties 2024-02-01 18:01:27 +00:00
Oisin Coveney
d34503373d Adjust to make sure that fonts are initialized 2024-02-01 17:55:12 +00:00
Oisin Coveney
71952ab1a3 Add question list hook and move MetabaseProvider to root 2024-02-01 17:46:34 +00:00
Romeo Van Snick
6f7e9c4baf Fix issue where reverted question does not use parameter values (#38321)
Makes sure we pass the parameter values to the question when running it after a user reverts to an older version. Resolves metabase#38176.

* Pass correct shape of parameters to question
* Add reproduction for #38176, where a reverted question does not use the parameters
* Reduce paramterValues to the correct format instead of using internal field
* Add issue specifier to test
Co-authored-by: Nemanja Glumac <31325167+nemanjaglumac@users.noreply.github.com>
* Create test question with relevant name
Co-authored-by: Nemanja Glumac <31325167+nemanjaglumac@users.noreply.github.com>
* Avoid setting delay on input
* Fix text in cell
* Simplify selectors for button
* Add comment on parameterValues building

---------

Co-authored-by: Nemanja Glumac <31325167+nemanjaglumac@users.noreply.github.com>
2024-02-01 18:01:47 +01:00
Oisin Coveney
9bdd7e926c Add question search hook and question list 2024-02-01 16:33:17 +00:00
Oisin Coveney
eb8e199625 Change import order to make things work 2024-02-01 16:31:17 +00:00
Nicolò Pretto
649b99a1e0 deprecate trackStructEvent to avoid confusion (#38351) 2024-02-01 16:18:44 +01:00
Tony-metabase
eaa548f441 Update migrating-from-h2.md so Postgres version is 9.5 (#38318)
On version 4.8 metabase version 9.4 is not supported

Co-authored-by: Jeff Bruemmer <jeff.bruemmer@gmail.com>
2024-02-01 11:34:42 -03:00
Oisin Coveney
3718f2d3ae Remove useApi 2024-02-01 14:13:15 +00:00
Oisin Coveney
b704429325 Remove unneeded files, add hooks, change styles 2024-02-01 14:09:38 +00:00
Oisin Coveney
7653d2fe06 Move css to styled components 2024-02-01 12:51:51 +00:00
Ngoc Khuat
54b0d73bb1 Speculative fix for migration on multi instances (#38257) 2024-02-01 11:52:57 +00:00
Oisin Coveney
27b7ade789 Merge changes 2024-02-01 11:33:25 +00:00
Uladzimir Havenchyk
4aafb85d14 Add repro for handling not saved dashcards with mapped filters and tabs (#38249)
* Add repro for handling not saved dashcards with mapped filters and tabs

* Fix repro test

* Update e2e/test/scenarios/dashboard-filters/reproductions/38245-negative-dashcard-id-switching-tabs.cy.spec.js

Co-authored-by: Nemanja Glumac <31325167+nemanjaglumac@users.noreply.github.com>

---------

Co-authored-by: Nemanja Glumac <31325167+nemanjaglumac@users.noreply.github.com>
2024-02-01 14:06:12 +03:00
Nemanja Glumac
8b7b1f621f Upgrade actions/setup-java action to v4 (#38332) 2024-02-01 11:38:22 +01:00
Nemanja Glumac
717120cbbd Upgrade actions/cache action to v4 (#38335) 2024-02-01 10:07:50 +01:00
Nemanja Glumac
16fdd8ef7b Upgrade actions/setup-node action to v4 (#38331) 2024-02-01 10:07:34 +01:00
Nemanja Glumac
82a6b79871 [QC] Clean up isStructured (v1) utilities (#38136)
* Tidy-up `isStructured` v1 utils

This is a follow-up after #37977.
Related to #37953

* Rename MLv1 helper from `isStructured` to `isNative`
2024-02-01 10:03:18 +01:00
Nemanja Glumac
0ef4644aea Upgrade aws-actions/configure-aws-credentials action to v4 (#38334) 2024-02-01 09:39:34 +01:00
Nemanja Glumac
3ea5caff0c Upgrade actions/upload-artifact and actions/download-artifact action to v4 (#38306)
* Upgrade `actions/download-artifact` action to v4

* Upgrade `actions/upload-artifact` action to v4
2024-02-01 09:31:49 +01:00
Vamsi Peri
8cda1be267 TLS Certificates: updates AWS RDS CA bundle (#38340)
Updated the Global Bundle with the content of  https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem -O rds-combined-ca-bundle.pem
This is the new URL to be used, as described on https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.SSL.html

The new bundle:
- removes expired root certificates
- keeps certificates for `rds-ca-2019`
- adds certificates for all regions for
  - `rds-ca-rsa2048-g1`: certificate authority with RSA 2048 private key algorithm and SHA256 signing algorithm
  - `rds-ca-rsa4096-g1`: certificate authority with RSA 4096 private key algorithm and SHA384 signing algorithm
  - `rds-ca-ecc384-g1`: certificate authority with ECC 384 private key algorithm and SHA384 signing algorithm

It fixes #32017 and #27790

Co-authored-by: Théophile Helleboid <theophile.helleboid.ext@qonto.com>
2024-01-31 17:28:05 -05:00
Emmad Usmani
ad839609c1 add e2e test for dashboard card and tab duplication (#38246)
Part of https://github.com/metabase/metabase/issues/38208

### Description

Adds e2e tests for dashboard card and tab duplication

### Checklist

- [x] Tests have been added/updated to cover changes in this PR
2024-01-31 12:25:09 -08:00
Emmad Usmani
8f3f8a412c allow users to duplicate dashboard tabs (#38190)
Closes https://github.com/metabase/metabase/issues/38208

### Description

Adds a item to the dashboard tab menu to duplicate the tab.

### How to verify

1. Open a dashboard you can edit
2. Go to edit more, click the tab menu for a tab
3. Click duplicate, tab should be duplicated

### Demo

https://www.loom.com/share/d73aad469074440992618ee179518d39

### Checklist

~~- [ ] Tests have been added/updated to cover changes in this PR~~

e2e tests are added in the next PR in the stack
2024-01-31 11:46:44 -08:00
Emmad Usmani
784d3c697a add button to duplicate dashcard (#38186)
Part of https://github.com/metabase/metabase/issues/38208

### Description

Adds another button to the dash card action panel that duplicates that dashcard.

### How to verify

Describe the steps to verify that the changes are working as expected.

1. Open a dashboard that you can edit
2. Mouseover a dashcard
3. Click the duplicate icon

### Demo

https://www.loom.com/share/d73aad469074440992618ee179518d39

### Checklist

~~- [ ] Tests have been added/updated to cover changes in this PR~~

e2e tests are added further down the stack
2024-01-31 11:06:50 -08:00
Raphael Krut-Landau
164f0f5de0 Fix TableBrowser flex (#38324) 2024-01-31 17:30:54 +00:00
John Swanson
aa76efb249 Query row limit doesn't limit in-product downloads (#37716)
I misunderstood the desired behavior when I implemented this before. We
only want the limit to apply when the `add-default-userland-constraints`
middleware is applied to the query, not when we're downloading the data
directly.

This is a bit of a rat's nest. If there's a better way to approach the
problem, I'd be happy to hear it. I added documentation for the odd approach
as much as possible.

The main difficulty is that the userland middleware does not have access
to db-local settings. So if we want db-local settings to apply only to
userland, we have to hack our way around it.

The solution here is to divide the userland middleware into two parts:

- the actually-userland bit, which just marks the query as needing
default limits, and

- a middleware inserted deeper in the middleware stack (just before we
actually apply limits) that actually calculates those limits and
attaches them to the query.
2024-01-31 12:25:05 -05:00
Denis Berezin
7f38319360 Add fonts loading 2024-01-31 23:50:29 +07:00
Raphael Krut-Landau
9166c58e6d Basic version of Models in Browse Data (#37707)
* Add Models and Databases tabs
* Models are organized by collection
* Exclude items in personal collections
* Simplify BrowseHeader
2024-01-31 10:39:48 -05:00
Aleksandr Lesnenko
6657c3cb75 format native queries (#38113)
* format native queries

* optional clauses, mlv2, specs

* remove unnecessary webpack chunk name directive

* disable formatting for mssql and sqlite, address review comments
2024-01-31 14:54:11 +00:00
Nicolò Pretto
c9d832deba use different folders for oss and ee for webpack cache (#38308) 2024-01-31 15:18:10 +01:00
Nemanja Glumac
4ac58f9ded [CI] Upgrade actions/checkout action to v4 (#38302) 2024-01-31 11:37:14 +01:00
Cal Herries
6f33ab2a70 CSV uploads: Expand valid date formats to include one digit days (#38276) 2024-01-31 09:47:05 +00:00
Cal Herries
6fa785b5b8 CSV appends: Do not allow numbers with fractional component to be uploaded to an integer column (#38274) 2024-01-31 09:58:20 +01:00
John Swanson
ebbc6670c2 Add intermittent test solver (#38159)
Sometimes a test passes when run by itself, but fails due to ordering
issues. This is typically caused by another test failing to properly
clean up after itself, leaving the database in a dirty state. For
example, we might change permissions and forget to change them back, so
that another test hits an unexpected permissions failure.

Finding the cause of these has been a source of pain for me, so I wrote
a small snippet to do it for me.

If you have a test that passes when run by itself, but fails when run
along with all the other tests, you can run
`(dev/find-root-test-failure! #'my-ns/my-intermittent-failure-test')`.

It will run *all* tests. After each one, it'll run the test you passed
in. Once that test starts failing, it'll alert you about which test
caused it to fail.
2024-01-30 16:19:55 -05:00
Ryan Laurie
e4827e08b6 Use mantine popover in entityMenu (#37895)
* use mantine popover in entityMenu

* control popover state

* more control

* fix unit tests to work with snazzy new popover

* boringer animation
2024-01-30 19:13:06 +00:00
Filip Hric
667630d503 Add sourcemap option to Cypress preprocessor (#38251) 2024-01-30 19:40:15 +01:00
metamben
636258a798 Cast to timestamp before truncating (#38214)
* Cast to timestamp before truncating

The shift according to the timezone after the truncation can produce values not at the beginning of the truncation
period.

* Separate handling of time and date inputs

* Add test reproducing issue #37065
2024-01-30 21:29:51 +03:00
Oleg Gromov
a86239611f Native query editor: Add an explanatory tooltip for the save button when required template tags miss defaults (#38232)
* Add an explanatory tooltip for the save button when required template tags miss defaults
* Update e2e tests
2024-01-30 17:06:44 +00:00
Denis Berezin
f612a5e5e7 Fix css and emotion global styles 2024-01-30 23:33:39 +07:00
Nemanja Glumac
b40ecc5282 [MLv2] Resort to using isNative check over isStructured (#38199)
This is purely semantic change.
Please see this comment https://github.com/metabase/metabase/pull/37977#discussion_r1467360379
2024-01-30 16:53:10 +01:00
Nemanja Glumac
023dea240f Migrate canRun() method for the structured query to MLv2 (#38240)
* Export `can-run` MLv2 function

* Add a TS wrapper `canRun`

* Migrate `canRun()` to MLv2 only for structured queries
2024-01-30 16:44:40 +01:00
metamben
1692da23e9 Support converting aggregation references to legacy references (#37705)
* Support converting aggregation references to legacy references
* Pass query and stageIndex to legacyQuery

---------

Co-authored-by: Alexander Polyankin <alexander.polyankin@metabase.com>
2024-01-30 17:51:09 +03:00
bryan
f7e688b6eb Remove useless warnings from defendpoint missing a malli schema (#38157)
* Remove useless warnings from defendpoint missing a malli schema

we knowingly call umd/describe on a possibly-nil value (`nil` is not a
malli schema). That's ok in this instance, so don't warn about it.

* Actually use the output of umd/describe
2024-01-30 09:44:52 -05:00
Nemanja Glumac
0c0e84ce33 Use Cypress event listener for beforeunload globally (#38264)
https://github.com/cypress-io/cypress/issues/2118
2024-01-30 15:32:04 +01:00
Nemanja Glumac
1011ecdb6f Disallow using async functions in Cypress tests (#38254)
* Do not use `async` functions as Cypress tests

* Add eslint rule that enforces no `async` functions

* Skip broken tests (created a follow up issue for this: https://github.com/metabase/metabase/issues/38258)
2024-01-30 11:33:40 +00:00
Nemanja Glumac
ff7db79ba7 Replace deprecated unescape function in a Cypress helper (#38252)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/unescape
2024-01-30 11:27:43 +01:00
lbrdnk
3179ab1251 Add path filtering for cljs workflow (#38198)
* Add path filtering for cljs workflow

* Add shadow-cljs.edn to cljs file paths
2024-01-29 22:22:24 +01:00
Oisin Coveney
1bb09a7c4c Allow for changes in visualization type 2024-01-29 15:12:51 -06:00
Denis Berezin
470cc7d9b1 Add basic css loading 2024-01-30 03:08:19 +07:00
Denis Berezin
a4599b3432 Fix api data loading 2024-01-30 03:02:25 +07:00
Anton Kulyk
fc53ec658b Hide dashboard filters if they're not mapped to dash cards on the current tab (#37711)
* Hide filters not mapped to current tab's dashcards

* Show all filters in edit mode

* Fix `text-dashcards.cy.spec.js`

* Remove no longer relevant test

`dashboard-filters-source.cy.spec.js`

* Fix repro test (26230)

* Update repro test (16663)

* Fix `dashboard-filters-number.cy.spec.js`

* Fix repro test (32444)

* Fix `click-behavior.cy.spec.js`

* Add basic e2e test

* Fix e2e tests

* Test filter values

* Use `undefined` for `hiddenParameterSlugs`

* Use `addOrUpdateDashboardCard` over `cy.request`

* Remove redundant spread

* Remove redundant dashboard name
2024-01-29 18:56:14 +00:00
Anton Kulyk
594cdb01a0 Convert Table viz and TableSimple to TypeScript (#38099)
* Convert `TableSimple` to TypeScript

* Convert `Table` viz to TypeScript

* Update frontend/src/metabase/visualizations/components/TableSimple/TableCell.tsx

Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>

* Update frontend/src/metabase/visualizations/components/TableSimple/TableSimple.tsx

Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>

---------

Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>
2024-01-29 18:29:10 +00:00
Anton Kulyk
221ca042d7 Convert ExplicitSize to TypeScript (#38098)
* Remove `wrapped` arg from `ExplicitSize`

* Remove `AutoExpanding` HOC

* Convert `ExplicitSize` to TypeScript

* Fix `ExplicitSize` mock

* Remove redundant type

* Revert "Remove `wrapped` arg from `ExplicitSize`"

This reverts commit 014bc4c61ae21ff67ae2157c40297f33fd39d95d.

* Fix type
2024-01-29 17:51:29 +00:00
metamben
4a5c539abd Implement MLv2 dependent-metadata (#38151)
Fixes #36974.

See the Slack [discussion](https://metaboat.slack.com/archives/C04CYTEL9N2/p1706193649444639)
for details.
2024-01-29 19:41:50 +03:00
Denis Berezin
17aa273aea Add api token usage 2024-01-29 23:05:50 +07:00
Chris Truter
6c9d52e442 Replace anaphoric with-source-and-dest-dbs with hygienic alternative (#38175)
Closes https://github.com/metabase/metabase/issues/36103

### Description

This change introduces a new `with-dbs` macro which is hygienic and supports an arbitrary number of databases.

For now I am leaving the old `with-source-and-dest-dbs` macro, so we can deal with the noise of upgrading the tests in a later PR. I upgrade a single test so that the usage is clear.
2024-01-29 13:17:07 +02:00
Alexander Solovyov
8f2194d497 update graalvm (#38218) 2024-01-29 14:03:32 +03:00
Cal Herries
31469f2f44 Exclude metabase.sync* and metabase.upload* from malli instrumentation (#38206) 2024-01-29 09:14:07 +00:00
Cam Saul
45080ad694 Chain filter search should check block perms (#38213)
* Chain filter search should check block perms

* Simplify test
2024-01-26 16:33:52 -06:00
Case Nelson
6101546f9c Field values cache needs to check permissions (#38104)
* Field values cache needs to check permissions

If a user does not have permissions to the field, we should not return
the cached field values.

* Update default-get-or-create-field-values-for-current-user to check can-read too

* Revert params.field-values change

* Use query processor permissions checks before returning cached values

* Return true from check

* Fix test

* Check for ee config
2024-01-26 20:45:37 +00:00
Nemanja Glumac
b0a54aa12d Display chart caption even where there is no card title (#36801)
* Display chart caption even where there is no card title

* Add E2E reproduction for #36788
2024-01-26 18:46:14 +00:00
Nemanja Glumac
1dda54f4f5 Migrate isStructured method references to MLv2 (#37977)
* Migrate `isStructured` method references to MLv2

* Fix broken audit pages

Just as with #38123, this is another place where MLv2 invocation broke
because it didn't guard against the internal queries.

* Remove `isStructured()` method from the `Question` prototype
2024-01-26 19:05:17 +01:00
Denis Berezin
95c356ec88 Fixes 2024-01-27 01:02:23 +07:00
Denis Berezin
5330bb6b2f Add bundling and sample app 2024-01-27 00:10:16 +07:00
Romeo Van Snick
bb6a4d0b0b Run selected text loses parameters (#38095)
* Reproduction: Run selected text does not use parameter values correctly

* Use question instead of card when overriding

* Switch to overrideWithQuestion in RELOAD_CARD

* Rename run to dataset in e2e test

* Use cypress builtins instead of custom selectors

* Remove async from e2e test

* Avoid assigning editor to variable

* Type closing }} on editor

* Set type delay to 0

* Add explainer about why the reproduction differs from the issue

* Add limit to test case

* Test actual vizualisation results instead of implementation detauls of dataset

* Clarify that the space is not needed

* Simplify cypress check
2024-01-26 17:35:31 +01:00
Raphael Krut-Landau
7de3ad243f More tidying prior to Models in Browse Data (#38126)
* Make embedding-full-app.cy.spec.js and associated components more semantic

* Make signin.cy.spec.js and associated components more semantic

* Fix comment

* minor tweak

* Remove aria-label=breadcrumbs

* Fix variable name

* Fix e2e tests

* Remove cy.heading

* Restore test name
2024-01-26 11:25:35 -05:00
Mahatthana (Kelvin) Nomsawadi
13e6ebe973 ESLint for detecting the use of Metabase links (#37738)
* [WIP] ESLint for detecting the use of Metabase links

* Add a rule to detect the use of Metabase links

* Add tests to the new eslint lint rule that detect Metabase links

* Fix all places where errors are caused by the new ESLint rule

* Review: Disable rule for admin folder

* Review: Remove rule disable reason from files under admin folder
2024-01-26 15:19:50 +00:00
Uladzimir Havenchyk
4acd8deb67 Forbid using InternalQuery with MLv2 (#38178) 2024-01-26 17:12:08 +03:00
Oleg Gromov
98005e2bac Switch to using enableRequiredBehavior instead of isInsideNativeQuery (#38177) 2024-01-26 13:25:50 +00:00
Nemanja Glumac
4aaa6866ef Fix typo in a password reset token defendpoint docstring (#38129)
[ci skip]
2024-01-26 13:44:15 +01:00
Ryan Laurie
61bc171324 Remove deprecated event tracking (#37927)
* remove deprecated event tracking

* fix e2e tests

* fix types
2024-01-26 12:27:26 +00:00
Nemanja Glumac
8575ff35e3 Restore border in a default state for bulk filter input (#38150)
Fixes #38149
2024-01-26 12:56:08 +01:00
Alexander Solovyov
c29deb8a85 specify one more guava explicitly (#38173)
It's hard for Snyk to understand which version will be used in the end,
so it complains.
2024-01-26 10:49:59 +00:00
Romeo Van Snick
a35f41d1fd Optimise autocomplete query (#38080)
For big databases autocomplete can be quite slow. At stats, query in regular form takes about 80 ms to run. Filtering out inactive tables and adding an index (pgsql-only unfortunately) for ordering clause brings that down to 10 ms.

Also I suspect that in a single session you'll hit similar autocomplete rules multiple time, so some client caching could help with performance.
2024-01-26 11:24:00 +03:00
Chris Truter
c988a90fff Add regression test for #38138 (#38144) 2024-01-26 07:20:03 +00:00
ixipixi
4c2bd21828 Update exploration.md (#37766)
Replaced reference to pulses
2024-01-26 06:53:05 +01:00
Alexander Solovyov
291ecc09a9 switch to regenerator-runtime and update follow-redirects to silence Snyk warnings (#38124)
* switch to regenerator-runtime and update glob to silence Snyk warnings

* no glob update

* update follow-redirects

* lets update debug as well
2024-01-25 21:22:31 -03:00
Cam Saul
51097b1220 Fix Snowflake sync not returning all schemas regression in 48+ (#38160)
* Fix Snowflake sync not returning all schemas regression in 48+

* Fix extra whitespace

* Better DB name

* Improved test
2024-01-25 23:46:32 +00:00
Cam Saul
508b993141 Fix NPE in schema pattern matching fns in sync (#38161)
* Fix NPE in schema pattern matching fns in sync

* Require PG
2024-01-25 23:18:57 +00:00
Nick Fitzpatrick
bdfaf72fa9 use dnd kit sortable for bookmark items (#36644) 2024-01-25 15:51:41 -04:00
Denis Berezin
f451285bef Add basic question and visualization bar 2024-01-26 01:48:30 +07:00
Oleg Gromov
913d1b1ca1 Required parameters: add to native queries (#37709)
* Mark parameter on the dashboard with *
* Require default value for a required template tag
* Add reset to native queries
* Remove unused WidgetStatusIcon
* Add reset button for native queries only
* Rewrite FieldSet in TS to fix typing
* Update e2e helper to click "Always require a value" insted of previously "Required?"
* Switch to MLv2
* Add e2e tests for required filters
* Update e2e tests
* Update another test
* Fix required untoggling bug
* Fix parenthesis in t
* Reset to default on input blur
* Show correct icons & update behavior for reqiured parameters in native queries
* Don't reset default value when toggling required
* Update the widgetstatusicon types
* Set parameter value when toggling default
* Update TagEditorParam unit tests
* Add native query tests for number, string and date
* Fix re-setting to default from empty state for field widgets
* Add e2e tags for field tags
2024-01-25 18:31:34 +00:00
Sloan Sparger
a730edff81 Navbar Improvements: Embedding (#38053) 2024-01-25 12:00:47 -06:00
Nemanja Glumac
0071b8b52d Improve developers guide related to E2E tests (#37132)
* Add section about `Lodash`

* Fix typo

* Expand the standard development flow section

* Expand the running options section

* Expand running on Docker section

* Add section for tests that require SMTP server

* Clarify the viewport resizing options

* Javascript -> JavaScript

* Delete redundant README section

* Explain `contains` vs `find` vs `get` better
2024-01-25 18:57:24 +01:00
Sloan Sparger
d789573ddc Navbar Improvements: Updated Heuristics (#37944) 2024-01-25 11:49:32 -06:00
Raphael Krut-Landau
d96f4f4b30 Port LastEditInfoLabel to TypeScript (#38109) 2024-01-25 12:47:30 -05:00
Jeff Bruemmer
6d4a294245 docs - update encryption page (#37935) 2024-01-25 12:02:05 -05:00
Kyle Doherty
09c075a73c remove border from SearchContainer until activated (#38142) 2024-01-25 11:55:50 -05:00
Kyle Doherty
94f10ed175 remove extra border from recipient picker in dash subs (#38131) 2024-01-25 11:47:47 -05:00
Nicolò Pretto
f56d5118dc Fixes settings that should default to false returning null (#38139) 2024-01-25 18:23:30 +02:00
Alexander Solovyov
8aa801d557 CVE updates: lambdaisland/uri, aws sdk (drop ions), specify guava for googleanalytics (#38118) 2024-01-25 18:55:31 +03:00
Noah Moss
9b371a9cf6 Add :impersonated to the cond in a debug log to fix impersonation on stats (#38134) 2024-01-25 15:49:49 +00:00
Jeff Bruemmer
86b6b0fd60 47.13 (#38133) 2024-01-25 10:36:16 -05:00
Ryan Laurie
3e78dc3ffa Update replay io to 1.7.15 (#38106) 2024-01-25 07:36:22 -07:00
Nick Fitzpatrick
b72bc0eeb0 Load tables when db id is present in data permissions pages, e2e test (#37860)
* Load tables when dbid is present in data permissions pages, e2e test

* run prettier

* cleanup. Fixing #37811

* remove undeeded awaits
2024-01-25 09:35:37 -04:00
Nemanja Glumac
e322fc8e25 Fix broken Audit overview page (#38125)
* Revert "Remove internal query check (#37587)"

This reverts commit 16aa9974fb.

* Add a comment

Explains why the guard against `internal` queries is needed here.
2024-01-25 13:54:26 +01:00
Oleg Gromov
6955751aac Move the "remove" button to the sidebar footer (#38050)
* Convert Sidebar to TSX
* Move remove button to the sidebar footer
* Change styles to styled components
* Fix tests
2024-01-25 12:52:12 +00:00
Kamil Mielnik
0511c9c21d Repro #36122 - Table Metadata having 2 foreign keys from the same table pointing to the same key cause implicit joins to only show 1 (#38085)
* Add a repro for 36122

* Improve assertions
2024-01-25 18:38:06 +07:00
Uladzimir Havenchyk
8de2a873b6 Fix e2e test to verify that the filter is applied to twice summarized question (#38091) 2024-01-25 13:56:48 +03:00
Nicolò Pretto
e254ecdb78 add ENV to log snowplow events (#37915)
* console log snowplow events

* wraps it in a env var to not spam the console

* remove try catch now that's under a flag

* moved reading the env to env.js
2024-01-25 11:49:56 +01:00
Mahatthana (Kelvin) Nomsawadi
a504c8b87a Fix dashboard parameter values in embed preview not working (#37972)
* Fix dashboard parameter values in embed preview not working

* Fix iframe rerendering unnecessarily

* Add E2E reproduction test

* Prevent iframe from rerendering unnecessarily
2024-01-25 09:37:24 +00:00
Kamil Mielnik
1cf1923294 Fix - Flaky QueryBuilder.unit.spec.tsx
Split QueryBuilder.unit.spec.tsx into QueryBuilder.beforeunload-events.unit.spec.tsx, QueryBuilder.unsaved-changes-warning.unit.spec.tsx & test-utils.tsx (#38032)
2024-01-25 14:11:36 +07:00
bryan
0e88f8eeaa Malli defn improvements: print the incorrect value in the error (#38062)
* adds info about what value validate got to the exception message

* test fixups

* fix the other test

* remove inline def
2024-01-24 17:33:07 -06:00
Raphael Krut-Landau
86cea6c5bf Initial tidying before putting models on the Browse Data page (#38107)
* Port BrowseHeader to tsx

* Use generic type with useSearchListQuery

* Allow the query to be specified in setupDatabasesEndpoints

* Port EmptyState to tsx

* Correct type in FilterableTree

* Remove unneeded props
2024-01-24 23:15:47 +00:00
Jeff Bruemmer
67605d99c0 docs - api keys (#37668) 2024-01-24 22:29:56 +00:00
Jeff Bruemmer
6fa6db7b0d docs - account for case when ordering endpoint links (#37588) 2024-01-24 16:38:19 -05:00
Braden Shepherdson
3fcbe80813 Handle multiple date filters for the same template tag (#38070)
This regressed in 48 - it only works when either none of the
several filters has a value, or when all of them do.

This PR restores the 47 behavior: whatever subset of the filters have
values (including defaults) will be used, and the others are ignored.

The fix is on the BE but the change actually occurred in the FE -
previously only those parameters with values were sent in the request.
We might want that FE behavior back, but the new BE logic should work
either way.

Fixes #38012.
2024-01-24 15:45:55 -05:00
Jerry Huang
170dee2f5d Add personal-only to collection endpoint (#37608)
* add personal-only to collection endpoint

* address some comments

* fix test

* fix select-collections test

* Update src/metabase/api/collection.clj

Co-authored-by: bryan <bryan.maass@gmail.com>

* Update src/metabase/api/collection.clj

Co-authored-by: bryan <bryan.maass@gmail.com>

* address comments

---------

Co-authored-by: bryan <bryan.maass@gmail.com>
2024-01-24 11:18:53 -08:00
Oleg Gromov
8f20b25900 Remove the newline icon from the parameter value widget (#38086) 2024-01-24 17:48:53 +00:00
Denis Berezin
8f0a57ba47 Add code diff logic and switch to preview mode (#37155)
* Migrate EmbedModalContent to TS

* Add basic UI changes to Embed modal

* More styling

* Add more styling

* Self review fixes

* Self review fixes

* Fix action button

* Fix unit tests

* Fix e2e tests

* Fix e2e tests

* Code review and design fixes

* Fix unit test

* Add Parameters tab text diff and switch to preview

* Add code diff display logic for appearance tab

* Self review fixes

* Fix e2e tests

* Button text hotfix

* Move state to component, fix diff

* Review fixes, action buttons refactor

* Implement new code diff

* Fix text highlight, fix unit tests

* Code review fixes

* Design review fixes

* New code diff highlight UX

* Remove folding

* Change code diff logic, add automatic client code switch

* Fix code highlight logic

* Add unit tests

* Fix some e2e tests

* Fix e2e tests

* Fix code highlight, parameters diff

* Add code highlight on locked parameter value change

* Add more tests

* Review fixes

* Refactor unit tests

* Rollback preview tab remove, add utm tags

* Fix prettier

* Add interactive modal header with hover

* Review fixes

* Review fixes
2024-01-24 17:34:17 +00:00
Oisin Coveney
512d30444d Convert CopyButton to typescript (#37933) 2024-01-24 08:06:58 -08:00
Romeo Van Snick
2aba403b65 Debounce autocomplete (#37852)
* Move _lastAutocomplete to a variable in closure

* Debounce the initial autocomplete

* Add e2e tests

* Fix typo in test case

Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>

* Remove async from 2e2 tests

* Fix wording of comment

* Avoid casting in lastAutoComplete

* Clarify comment in skip condition for initial autocomplete

* Remove outdated comment in e2e test

* Describe problem in filename, not assertion

* Use early return instead of skip variable

* Pass results from last autocomplete to ace

* Actually use last autocompletions result

* Detect the first autocomplete without looking at the actual prefix

* Add test for backspacing to one character in native editor

* Rename resultsForAce to prepareResultsForAce

* Avoid running autocompleter with prefix of length 1

* Remove unnecessary fallback

Co-authored-by: Uladzimir Havenchyk <125459446+uladzimirdev@users.noreply.github.com>

---------

Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>
Co-authored-by: Uladzimir Havenchyk <125459446+uladzimirdev@users.noreply.github.com>
2024-01-24 16:51:54 +01:00
Denis Berezin
25cd3c4f54 Draft sdk structure 2024-01-24 22:36:13 +07:00
Ryan Laurie
902733eb0a Zaycev/202401 fix test upload action (#38067)
Co-authored-by: Vladimir Zaytsev <vladimir@trunk.io>
2024-01-24 07:47:10 -07:00
Chris Truter
4c79e00260 Reapply "Add validation for remaining setting types (#37519)" (#38031)
This reverts commit d78f324c60, which reverted 7b0a906ab9.
2024-01-24 20:51:37 +07:00
Uladzimir Havenchyk
e58e035105 [QB] Add e2e test for previously broken SumIf and CountIf functions in custom expressions (#38082)
* Add repro for aggregation with SumIf and CountIf

* Decrease typing delay

* Update e2e/test/scenarios/question/notebook.cy.spec.js

Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>

---------

Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>
2024-01-24 13:23:29 +00:00
Nemanja Glumac
3e4a40ee50 [MLv2] Migrate isEditable method to MLv2 (#37886)
* Migrate structured query isEditable method to MLv2

* Migrate all `isQueryEditable` references to MLv2

* Remove `isEditable` methods altogether

* Fix failing unit test

* [MLv2] Rewrite `QuestionDataSoruce` FE unit test (#38058)

* Rewrite `QuestionDataSoruce` FE unit test

* Remove unused parameter

* Construct empty metadata instance as a fallback
2024-01-24 13:49:01 +01:00
Anton Kulyk
003cad0098 Optimize MLv2 usage in parameters auto-wiring code (#38046) 2024-01-24 12:40:29 +00:00
Kamil Mielnik
eeacd7b076 Add stress testing workflow for unit tests (#38081)
* Add Unit Test Stress Test Flake Fix workflow

* Add "frontend" prefix to the workflow to disambiguate between backend and frontend
2024-01-24 09:37:34 +00:00
Nemanja Glumac
a5f28f0447 [MLv2] Update metadataProvider type (#38068)
This is a follow-up after #38011.
See this comment: https://github.com/metabase/metabase/pull/38011#discussion_r1462885451
2024-01-24 08:23:05 +01:00
Nemanja Glumac
3342357531 Upgrade jsrsasign to v11.0.0 (#38075)
Resolves https://github.com/metabase/metabase/security/dependabot/130
2024-01-24 06:35:51 +00:00
Chris Truter
fd9d5c9bcc Disable auditing when site-uuid nonces are initialized (#38027) 2024-01-24 08:13:25 +02:00
Chris Truter
fa9868c66b Improve documentation and safety around new setting arguments (#38060) 2024-01-24 07:50:55 +07:00
Nemanja Glumac
4e4fa5e1a3 Revert Trunk upload (#38066)
* Revert "Fix trailing whitespace (#38057)"

This reverts commit 1de0326c04.

* Revert "Add upload test results to Trunk (#37490)"

This reverts commit a36347a177.
2024-01-23 22:03:51 +00:00
Nemanja Glumac
1de0326c04 Fix trailing whitespace (#38057) 2024-01-23 12:54:08 -08:00
Matt Matheson
a36347a177 Add upload test results to Trunk (#37490) 2024-01-23 19:44:48 +01:00
Tim Macdonald
4046809161 Fix one flaky [SparkSQL?] fingerprinting test (#37853)
* Fix flake in fingerprint test:

```
FAIL in metabase.sync.analyze.fingerprint-test/fingerprint-test (fingerprint_test.clj:287)

:sparksql
 Fingerprints should actually get saved with the correct values Text fingerprints
expected: {:global {:distinct-count 100, :nil% 0.0},
           :type {:type/Text {:average-length #<Fn@2ee5402f metabase.sync.analyze.fingerprint_test/fn__139755[fn/fn]>,
                              :percent-email 0.0,
                              :percent-json 0.0,
                              :percent-state 0.0,
                              :percent-url 0.0}}}
  actual: nil
```

* Typo fix
2024-01-23 17:12:24 +00:00
Sloan Sparger
ba0997dcc3 Navbar Improvements: Updated UI (#37821) 2024-01-23 10:02:05 -06:00
Ryan Laurie
0cfa393d0b Test display icons on search questions (#37839) 2024-01-23 08:35:55 -07:00
Braden Shepherdson
d83c863a11 Don't try to compute query-hash for cards without queries (#38007)
Fixes #37345.
2024-01-23 08:59:56 -05:00
Chris Truter
d2113a27e0 Fix potential deadlock when loading feature flags
Fixes https://github.com/metabase/metabase/issues/38009

### Description

This makes the feature flag loading code more robust by making the function re-entrant. To understand how this function could deadlock before, see the description in https://github.com/metabase/metabase/pull/38027.

It works by ensuring that the call to initialize the nonce comes from the same thread that initially locked on fetching the tokens.

There is a subtle behavior change here - was allow for a 10s timeout on each call individually now. Since it is unlikely that both endpoints will timeout consecutively, and the combined wait time is still fairly short, I think this is OK.

### How to verify

You can use the same steps as https://github.com/metabase/metabase/pull/38027, either of these PRs are sufficient to fix the bug.
2024-01-23 15:59:33 +02:00
Oleg Gromov
926b04a1d5 HK: remove useCallback in WidgetStatusIcon (#38006) 2024-01-23 10:30:27 +00:00
Nemanja Glumac
fb696adfc8 Make databaseId potentially nullable (#38011)
Resolves #38010
2024-01-23 06:21:46 +01:00
Mark Bastian
75f2dc1a01 Formatting for time types (#37942)
* Formatting for time types

Currently, the frontend does not do any special formatting for time of day types. These are always formatted as 12 hour AM/PM times. This PR adds a new function to `frontend/src/metabase/lib/formatting/time.ts`, `formatTimeWithOptions`, that applies user-defined formatting to the time. Previously, `formatTime` was called, which takes no formatting options, so none can be applied.

Fixes #11398

* e2e tests for time of day formatting.

* Update frontend/src/metabase/lib/formatting/time.ts

Co-authored-by: Emmad Usmani <emmadusmani@berkeley.edu>

* Replacing formatTime with formatTimeWithOptions

This replaces uses of `formatTime` with `formatTimeWithOptions`, updates unit tests, removes references to `formatTime`, and incorporates some code suggestions.

* Unit tests

* Adding test id for field info popover.

* Refactoring `formatTimeWithOptions` to `formatTime`

* Moved `TimeOnlyOptions` interface to formatting types and made it an ancestor of `OptionsType`

---------

Co-authored-by: Emmad Usmani <emmadusmani@berkeley.edu>
2024-01-23 04:10:43 +00:00
Cal Herries
dbb4cc7d30 Fix BE flake: metabase.driver.bigquery-cloud-sdk-test/query-drive-external-tables (#37996) 2024-01-23 10:39:18 +07:00
metamben
42b48cb65e Return “contains” and “does-not-contain” for comment/description (#37900)
Fixes #36856.
2024-01-23 01:56:14 +03:00
Aleksandr Lesnenko
26e5ab5f28 fix auto y-axis split on native queries (#37909)
* fix auto y-axis split on native queries

* specs
2024-01-22 13:38:53 -03:00
Nemanja Glumac
17b5f18113 Fix wrong target prop type on DashCardParameterMapper (#37966)
* Fix wrong `target` prop type on `DashCardParameterMapper`

* Remove unneeded prop from the test setup
2024-01-22 16:35:58 +00:00
bryan
7db8305146 Fix search input surfacing views powering audit-db (#37929)
* Filter out audit tables in search results

* add test
2024-01-22 10:04:21 -06:00
Anton Kulyk
0b03d12d4c Tweak trend charts static viz look (#37869)
* Use ASCII arrow characters instead of SVG icons

* Increase comparison text font size
2024-01-22 15:27:52 +00:00
Chris Truter
9184ddaa7e Fix salt in pulse unsub hash (#37817)
* Fix salt in pulse unsub hash
* Workaround for read-only settings not supporting temp overrides yet
2024-01-22 13:55:08 +00:00
Chris Truter
af800eba49 Fix link to blog post (#37968) 2024-01-22 08:11:13 -05:00
Chris Truter
59f8fe35f3 Fix race-condition that could revert (un)subscriptions (#37954)
Ensure we read and update nested JSON in a transaction
2024-01-22 11:16:26 +00:00
Chris Truter
15c1274290 Remove obsolete test for exported settings (#37956) 2024-01-22 11:01:27 +00:00
Chris Truter
528b9c59c2 Improve safety of lazily initialized settings (#37849)
- Introduce an "init" hook for application settings.
- Add guards against introducing race conditions again in other ways.
- Fix the usage of hygienic scope macros with read only settings.
- Lots of misc improvements to settings API and implementation.

This init hooks better ergonomics, and protects against race conditions. 
The previous pattern of calling setters inside getters almost caused a P0. 

See https://github.com/metabase/metabase/issues/37801.
2024-01-22 10:26:41 +00:00
Nemanja Glumac
2cd8c5fa41 Migrate isNative to MLv2 (#37805)
* Migrate Question `isNative` and `isStructured` methods to MLv2

* Mark methods as deprecated

* Add the guard to the `isNativeDashCard` util

* Add additional guard to the `buildFieldFilterUiParameter` helper

* Update all `isNative` method instances to MLv2

* Fix the negation logic 🤦

* Remove `isNative()` method altogether

* Simplify the `shouldResolveFkField` check

Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>

* Remove explicit Boolean conversion

* Simplify conditional logic for `getTargetsForQuestion`

---------

Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>
2024-01-22 08:44:29 +00:00
Ngoc Khuat
9723e461c4 RFC: kondo lint to enforce naming convention for thread not safe defn/defmacro in tests (#37126) 2024-01-22 08:40:49 +00:00
adam-james
cbbc9c6410 Disallow Filter labels to be any variation of the word 'tab'. (#37905)
To prevent ambiguous dashboard URLs, labels should not be called 'tab'.
2024-01-19 16:08:21 -08:00
Mark Bastian
6372547989 Enabling dragging of long-named TabButtons (#37910)
* Enabling dragging of long-named TabButtons

The primary change needed to support rearranging of tabs with super long names is the to shorten the names only when dragging. This was achieved by exposing the `isDragging` prop of the `useSortable` hook in the `RenameableTabButtonStyled` component. The label of this component is dynamically shortened if it is very long on a drag operation by the following logic and function:

```
// Update the label prop when dragging
label={isDragging ? dragLabel(label) : label}
```

The `dragLabel` function is as follows:
```
  const dragLabel = (s: string) => {
    if (s.length < 20) {
      return s;
    } else {
      return `${s.slice(0, 17)}...`;
    }
  };
```

The other change needed to support e2e testing for this operation was the addition of the `MouseSensor` hook to the DnDContext. See [this issue comment](https://github.com/clauderic/dnd-kit/issues/208#issuecomment-824469766) for explanation.

Once that change was in place it was possible to do a drag and drop rearrange test in the "should allow me to rearrange long tabs (#34970)" spec.

This test:
- Creates a dashboard with 3 tabs
- Ensures their order
- Gives the last tab a super long name that would not be rearrangeable before fix
- Drags that tab to the first position
- Saves the dashboard
- Asserts the new tab order is saved

Fixes #34970

* Fixing type from T to unknown to satisfy the type of the render function in TabButton.unit.spec.ts

* Fixing type from T to any to satisfy the type of the render function in TabButton.unit.spec.ts

* Fixing divergent tests

The tests to ensure DnD works required the addition of the `mouseSensor` in TabRow.tsx. This, in turn, broke the tests in DashboardTabs.unit.spec.tsx. Adding in the `activationConstraint: { distance: 10 }` prop to the mouseSensor fixed the DashboardTabs.unit.spec.tsx tests, but broke the DnD tests. Based on the docs [here](https://docs.dndkit.com/api-documentation/sensors/mouse) it looks like you need to move a "distance, in pixels, by which the mouse needs to be moved before a drag start event is emitted." So, the DnD test in tabs.cy.spec.js added an addtional mousemove trigger of 11 pixels to activate the mouseSensor. Yeah, it totally makes sense. 😜🤯💢😡😥

* prettier
2024-01-19 20:17:10 -03:00
metamben
16002d81ac Add (legacy) expression conversion tests (#37826)
Part of #37173.
2024-01-19 22:38:41 +00:00
Jeff Bruemmer
03a60034d5 docs - update field types (#37662) 2024-01-19 16:49:17 -05:00
Oisin Coveney
b4c9d98b05 [Epic #35961] Milestone 4 - Add Legalese Step (#37006)
Co-authored-by: Noah Moss <32746338+noahmoss@users.noreply.github.com>
2024-01-19 11:37:18 -08:00
Jeff Bruemmer
6baae6ae96 docs - various updates (#37892) 2024-01-19 14:36:34 -05:00
Uladzimir Havenchyk
109f330395 Replace brush filters with MLv2 alternatives (#37293)
* Cleanup component

* Replace filters with MLv2 methods

* Cleanup unused functions

* Make filter work

* Make filter work

* Fix rebase issues

* Update ML methods usage

* pass params in the correct order

* pass params in the correct order

* Fix argumetns order

* Remove duplicated test and unskip correct one

* [Leaflet] Replace brush filter with MLv2 alternative (#37295)

* Update ML methods usage

* Fix argumetns order

* Unskip test

* Pass metadata

* Pass metadata
2024-01-19 19:08:55 +00:00
Nick Fitzpatrick
c6a4f165d2 Render Auth Cards when env var is set (#37894)
* add force render to auth settings, read only auth card

* adding footer prop to auth cards, force render differt auth cards
2024-01-19 14:55:42 -04:00
Nemanja Glumac
a5f50f761b Revert "Remove unused code from QuestionDataSource (#37691)" (#37918)
This reverts commit a5dd444483.
2024-01-19 19:03:51 +01:00
Braden Shepherdson
7837c7106b [MLv2] Add aggregation-column and breakout-column (#37873)
These are helpers for going from an aggregation or breakout
clause to the relevant `:metadata/column`. (Nil for top-level
aggregations like `:count`.)

Fixes #37120.
2024-01-19 13:02:26 -05:00
Cal Herries
9b9a921401 Fix flaking bigquery dataset-filtering-test (#37913) 2024-01-19 19:29:10 +02:00
Braden Shepherdson
e51f91da74 [MLv2] Add isTemporalExtraction flag to displayInfo (#37889)
That applies to both freestanding temporal buckets and to breakouts with
`:temporal-unit` set.

Fixes #36978.
2024-01-19 17:19:53 +00:00
Braden Shepherdson
9b10e888f7 [MLv2] Properly match aggregations across versions of a query (#37867)
Because aggregation refs are based on `:source-uuid` they are not
comparable between queries, which breaks some logic to find columns
added and removed between two versions of a query.

This adds a fallback based on the newly added `:source-name` option on
aggregation refs.

Fixes #37851.
2024-01-19 17:04:56 +00:00
Nemanja Glumac
7ecb298535 [MLv2] Introduce a queryDisplayInfo abstraction (#37862)
* Introduce a `queryDisplayInfo` abstraction

* Address review comments

Call `ML.display_info` directly in a new abstraction,
and remove the additional function overload.

* Tidy up comments
2024-01-19 16:44:18 +01:00
Cam Saul
784759be82 Register keywords defined by mr/def for LSP (#37616) 2024-01-19 17:09:47 +03:00
Anton Kulyk
74155034b3 Turn Dashboard into a functional component (#37757)
* Turn `Dashboard` into a functional component

* Fix loading

* Fix loading

* Properly type `fetchDashboard` result

* Update `tabHasCards` check

* Group data fetching `useEffects` into one
2024-01-19 12:08:28 +00:00
Ngoc Khuat
78f7171a02 Add unique constraint on databasechangelog if it's not existed (#37846) 2024-01-19 19:01:22 +07:00
Anton Kulyk
46fb2d9468 Convert top-level dashboard components to TypeScript (#37703)
* Convert `DashboardApp` to TypeScript

* Convert `Dashboard` to TypeScript

* Convert `DashboardGrid` to TypeScript

* Convert `DashboardHeader` to TypeScript

* Bind `setDashboardAttribute` method

* Fix adding dashcards

* Fix question's "Add to dashboard" flow

* Remove `fetchCardData` prop from `DashCard` (not used)

* Make `editingTitle` prop optional

* Move `fetchPulseFormInput` to `DispatchProps`

* Fix TODO types in `DashboardGrid`

* Fix error handling

* Replace `any` with `unknown`

* Fix `any` in `DashboardGrid`

* Fix `onMainScroll` type
2024-01-19 11:31:17 +00:00
Cal Herries
6b4631a9ee Fix append CSV missing column in CSV file error string (#37876) 2024-01-19 09:29:51 +02:00
Cam Saul
f70cada723 Support legacy metadata and raw JS Dates for brush filter helper functions (#37841)
* Remove references to shared/ directory which no longer exists

* Update shadow-cljs and pinned cider/nrepl versions

* Support legacy metadata and raw Dates for brush filter helper functions

* Fix fn name

* Apply suggestions from code review

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>

---------

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>
2024-01-18 23:59:05 +00:00
metamben
2dbc078326 Improve with-expression-name test coverage (#37888)
Part of #37173.
2024-01-19 02:07:26 +03:00
Jerry Huang
a9b9c0fe7d Add user-provisioning-enabled? setting and logic (#37770)
* add user-provisioning code

* sort namespace

* fix linter

* fix linter

* swap to ee

* fix logic

* add tests

* address comments

* fix linter

* update tests, address comments
2024-01-18 14:45:00 -08:00
lbrdnk
bbf79d53fd Add :timezone key to database metadata (#36413)
* Add timezone to database metadata

* Use UTC as _user timezone_ for snowflake driver

* Use user timezone as db-default-timezone

* Update oracles unprepare-value to handle Z UTC

* Update `driver/db-default-timezone :h2` to use jvm timezone

* Update containers timezone to match instance timezone and tests

* Update modules/drivers/oracle/src/metabase/driver/oracle.clj

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>

* Make unprepare symmetric for offset and zoned datetime

---------

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>
2024-01-18 21:49:39 +01:00
Jacob Joseph
595785b92c Update environment-variables.md (#36231)
Added  MB_JDBC_DATA_WAREHOUSE_UNRETURNED_CONNECTION_TIMEOUT_SECONDS to docs
2024-01-18 15:47:56 -05:00
Noah Moss
e512233f8c Exclude :card from the parameter types which require defaults to be considered fully parameterized (#37764) 2024-01-18 15:02:23 -05:00
Cal Herries
e925e2cd7f Uncomment audit-v2-views-test except the part that flakes (#37883) 2024-01-18 19:46:53 +00:00
John Swanson
3982a6d1e8 Add a banner to the top of locales.clj (#37877)
Just add a comment warning that the file is autogenerated and not to
edit it by hand.
2024-01-18 10:57:36 -08:00
Braden Shepherdson
162349cf64 [MLv2] Look up FK columns in visible-columns, not metadata (#37771)
Models can override the `:id` and `:fk-target-field-id` of a column, and
can even lie and treat a quantity as a FK. Therefore we have to use the
query's view of the column and not the global field from the metadata.

This is a speculative fix for #36400, which I can't reproduce locally.
2024-01-18 12:35:35 -05:00
Nicolò Pretto
7634fad6b5 remove @flaky tag for a test that is not failing anymore (#37859) 2024-01-18 18:24:05 +01:00
Sloan Sparger
f774267f32 Add back auto-following logs on Admin Logs page (#37724) 2024-01-18 10:59:34 -06:00
Oleg Gromov
888fb7bf28 Refactor WidgetStatusIcon (#37858) 2024-01-18 16:51:09 +00:00
Sloan Sparger
8a75ea1e9e Improve admin page layout (#37706) 2024-01-18 09:55:48 -06:00
Nemanja Glumac
1aa7ae316f Remove redundant (and wrong) hasData check from ViewHeader component (#37566)
- Remove redundant checks
    - `canEditQuery` shouldn't determine whether or not a Save button should be visible; It only marks it as disabled or not.

- Update a related E2E test
    - This commit makes the test more explicit and more understandable.
    - Fix the test assumption
        - In all other cases we show the disabled Save button to the "nodata" user. It was only in this test that we wrongly asserted that the button doesn't exist at all.

* Deprecate `hasData()` methods on StructuredQuery and NativeQuery

Resolves #37516
2024-01-18 16:50:06 +01:00
Serge Klochkov
3102b188d2 Add align-temporal-unit-with-param-type-and-value multimethod (#37813)
* Add `align-temporal-unit-with-param-type-and-value` multimethod

* Fix tests and add a changelog entry

* Update the method docs

* Rearrange the default methods call order

* Revert formatting changes

* Move the clj-kondo ignore

* Update docs/developers-guide/driver-changelog.md

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>

---------

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>
2024-01-18 16:12:22 +01:00
Nick Fitzpatrick
2cdb3c6324 don't dismiss search unless location pathname changes (#37669)
* don't dismiss search unless location pathname changes

* Only dismiss when location changes using replace
2024-01-18 10:53:05 -04:00
Nemanja Glumac
03d6dba46e Migrate _serializeForUrl method to MLv2 (#37632)
* Migrate `_serializeForUrl` method to MLv2

* Use MLv2 function to compare queries

---------

Co-authored-by: Alexander Polyankin <alexander.polyankin@metabase.com>
2024-01-18 10:34:53 +00:00
Oleg Gromov
035d478c3b Add required field to the template tag parameter (#37800) 2024-01-18 09:27:38 +00:00
Kamil Mielnik
b46d159a14 [MLv2] [FE] Migrate supportsImplicitActions (#37570)
* Move hasAnyClauses from steps.ts to query-utils
- introduce query-utils file to avoid circular dependencies

* Update comment

* Update hasAnyClauses usage in Question

* Rename hasAnyClauses to hasAnyClausesAtStage, introduce new hasAnyClauses

* Rename query-utils.ts to stages.ts

* Move stage-related utils from query.ts to stage.ts

* Drop hasAnyClauses, rename hasAnyClausesAtStage to hasAnyClauses

* Rename stages.ts to stage.ts to make it consistent with stage.cljc

* Update function name

* Format code

* Update comment

* Add is-stage-empty to MLv2

* Add Lib.isStageEmpty and replace hasAnyClauses with it

* Fix typo in comment

* Update comment

* Update is-empty-clause to list all checked clauses

* Improve readability

* Export is-stage-empty via lib.core

* Revert "Fix typo in comment"

This reverts commit 286d412a5a.

* Update comment

* Use implicit way of checking clauses presence in query

* Inverse and rename is-stage-empty to has-clauses

* Update comment

* Fix drop-stage-if-empty

* Use seq

* Cast to boolean

* Update src/metabase/lib/stage.cljc

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>

* Add question mark to has-clauses

---------

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>
2024-01-18 08:38:50 +00:00
Uladzimir Havenchyk
62728b8f4c Handle an error of building UI parameters during dashboard fetching (#37790) 2024-01-17 21:50:09 -03:00
Ryan Laurie
c1e4d51517 API Keys UI follow-ups (#37618)
* ui followups for api keys

* make auth cards take up less vertical space

* filter groups users
2024-01-17 16:55:37 -07:00
Ryan Laurie
d3796f6082 Update database writability on upload settings change (#37720) 2024-01-17 15:13:10 -07:00
Case Nelson
9e721c3723 [MLv2] Add matrix tests for filter functions (#37759) 2024-01-17 17:01:09 -05:00
Braden Shepherdson
605eaf64b0 [MLv2] Make query= treat missing :base-type as matching (#37727)
Fixes #37659
2024-01-17 21:58:52 +00:00
Ryan Laurie
17813df17c Fix permissions breadcrumbs for schemaless dbs (#37733)
* fix breadcrumbs for schemaless dbs

* fix types
2024-01-17 14:31:41 -07:00
Ryan Laurie
56c70724dc observe redirect param even when logged in (#37750) 2024-01-17 14:31:21 -07:00
Ryan Laurie
45a03e00a1 Remove unused clojure release code 🥳 (#37822) 2024-01-17 14:30:55 -07:00
Luis Paolini
62f11c505a Add SNI check env var docs (#37793)
* Add SNI check env var

* Update environment-variables.md

* Update docs/configuring-metabase/environment-variables.md

Co-authored-by: Jeff Bruemmer <jeff.bruemmer@gmail.com>

---------

Co-authored-by: Jeff Bruemmer <jeff.bruemmer@gmail.com>
2024-01-17 18:00:11 -03:00
adam-james
0e971175ae Use :skip-results-metadata? true in pulse query execution (#37762)
* Use :skip-results-metadata? true in pulse query execution

Without this, the results-metadata middleware ends up replacing a model's metadata.

Using the correct flag causes that middleware to just be skipped, preserving whatever metadata already exists on the model.

* Add a testing form to explain the assertion as clearly as possible.
2024-01-17 12:16:44 -08:00
Mahatthana (Kelvin) Nomsawadi
d8696945a8 Attempt to fix pivot table not collapsing on public/static embedding (#37429)
* Attempt to fix pivot table not collapsing on public/static embedding

* remove extending dataset result with viz settings

* spec

---------

Co-authored-by: Aleksandr Lesnenko <alxnddr@gmail.com>
2024-01-17 17:14:15 -03:00
Nemanja Glumac
c00349dc58 Fix editable? function so that it respects native write permissions (#37788)
* Fix `editable?` source logic

The logic now takes into account whether or not a database
has native write permissions.

* Fix related metadata test

* DRY test code

* Set the test database metadata native permissions to true

* Mock the database native permissions in test

* Add issue reference to the test

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>
2024-01-17 20:46:56 +01:00
metamben
80017100f8 Add test for available-metrics and available-segments (#37767)
Part of #37173.
2024-01-17 22:30:34 +03:00
Jeff Bruemmer
09dc45154b docs - mysql version note (#37761) 2024-01-17 13:32:25 -05:00
Luis Paolini
46491833e5 Rename the jetty-insecure env var (#37791)
* Rename the env var

* env var rename
2024-01-17 15:14:56 -03:00
Case Nelson
bbafcbb034 [MLv2] Fix column-group display-name (#37760)
Column group display names need to take fk-reference-name into account
and fk-reference-name no longer needs to be exposed through
display-info.

Also add an implementation of display-name for column-group.
2024-01-17 11:03:12 -07:00
Cal Herries
d78f324c60 Revert "Add validation for remaining setting types (#37519)" (#37809) 2024-01-17 17:50:25 +00:00
Oisin Coveney
c42aa27084 Modify Embedded Analytics UTM codes (#37614) 2024-01-17 09:16:49 -08:00
Cal Herries
6863484850 Fix e2e test for serdes dashcardseries (#37747) 2024-01-17 19:13:55 +02:00
Jerry Huang
519e2d3279 Hydrate display for cards in search (#37755)
* hydrate display

* fix tests
2024-01-17 16:29:11 +00:00
Alexander Solovyov
028dcc1846 update malli and jsoup (to get rid of Snyk warning) (#37789) 2024-01-17 17:52:08 +03:00
Cal Herries
c4b7c3fc6c Skip listing tables for bigquery driver/can-connect? check (#37787) 2024-01-17 14:33:02 +00:00
Cal Herries
a8203762c8 Comment out flaky audit-v2-views-test (#37796) 2024-01-17 14:22:47 +00:00
Nemanja Glumac
2455a04b27 [MLv2] Update types to accommodate QueryDisplayInfo (#37786)
* Update types to accommodate `QueryDisplayInfo`

* Add a JSDoc comment to the query displayInfo overload

* Address review comments

Mark the first two parameters with an underscore.

* Address outstanding review comments
2024-01-17 12:54:33 +00:00
Oleg Gromov
b7a5c4eeec HK: remove noPopover and unnecessary function from ParameterValueWidget (#37736) 2024-01-17 12:53:01 +00:00
Alexander Polyankin
590948ab17 Migrate click behavior column computation to MLv2 (#37438)
* Extract click targets for native

* Add checks for mbql queries

* Add isa method

* Update styling

* Add dimensions handling for native questions

* Add a workaround to get proper columns

* [MLv2] Add `legacy-column->metadata` for converting `DatasetColumn`

The query and stage are unfortunately required to correctly handle
aggregation references.

Note that the JS version of this name is `legacy_column__GT_metadata`,
with the double underscore.

* Add TS wrapper

* fixup! Merge remote-tracking branch 'origin/mblib-dataset-column-conv' into click-behavior-draft

* Fix another test

* Fix test

* Use correct query in filtering logic

* Fix typecheck

* Make code cleaner

* Make question a mandatory argument

* Correct types

* oops

* [MLv2] Add `legacy-column->metadata` for converting `DatasetColumn`

The query and stage are unfortunately required to correctly handle
aggregation references.

Note that the JS version of this name is `legacy_column__GT_metadata`,
with the double underscore.

* Add TS wrapper

* [MLv2] Add `compatible-type?` and JS-friendly wrapper

`metabase.lib.types.isa/compatible-type?` returns true if the two
columns belong to the same type family (strings, numbers, temporal) or
the type of one column `isa?` subtype of the other.

The `lib.js/compatible-type?` wrapper can handle JS `DatasetColumn`
values as well as CLJS `:metadata/column` ones.

Fixes #37501. (Unblocks #37328.)

* Give a try assignable

* [MLv2] Add `compatible-type?` and JS-friendly wrapper

`metabase.lib.types.isa/compatible-type?` returns true if the two
columns belong to the same type family (strings, numbers, temporal) or
the type of one column `isa?` subtype of the other.

The `lib.js/compatible-type?` wrapper can handle JS `DatasetColumn`
values as well as CLJS `:metadata/column` ones.

Fixes #37501. (Unblocks #37328.)

* Address recent changes

---------

Co-authored-by: Uladzimir Havenchyk <uladzimir.dev@gmail.com>
Co-authored-by: Uladzimir Havenchyk <125459446+uladzimirdev@users.noreply.github.com>
Co-authored-by: Braden Shepherdson <braden@metabase.com>
Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>
2024-01-17 11:33:25 +00:00
Anton Kulyk
035404970c Trend chart improvements (#37038)
* Update Trend chart copy for special cases (on frontend) (#35184)

* add computeTrend

* fix unit test

* fix e2e test

* explicitly fallback to day unit if backend doesn’t provide one

* fix empty data cases

* rename function parameters

* correct and simplify computeChange function

- when prevVal < 0 and nextVal < 0, it would return the wrong percentChange. (nextVal - prevVal) / Math.abs(prevVal) fixes this issue.
  - i.e. prevVal = -5, nextVal = -10 -> computeChange(-5, -10) -> computeChange(--10, --5) -> -50% but we should it expect to be -100% since it dropped by a factor of Math.abs(prevVal)

* refactor PREVIOUS_VALUE options

* correct and simplify computeChange further

(-) -> (0) should be + increase (our end case already accounts for this behavior)

* update unit tests to reflect correctness changes to computeChange

* refactor for readability

* refactor to use isEmpty instead of ==/!= null

* refactor variable names for readability

* refactor nested ternaries into function

* refactor for readability

* refactor variable names

* re-use end of array index variable

* re-word comments

* refactor consumers based on return variable re-naming

* add missing test cases

* nit refactor

* re-arrange functions for readability

* truncate prevDate based on nextDate

- if prevDate is same day as nextDate, remove the day, month, and year from the comparisonPeriodStr
- if prevDate is same year as nextDate, remove the year from the comparisonPeriodStr

* fix comment

* fix test

* instead of ↓ and ↑ symbols, use icon names

* fix night mode hack

* refactor formatDateTimeRangeWithUnit behavior

- refactor how options.removeDay and options.removeYear work
- reorganize the layout to make the conditional branches easier to see

* fix tooltip styles

* Add tests to cover new options

- options.removeDay
- options.removeYear

* add option descriptors to test string

---------

Co-authored-by: Jesse Devaney <22608765+JesseSDevaney@users.noreply.github.com>

* Trend Charts: Support arbitrary date comparison (#36666)

* add computeTrend

* fix unit test

* fix e2e test

* explicitly fallback to day unit if backend doesn’t provide one

* fix empty data cases

* rename function parameters

* correct and simplify computeChange function

- when prevVal < 0 and nextVal < 0, it would return the wrong percentChange. (nextVal - prevVal) / Math.abs(prevVal) fixes this issue.
  - i.e. prevVal = -5, nextVal = -10 -> computeChange(-5, -10) -> computeChange(--10, --5) -> -50% but we should it expect to be -100% since it dropped by a factor of Math.abs(prevVal)

* refactor PREVIOUS_VALUE options

* correct and simplify computeChange further

(-) -> (0) should be + increase (our end case already accounts for this behavior)

* update unit tests to reflect correctness changes to computeChange

* refactor for readability

* refactor to use isEmpty instead of ==/!= null

* refactor variable names for readability

* refactor nested ternaries into function

* refactor for readability

* refactor variable names

* re-use end of array index variable

* re-word comments

* refactor consumers based on return variable re-naming

* add missing test cases

* nit refactor

* re-arrange functions for readability

* truncate prevDate based on nextDate

- if prevDate is same day as nextDate, remove the day, month, and year from the comparisonPeriodStr
- if prevDate is same year as nextDate, remove the year from the comparisonPeriodStr

* fix comment

* fix test

* instead of ↓ and ↑ symbols, use icon names

* fix night mode hack

* refactor formatDateTimeRangeWithUnit behavior

- refactor how options.removeDay and options.removeYear work
- reorganize the layout to make the conditional branches easier to see

* fix tooltip styles

* Add tests to cover new options

- options.removeDay
- options.removeYear

* add option descriptors to test string

* add support for different trend comparisons

- compare to previous value
- compare to previous period (minute, hour, day, ...)
- compare to X previous periods ago (30 minutes, 6 hours, 3 days, ...)

* refactor + add comments

* only show periodsAgo comparison option if # of selectable periods ago is >= 2

* auto select all text on click in periodsAgo field input

* fix bug caused by upstream date change

- this caused the parser to try to parse an already existing date object when it expected a string timestamp

* prevent accidental button click

-  Since the input field is small, when mouseDown in child and dragged across (to highlight the input text) and outside the input field, it accidentally mouseUps on the button. This causes the button to be considered clicked since the child element is within the parent element.

* fix searching outside of array bounds

* validate scalar.comparisons setting after any query changes

* add ttag for new copy

* clamp search to start of array incase rows contain missing periods

* rename styled components

* fix SmartScalarSettingsWidgets type errors

* change default comparison to previous period (if dateUnit is supplied)

- default to "compare to previous" if no dateUnit is supplied

* leave "X periods ago" setting even if filtered data reduces date range of dataset

* change copy for no comparable value using `compare to previous` comparison

* rename comparison `compare to previous` to `previous value`

* fix type errors

* fix bug if dateUnit is null

* fix bug and move option down

* fix type error

* remove comment

* refactor names

* fix wrong date display

* add tests

* add tests for "compare to previous"

* fix "previous period" tests

* rename COMPARE_TO_PREVIOUS to PREVIOUS_VALUE

- because copy changed, lets change this const name to match it

* default return null if no comparison selected

* remove unused export

* remove unused export on types

* do not hide primary number selector

* fix dateUnit null

* refactor computeTrend

* fix test b/c of refactor

* update computeChange unit tests

* refactor

* improve tests

* refactor tests based on functionality

* fix timezones bug

* reformat tests

* add test cases for invalid settings

* handle invalid comparison types

* fix type errors and rename variables

* hit "Enter" to submit periodsAgo comparison value

* fix timezone bug when comparisons dates are in different time-zones

- different time-zones in this case in daylight savings time
- this was causing two dates to not be the same ONLY b/c there timezone offset was different

* refactor tests

* reorganize SmartScalar file

* rename comparison option name

* fix type

* add unit tests for comparison option functions and comparison validation

* add component tests for SmartScalar

* re-organize tests

* add E2E tests

* use more direct variable

* refactor variable names

* fix translations error

* fix type errors

* update translation strings

* fix dateTime diffing

- see comment in function and tests for more info

* refactor test assertions

* move comparison types to metabase-types/api/visualization-settings

* drop any type

* update native_form type

* remove todo comment

* remove optionality on types

* remove console.error mock

- used for creating tests to sift out repetitive test errors. forgot to remove

* refactor icon check

* Remove CSS class targeting

* relocate props type object

* Remove CSS class targeting

* group smartscalar settings components into their own directory

* refactor component

* refactor tests to use it.each

* use createMockSingleSeries

* use createMockVisualizationSettings

* use createMockColumn

* reorganize code and files

* fix type

* fix i18n translations

* update periods ago value on blur if selected

* fix type error

* Trend Charts: Address Milestone 2 Feedback (#37062)

* add computeTrend

* fix unit test

* fix e2e test

* explicitly fallback to day unit if backend doesn’t provide one

* fix empty data cases

* rename function parameters

* correct and simplify computeChange function

- when prevVal < 0 and nextVal < 0, it would return the wrong percentChange. (nextVal - prevVal) / Math.abs(prevVal) fixes this issue.
  - i.e. prevVal = -5, nextVal = -10 -> computeChange(-5, -10) -> computeChange(--10, --5) -> -50% but we should it expect to be -100% since it dropped by a factor of Math.abs(prevVal)

* refactor PREVIOUS_VALUE options

* correct and simplify computeChange further

(-) -> (0) should be + increase (our end case already accounts for this behavior)

* update unit tests to reflect correctness changes to computeChange

* refactor for readability

* refactor to use isEmpty instead of ==/!= null

* refactor variable names for readability

* refactor nested ternaries into function

* refactor for readability

* refactor variable names

* re-use end of array index variable

* re-word comments

* refactor consumers based on return variable re-naming

* add missing test cases

* nit refactor

* re-arrange functions for readability

* truncate prevDate based on nextDate

- if prevDate is same day as nextDate, remove the day, month, and year from the comparisonPeriodStr
- if prevDate is same year as nextDate, remove the year from the comparisonPeriodStr

* fix comment

* fix test

* instead of ↓ and ↑ symbols, use icon names

* fix night mode hack

* refactor formatDateTimeRangeWithUnit behavior

- refactor how options.removeDay and options.removeYear work
- reorganize the layout to make the conditional branches easier to see

* fix tooltip styles

* Add tests to cover new options

- options.removeDay
- options.removeYear

* add option descriptors to test string

* add support for different trend comparisons

- compare to previous value
- compare to previous period (minute, hour, day, ...)
- compare to X previous periods ago (30 minutes, 6 hours, 3 days, ...)

* refactor + add comments

* only show periodsAgo comparison option if # of selectable periods ago is >= 2

* auto select all text on click in periodsAgo field input

* fix bug caused by upstream date change

- this caused the parser to try to parse an already existing date object when it expected a string timestamp

* prevent accidental button click

-  Since the input field is small, when mouseDown in child and dragged across (to highlight the input text) and outside the input field, it accidentally mouseUps on the button. This causes the button to be considered clicked since the child element is within the parent element.

* fix searching outside of array bounds

* validate scalar.comparisons setting after any query changes

* add ttag for new copy

* clamp search to start of array incase rows contain missing periods

* rename styled components

* fix SmartScalarSettingsWidgets type errors

* change default comparison to previous period (if dateUnit is supplied)

- default to "compare to previous" if no dateUnit is supplied

* leave "X periods ago" setting even if filtered data reduces date range of dataset

* change copy for no comparable value using `compare to previous` comparison

* rename comparison `compare to previous` to `previous value`

* fix type errors

* fix bug if dateUnit is null

* fix bug and move option down

* fix type error

* remove comment

* refactor names

* fix wrong date display

* add tests

* add tests for "compare to previous"

* fix "previous period" tests

* rename COMPARE_TO_PREVIOUS to PREVIOUS_VALUE

- because copy changed, lets change this const name to match it

* default return null if no comparison selected

* remove unused export

* remove unused export on types

* do not hide primary number selector

* fix dateUnit null

* refactor computeTrend

* fix test b/c of refactor

* update computeChange unit tests

* refactor

* improve tests

* refactor tests based on functionality

* fix timezones bug

* reformat tests

* add test cases for invalid settings

* handle invalid comparison types

* fix type errors and rename variables

* hit "Enter" to submit periodsAgo comparison value

* fix timezone bug when comparisons dates are in different time-zones

- different time-zones in this case in daylight savings time
- this was causing two dates to not be the same ONLY b/c there timezone offset was different

* refactor tests

* reorganize SmartScalar file

* rename comparison option name

* fix type

* add unit tests for comparison option functions and comparison validation

* add component tests for SmartScalar

* re-organize tests

* add E2E tests

* use more direct variable

* refactor variable names

* fix translations error

* fix type errors

* update translation strings

* fix dateTime diffing

- see comment in function and tests for more info

* refactor test assertions

* move comparison types to metabase-types/api/visualization-settings

* drop any type

* update native_form type

* remove todo comment

* remove optionality on types

* remove console.error mock

- used for creating tests to sift out repetitive test errors. forgot to remove

* refactor icon check

* Remove CSS class targeting

* relocate props type object

* Remove CSS class targeting

* group smartscalar settings components into their own directory

* refactor component

* refactor tests to use it.each

* use createMockSingleSeries

* use createMockVisualizationSettings

* use createMockColumn

* reorganize code and files

* fix type

* fix i18n translations

* update periods ago value on blur if selected

* fix type error

* rename types

* improve types

* rename function

* improve button styles

* rename component

* remove comments

* use rightIcon prop

* rename style

* refactor click hacks for periodsAgo menu component

* refactor menu change handling

- if menu is closed, submit onChange with the latest edited value.
- if item is simple, submit value itself
- it item is complex, set edited value state as input changes and submit value when committed

* disable invalid typescript error

- error is coming from using typescript 4.7.2 when .findLast was first introduced in 5.0.0
- code functions properly. IDE recognizes correct type

* if selectedValue and editedValue are equal, we do not need to submit a new value

* update file names to reflect component name changes

* refactor type export

* remove prop type covered by other type

* remove unused file

* remove unnecessary {}

* fix broken test b/c of functionality changes

* remove typescript ignore and replace with type safe function

* rename handleChange to onChange

* rename input validation function

* Trend Charts — Add static number comparison (#36951)

* Fix `MenuItemStyled` props type

* Implement static number comparison

* Fix `utils` unit tests

* Add unit tests for `getTrend`

* Add e2e test coverage

* Fix type

* Fix `compute` tests

* Rename `SmartScalarComparisonStaticNumber` type

* Replace `Flex` with `Stack`

* Fix `StaticNumberForm's` `value` type

* Fix options calc

* Simplify block

* Validate static number comparison

* Remove test

* Replace `Flex` with `Group`

* Minor `DoneButton` tweak

* Minor fix

* Fix value state

* Trend charts — Compact formatting viz setting (#36992)

* Refactor `compactifyValue`

* Add setting to `VisualizationSettings` type

* Respect `compact` option in `compactifyValue`

* Add viz setting

* Add e2e coverage

* Fix `onChange` for `StaticNumberForm`

* Move compact setting to `computeTrend`

* Add `formatOptions` tests for `computeTrend`

* Extend e2e tests

* Test formatting done by `computeTrend`

* Trend charts — Compare to another column (#37087)

* Add viz setting type

* Implement comparison

* Extract `renderMenuDropdownContent`

* Align `Select` label style with other inputs

* Use `column.name`

* Show opt only if there're cols to choose from

* Extend comparison validation check

* Handle missing column

* Fix type error

* Add tests for `getComparisonOptions`

* Extract test `describe` group

* Add tests for `isComparisonValid`

* Add tests for `computeTrend`

* Add basic e2e test

* Ensure comparison column exists in query results

* Fix onChange callback

* Trend charts — multiple comparisons (#37176)

* Turn `scalar.comparisons` into an array

* Implement adding new comparisons

* Implement removing comparison

* Use HTML list for comparisons

* Add `id` to comparison objects

* Implement sorting

* Extract `ComparisonPicker` component

* Trend charts — Misc fixes and polish (#37269)

* Use vertical layout for `StaticNumberForm`

* Update comparison picker display name

* Make smart scalar utils easier to use in static viz

* Fix height

* Fix `Icon` import

* Fix deprecated color reference

* Fix deprecated color reference

* Static viz path for the updated trend chart (#37418)

* Returning map-based response from js-svg/isomorphic.

* add common static viz code path which will be used for the trend chart

* review feedback

* update formatter type

* Fixed detect-pulse-chart-type test response to `:javascript_visualization` for `:smartscalar` case.

* Fixed TODO WRT keywordizing type value of `javascript-visualization` result.

* Better clj formatting

---------

Co-authored-by: Mark Bastian <markbastian@gmail.com>

* Fix merge conflict

* Trend charts — Static viz (#37602)

* Make `computeTrend` independent of "lib/formatting"

* Refactor `getArrowColor`

* Make `computeTrend` independent of "lib/colors"

* Make `computeTrend` independent `formatChange`

* Add `SmartScalar` placeholder

* Add basic static `SmartScalar` viz

* Fix `findLast` not available for static viz

* Clean up `SmartScalar`

* Enable PNG export

* static trend settings computation

* Fix `getDefaultComparison` return type

* Add `VIZ_SETTINGS_DEFAULTS` const for trend charts

* Add `getDefaultColumn` helper for `scalar.field`

* Fix `getDefaultComparison` tests

* Revert "Make `computeTrend` independent `formatChange`"

This reverts commit 9ab1db5a84cbcb58ec2d044f4d6cf7ffb341f62b.

* Fix `formatChange`

* Remove custom `formatChange`

* Add `scalar.comparisons` to `computeSmartScalarSettings`

* Fix `measureText` type

* Fix bad default value for `scalar.field`

* Use `getColor` instead of `color`

* Add stories

* Visual tweaks

* Add `getValue` for `scalar.comparisons`

* Extend e2e test

---------

Co-authored-by: Aleksandr Lesnenko <alxnddr@gmail.com>

* Fix flaky test

* Hide drag handle when there's only one comparison

* Update the "periods ago" control

* Inform people when "periodsAgo" value is clamped

---------

Co-authored-by: shaun <shaun@metabase.com>
Co-authored-by: Jesse Devaney <22608765+JesseSDevaney@users.noreply.github.com>
Co-authored-by: Aleksandr Lesnenko <alxnddr@users.noreply.github.com>
Co-authored-by: Mark Bastian <markbastian@gmail.com>
Co-authored-by: Aleksandr Lesnenko <alxnddr@gmail.com>
2024-01-17 11:29:02 +00:00
Nicolò Pretto
27873cca35 add whitelabeling feature usage to anon stats (#37657)
* rename site_name and help_link

* fix function + add tests

* appearance_logo

* appareance_favicon

* fix

* adds the remaining settings

* extracted functions + updated tests

* adds `appearance_show_mb_links`

* not-empty -> seq

* extract the ui colors to a variable

* Update src/metabase/analytics/stats.clj

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>

---------

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>
2024-01-17 11:31:39 +01:00
Cal Herries
151613f0ee Fix format-personal-collection-name-length-test (#37783) 2024-01-17 09:38:10 +00:00
Alexander Solovyov
ffcfaecccb env var MB_JETTY_SSL_INSECURE to disable SNI check (#37781)
Resolves #29660
2024-01-17 09:14:15 +00:00
Kamil Mielnik
e4e34df9bd [MLv2] [FE] Migrate data reference (#37694)
* Migrate StructuredQuery.prototype.filter in ObjectDetailView

* [MLv2] Add `legacy-column->metadata` for converting `DatasetColumn`

The query and stage are unfortunately required to correctly handle
aggregation references.

Note that the JS version of this name is `legacy_column__GT_metadata`,
with the double underscore.

* Add TS wrapper

* Use fromLegacyColumn

* Make code more backwards-compatible

* Make code more backwards-compatible

* Remove type argument from startNewCard

* Migrate startNewcard in actions/object-detail to MLv2

* Fix filter clause

* Use numberFilterClause when dealing with numbers

* Use numberFilterClause when dealing with numbers in ObjectDetailView

* Always pass metadata to getQuestionUrl

* Partially migrate getQuestion

* Handle metricId & segmentId in getQuestion

* Order functions

* Return after handling the metric and use setDisplay after handling all the clauses

* Update frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailView.tsx

Co-authored-by: Uladzimir Havenchyk <125459446+uladzimirdev@users.noreply.github.com>

* Do not pass tableId to Question.create

* Rename aggregateCount to aggregateByCount

* Do not pass tableId to Question.create

* Simplify code

* Get databaseId from Question instea of raw dataset query

* Fix code order

* Allow Field to be passed to fromLegacyColumn

* Prettier

* Handle fieldId in getQuestion

* Drop getQuestionOld

* Drop startNewCard

* Move aggregateByCount to metabase-lib/aggregation

* Migrate loadObjectDetailFKReferences to MLv2

* Reuse Lib.aggregateByCount

* Reverse logic

* Use proper Field type

* Handle field not being present in metadata

* Remove Q_DEPRECATED.createQuery

* Remove unused argument

* Make ObjectDetail.unit.spec.tsx tests pass

* Fix setting display

* Fix typo

* Add missing typing

* Fix withDefaultTemporalBucket usage

* Update getQuestion tests

* Add `null` to aggregation assertions
- pending question: https://metaboat.slack.com/archives/C04CYTEL9N2/p1705408133622419

* Remove unnecessary props argument from getMetadata calls

* Add missing metadata

* Handle missing table

* Format code

* Make sure setDisplay is called even if table is not available

* Use correct values in assertions

* Skip tests failing because of BE issue

---------

Co-authored-by: Braden Shepherdson <braden@metabase.com>
Co-authored-by: Alexander Polyankin <alexander.polyankin@metabase.com>
Co-authored-by: Uladzimir Havenchyk <125459446+uladzimirdev@users.noreply.github.com>
2024-01-17 09:03:18 +00:00
Ngoc Khuat
f40e8f0bc0 bump hawk to include the :times option (#37780) 2024-01-17 07:24:44 +00:00
Mark Bastian
280b7cb839 Don't break pivot tables when column widths are set (#37726)
* Don't break pivot tables when column widths are set

As per the repro on #37083, if a pivot table column is resized then another column is added from the "Summarize" button, the FE will break if either the question is refreshed or saved then reloaded.

This fixes that behavior by following the same pattern of calling `onUpdateVisualizationSettings` _after_ the relevant visualization settings are recomputed in the column changed `useEffect` as is done in `handleColumnResize`.

In addition to updating the left header widths, `valueHeaderWidths` is also preserved from its `useState` definition. This fixes the subtle behavior in which the UI resets the value header column width when a new breakout is added. Now all existing values are preserved.

* Adding e2e test.

* Preserving initial valueHeaderWidths logic

This PR had originally preserved valueHeaderWidths if they existed. However, if several new columns are added, it appears that the widths are narrow, so the initial logic is preserved.

* Adding `confirmSave` to `openStaticEmbeddingModal` helper

In some cases, if a question has been modified but not saved, when you got to do a static embed, it will ask you to save the question. This commit adds a param to allow you to save the question.

This affects the "should display pivot table in an embed URL" test in `e2e/test/scenarios/visualizations-tabular/pivot_tables.cy.spec.js`. To fix, `TEST_CASES` now includes a `confirmSave` param that is passed into `openStaticEmbeddingModal`.

* Removing extra comma
2024-01-16 18:14:08 -07:00
Jerry Huang
066e99ca4c Fix SQL server default to be empty again (#37749)
* fix sql server dfeault

* address comments
2024-01-16 21:48:01 +00:00
Uladzimir Havenchyk
f22d6e9c44 Drop ts-ignore and replace it with ts-expect-error where it is needed (#37699)
* Drop ts-ignore and replace it with ts-expect-error where it is needed

* Address some comments

* lint
2024-01-16 21:28:26 +00:00
Nick Fitzpatrick
1a411da8a2 adding back events on persist and unpersist (#37708)
* adding back events on persist and unpersist

* adding e2e test

* using cy.clock to speed up timers
2024-01-16 16:28:30 -04:00
Jeff Bruemmer
ee1e366ab7 add 47.12 to list of releases (#37756) 2024-01-16 13:43:50 -05:00
Jerry Huang
b4a156b2ef Update first and last name in Google SSO (#37674)
* add updatefirst and last name for google sso

* Update src/metabase/integrations/google.clj

Co-authored-by: Noah Moss <32746338+noahmoss@users.noreply.github.com>

* address comments

---------

Co-authored-by: Noah Moss <32746338+noahmoss@users.noreply.github.com>
2024-01-16 18:01:39 +00:00
Sloan Sparger
0c9ca50761 Allow non-admins to see unarchive/delete buttons in archive list (#37725) 2024-01-16 09:33:01 -06:00
Braden Shepherdson
f7b780c14b [MLv2] Add lib.js/valid-filter-for? function for filter compatibility (#37609)
`metabase.lib.types.isa/valid-filter-for?` returns true if the two
columns belong to the same type family (strings, numbers, temporal) or
the type of one column `isa?` subtype of the other.

Fixes #37501. (Unblocks #37438.)

Co-authored-by: Uladzimir Havenchyk <125459446+uladzimirdev@users.noreply.github.com>
2024-01-16 15:23:33 +00:00
Alexander Polyankin
26e578e10f Migrate QuestionDataSource to MLv2 (#37692)
* Remove table links

* Remove possibly unused code from QuestionDataSource

* Migrate QuestionDataSource to MLv2

* Migrate QuestionDataSource to MLv2

* Fix tests

* Fix legacy query issue

* Fix sandboxing issues

* Add a comment

* Format code

---------

Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>
2024-01-16 14:56:12 +00:00
Ngoc Khuat
0a54da9c64 Remove N+1 in sync (#37439) 2024-01-16 21:27:33 +07:00
Uladzimir Havenchyk
73c0701b16 Migrate dataset.js to TS (#37700)
* Migrate dataset.js to TS

* Make code more predictable
2024-01-16 17:18:10 +03:00
John Swanson
69bdca81d5 Do not use API Key names as part of user email (#37717)
Originally I had planned on using this to ensure uniqueness of the
ApiKey name. However, a) this is no longer a requirement, as we have a
uniqueness constraint on `:name` of the ApiKey directly, b) it would be
buggy anyway, because email addresses are case insensitive and `u/slugify`
will in some cases return the same slug for different names, and c) it
causes issues when you attempt to create a new ApiKey with the same name
as a deleted ApiKey (because the old user still exists).

The email can just be random - it's an implementation detail that
shouldn't be exposed to users.
2024-01-16 06:07:13 -08:00
Romeo Van Snick
78c2ef6154 Add romeovs to the Quering Components team (#37732) 2024-01-16 13:20:17 +01:00
Chris Truter
f926e90838 Add linter to rachet down implicitly non-exported defsettings (#37697)
* Add kondo for missing :export? on defsetting
* And tons of explicit ignores, including some inadvertent test vars, probably
* Disable linter in tests
* Handle multi settings
2024-01-16 10:52:36 +00:00
Kamil Mielnik
dd9ba07e2e [MLv2] [FE] Migrate object detail (#37639)
* Migrate StructuredQuery.prototype.filter in ObjectDetailView

* [MLv2] Add `legacy-column->metadata` for converting `DatasetColumn`

The query and stage are unfortunately required to correctly handle
aggregation references.

Note that the JS version of this name is `legacy_column__GT_metadata`,
with the double underscore.

* Add TS wrapper

* Use fromLegacyColumn

* Make code more backwards-compatible

* Make code more backwards-compatible

* Remove type argument from startNewCard

* Migrate startNewcard in actions/object-detail to MLv2

* Fix filter clause

* Use numberFilterClause when dealing with numbers

* Use numberFilterClause when dealing with numbers in ObjectDetailView

* Update frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailView.tsx

Co-authored-by: Uladzimir Havenchyk <125459446+uladzimirdev@users.noreply.github.com>

* Do not pass tableId to Question.create

* Get databaseId from Question instea of raw dataset query

* Fix code order

* Allow Field to be passed to fromLegacyColumn

* Prettier

---------

Co-authored-by: Braden Shepherdson <braden@metabase.com>
Co-authored-by: Alexander Polyankin <alexander.polyankin@metabase.com>
Co-authored-by: Uladzimir Havenchyk <125459446+uladzimirdev@users.noreply.github.com>
2024-01-16 09:36:35 +00:00
Nemanja Glumac
e5b19dd2e7 Stress-test a single driver test in isolation (#35919) 2024-01-16 08:08:22 +01:00
Nemanja Glumac
d133a0b2b2 Align pie chart label and value vertically (#37637)
Fixes #37635
2024-01-16 08:06:49 +01:00
Braden Shepherdson
be231ec835 [MLv2] Add display-info for queries (#37675)
Fixes #36973.
2024-01-15 17:07:56 -05:00
Braden Shepherdson
045a54da09 [MLv2] Only allow implicit join on a column if its real ID is known (#37536)
This is how legacy worked but MLv2 changed this behavior. Even if the
metadata for a native column includes `:semantic-type :type/FK` and
`:fk-target-field-id`, it can't be used for a JOIN unless it's a real
field in the database.

This undoes some hacks from #37079 that were misguided. Fixes #37067.
2024-01-15 16:41:35 -05:00
Case Nelson
609bbdb3a4 [MLv2] Visible columns should not see breakout binning or bucketing (#37537)
* [MLv2] Visible columns should not see breakout binning or bucketing

Fixes #37463

* Fix geographic drill through to look at returned columns first, fix quick filter test to match v.47

* Fix lint

* Fix lint

* Fix cljs compile

* Address pr review

* Fix test

* Fix e2e test to reflect pre-mlv2 behavior
2024-01-15 14:29:13 -07:00
Nick Fitzpatrick
c5fb372d87 Show Loading state while checking dashboard redirect (#37089)
* Show Loading state while checking dashboard redirect

* adding e2e test
2024-01-15 16:34:39 -04:00
Nick Fitzpatrick
06239693e0 mobile admin view menu icon is now a button (#37714) 2024-01-15 16:33:35 -04:00
Alexander Polyankin
8d5179dffc Revert "Remove unused code from QuestionDataSource" (#37710) 2024-01-15 19:01:22 +00:00
Alexander Polyankin
e0e27e3994 TableInteractive - migrate sorting direction to MLv2 (#37634) 2024-01-15 17:57:03 +00:00
Braden Shepherdson
1418a78c30 [MLv2] Add legacy-column->metadata for converting DatasetColumn (#37648) 2024-01-15 19:24:00 +02:00
Sloan Sparger
ab4ae5297c Fix admin landing page e2e test flakes (#37653) 2024-01-15 11:02:40 -06:00
Ngoc Khuat
73ff8b97e8 Bigquery fix sync for tables that require a filter (#37102) 2024-01-15 16:06:46 +00:00
Chris Truter
fda549e2f7 Replace global exported-settings var with inline kwarg (#37640)
* Replace global var with explicit export? opt-ins
* Rename helper and add proper docstring
2024-01-15 16:36:22 +02:00
Oleg Gromov
ccc5db06cd Remove unused noReset prop (#37696) 2024-01-15 14:00:15 +00:00
Alexander Polyankin
d33ee387b8 Remove unused code from QuestionDataSource (#37691) 2024-01-15 15:37:20 +02:00
Alexander Polyankin
a5dd444483 Remove unused code from QuestionDataSource (#37691) 2024-01-15 15:36:18 +02:00
Anton Kulyk
1b80c36fb6 Convert dashboard selectors to TypeScript (#37664)
* Add `draftParameterValues` type to dashboard state

* Fix type in `getParameterMappingOptions`

* Convert dashboard selectors to TypeScript

* Merge `selectors` and `selectors-typed`

* Remove `selectors` directory

* Fix `getDashboard` selector in public/embedded env
2024-01-15 12:37:15 +00:00
Chris Truter
73cfd731a8 Introduce way to mark exported settings inline (#37624)
* Pull out common method for pulling out settings for frontend or export
* Migrate application-colors to use explicit :export? key
* Add setting key to schema
* Add tests
2024-01-15 12:56:26 +02:00
Luis Paolini
38b5a56fd1 Upgrade regenerator package (#37672) 2024-01-15 07:21:10 -03:00
Cal Herries
8a961a8568 Exclude snippet and card template tags from parameters returned from BE endpoints (#37405) 2024-01-15 09:59:26 +00:00
Mahatthana (Kelvin) Nomsawadi
9a840f92c5 Add show metabase links toggle admin setting (#37076)
* Add show metabase links toggle admin setting

* Hide Metabase links

* Fix type error

* Add selector tests

* Hide a link in HomeHelpCard

* Make test names more consistent with existing test suites

* Add tests to `NewModelOptions`

* Prepare `VisualizationError` for testing

* Add tests to `VisualizationError`

* Hide link and add tests to `PreviewQueryModal`

* Extract components to make it easier to test

* Move the new component into its own folder

* Hide Metabase link in `ActionDashcardSettings`

* Prepare `EmptyFormPlaceholder` for testing

* Hide Metabase link in `EmptyFormPlaceholder`

* Extract Metabase link from `FormCreator` for testing

* Hide Metabase link in `FormCreator`

* Extract link from `DashCardCardParameterMapper` to prepare for testing

* Hide Metabase link in `DashCardParameterMapper`

* Clean up the test setup function

* Hide Metabase link in `ExpressionEditorHelpText`

* Hide Metabase link in `TagEditorHelp`

* Hide Metabase links in `MetricList`

* Hide Metabase link in `SegmentList`

* Prepare `CaveatMessage` for testing

* Hide Metabase link in `CaveatMessage`

* Hide Metabase link in `CustomMapFooter`

* Hide Metabase link in `ImpossibleToCreateModelModal`

* Hide Metabase link in `ExpressionWidget`

* Hide Metabase link in `ExpressionWidget`

* Add BE tests

* Update sample database description

* Fix TypeScript type-check

* Fix failed unit tests

* Fix wrong test names

* Add missing translations

* Make tests looks like tests from other components

* Update enterprise/frontend/src/metabase-enterprise/whitelabel/components/MetabaseLinksToggleWidget/MetabaseLinksToggleWidget.tsx

Co-authored-by: Nicolò Pretto <info@npretto.com>

* Simplify the change

* Fix weird import directory

* Fix wrapped translation copy

* Fix test name

* Move comment next to the component

* Fix test names

* Review: Make code easier to review

* Fix wrong document link

* Update src/metabase/public_settings.clj

Co-authored-by: Noah Moss <32746338+noahmoss@users.noreply.github.com>

* Update src/metabase/public_settings.clj

Co-authored-by: Noah Moss <32746338+noahmoss@users.noreply.github.com>

* Address review: BE changes

---------

Co-authored-by: Nicolò Pretto <info@npretto.com>
Co-authored-by: Noah Moss <32746338+noahmoss@users.noreply.github.com>
2024-01-15 09:29:35 +00:00
Alexander Polyankin
b8b4294514 Fix filter UI issues (#37676) 2024-01-15 08:34:19 +00:00
Alexander Polyankin
3a0e93eb86 Migrate updateQuestion to MLv2 (#37499) 2024-01-15 08:19:32 +00:00
Chris Truter
7b0a906ab9 Add validation for remaining setting types (#37519)
* Add tests and non-redact criteria for csv validation
* Set redaction rules and test validation for remaining types
* Test that our format test coverage has not slipped
* Test we have defined the redaction logic
2024-01-15 09:48:08 +02:00
Braden Shepherdson
ed309c5918 [MLv2] Fix an edge case where a join-alias is needed on a field ref (#36871)
The QP sometimes provides a `:source-alias` and no `:join-alias` for
a joined column. Then its MLv2 ref would be missing a `:join-alias` and
it would not match its own column under
`lib.equality/find-matching-column`.

Fixes #36861.
2024-01-13 17:44:18 +00:00
Gustavo Saiani
89d33df5c2 Pass email and siteURL to metabase.com/help/connect (#37571) 2024-01-13 00:13:24 +00:00
Nick Fitzpatrick
859ca2df2e 36797 partial permission graph (#37058)
* building out partial graphs

* Set up change deteected modal, graph loading states

* e2e tests. Load admin permissions

* reset permissions from memory on cancel

* fixing types and tests
2024-01-12 17:40:54 -04:00
Oleg Gromov
34ebffa986 Fix colors in Mantine select (#37660) 2024-01-12 20:08:41 +00:00
Jerry Huang
672b07e900 Add email retry to all email events (#37408)
* add retry to password reset

* fix error case

* add to all emails

* fix misc stuff

* fix test

* fix test

* fix linter

* fix retrying framework

* fix linter

* fix e2e test

* add comment

* adress comments

* fix linter

* fix linter

* fix test

* fix test

* fix test

* fix test

* fix test

* fix e2e test

* fix e2e test

* fix e2e test

* fix test

* fix e2e test and unit tests

* remove paren

* fix linter

* fix e2e test

* fix e2e test

* finally actually fix e2e test
2024-01-12 19:54:56 +00:00
Aleksandr Lesnenko
1d6d58b554 check backport script workflow (#37545) 2024-01-12 16:13:01 -03:00
Alexander Polyankin
dd995f6b0a Remove model filters from x-rays (#37647) 2024-01-12 18:16:40 +00:00
Alexander Polyankin
2928249967 Fix isEditable check (#37654) 2024-01-12 22:01:12 +04:00
Anton Kulyk
2c7eb3072c Use UTF8 encoding for dashboard preview page (#37636)
* Use UTF8 encoding for dashboard preview page

* Remove `nonce`

Co-authored-by: adam-james <21064735+adam-james-v@users.noreply.github.com>

---------

Co-authored-by: adam-james <21064735+adam-james-v@users.noreply.github.com>
2024-01-12 17:10:37 +00:00
Jeff Bruemmer
bb8dbacf6e specify how to revert homepage (#37575) 2024-01-12 11:45:03 -05:00
Ryan Laurie
47175ac17d set select input label to text-medium (#37649) 2024-01-12 16:41:00 +00:00
Uladzimir Havenchyk
422dc5ebff Improve performance of ExpressionEditor (#37584) 2024-01-12 19:26:55 +03:00
Alexander Polyankin
16aa9974fb Remove internal query check (#37587) 2024-01-12 18:26:48 +02:00
Oleg Gromov
ff4acb4df1 Disable CYPRESS_FE_HEALTHCHECK for test-cypress-open (#37643) 2024-01-12 15:28:51 +00:00
metamben
e98b6a14b4 Optimize canonicalization of MBQL clauses (#37539)
* Optimize canonicalization of MBQL clauses

Fixes #37245.
2024-01-12 15:16:14 +00:00
Braden Shepherdson
dc4cc6aedd [MLv2] Add caching for all the foo-columns functions (#37586)
This is at the `metabase.lib.js` level. Should help solve some
performance issues where eg. `expressionable-columns` was getting called
on every keystroke for autocomplete; see #37528.

Powered by `metabase.lib.cache/side-channel-cache`, which attaches
the cache in an Atom on a private property mutated onto the `query`.
That means it is invalidated with any edit to the query (since a new
object is returned) and becomes garbage at the same time the query does.
2024-01-12 09:58:05 -05:00
metamben
8436c646f3 Support replacing expressions changing types and names (#37409)
* Support replacing expressions changing types and names

Part of #36211.
2024-01-12 17:14:51 +03:00
Ibe Dwi
b1e06cec77 Fix TypeError when changing click behavior to drill-through menu & default click behavior does not have selected state (#35863)
* fix: type error on click behavior change

* chore: add comments

* chore: tidy up comments

* chore: reset changes

* add aria-selected & selected drill-through menu assertion

* chore: update assertion comment

* refactor: move aria-selected inside selectable item

* remove 'menu' from click behavior option

* test: add e2e test fro 35354

* chore: clean up demo and update assertion

* refactor: move assertion to existing scenario

* chore: add log on e2e test

* feat: update name for actionMenu

* fix: unknown type in 34845

* fix: test after rebase

* fix: remove unused union type "menu"

* fix: use master version of click-behavior

* fix: readd the tests

* fix: e2e test

* fix: remove set type selector after unset column

* fix: show type selector when click behavior is undefined

* fix: show type selector when finalClickBehavior is default (actionMenu)
2024-01-12 20:48:40 +07:00
Alexander Polyankin
cae348af54 Migrate TableInteractive -> DimensionInfoPopover from legacy query (#37585) 2024-01-12 11:59:59 +00:00
Alexander Polyankin
4f949af3c3 Remove unused legacy code (#37631) 2024-01-12 11:46:25 +00:00
Alexander Solovyov
49b882686e Serialization API (#36851) 2024-01-12 14:43:15 +03:00
Kamil Mielnik
dfc8a775c6 Remove aggregate, breakout, filter methods from Question (#37574)
* Get rid of Question.prototype.aggregate

* Get rid of Question.prototype.breakout

* Get rid of Question.prototype.filter
2024-01-12 11:19:50 +00:00
Alexander Polyankin
198bdad0a5 TableInteractive - check for aggregations based on query results (#37625) 2024-01-12 10:36:19 +00:00
Nemanja Glumac
517a846843 Expose MLv2 functions in the browser in dev mode (#37622) 2024-01-12 10:15:18 +01:00
Alexander Polyankin
95833c9679 Migrate EditSandboxingModal to MLv2 (#37590) 2024-01-12 11:12:34 +02:00
Alexander Polyankin
305e637175 Remove unneeded check (#37595) 2024-01-12 11:12:13 +02:00
Nicolò Pretto
440d600702 run frontend ci tasks when eslint config changes (#37601) 2024-01-12 09:12:19 +01:00
Nemanja Glumac
b457c8dac3 Remove setDefaultQuery() method for queries (#37583)
This removes the `setDefaultQuery()` method for both
- StructuredQuery and
- Query

Resolves #37506
2024-01-12 09:11:07 +01:00
Kamil Mielnik
51c98b89c4 Migrate initializeQB (StructuredQuery only) (#37498)
* Migrate segments in getCardForBlankQuestion and... fix it

* Separate parsing, use Metadata.prototype.segment

* Extract filterBySegmentId

* Migrate metrics in getCardForBlankQuestion

* Rename filterByMetricId to aggregateByMetricId

* Expose segment(query, segmentId) in MLv2, map it in metabase-lib, and use it in initializeQB

* Expose metric(query, metricId) in MLv2, map it in metabase-lib, and use it in initializeQB

* Update Lib.metric and Lib.segment return type

* Break TemplateTag type down to ensure presence of snippet-specific and card-specific properties when dealing with respective snippet types

* Begin migrating updateTemplateTagNames, migrate referencedQuestionIds, migrate updateCardTemplateTagNames

* Migrate hasSnippets

* Remove redundant conditioning

* Migrate updateSnippetNames

* Revert "Break TemplateTag type down to ensure presence of snippet-specific and card-specific properties when dealing with respective snippet types"

This reverts commit f303122055.

* Migrate updateSnippetsWithIds & setTemplateTag

* Format code

* Use new updateTemplateTagNames implementation

* Remove old updateCardTemplateTagNames, move and refactor relevant test to initializeQB unit test suite

* Remove no-longer-used NativeQuery.prototype.hasSnippets

* Fix TS issues

* Update initializeQB unit tests

* Revert NativeQuery-related changes in initializeQB

* Rename segment to segmentMetadata & metric to metricMetadata
2024-01-12 14:59:52 +07:00
Jerry Huang
6fafcb348d Backend validation for landing-page to disallow external URLs (#37551)
* landing-page backend validation

* fix spacing
2024-01-11 19:40:46 -08:00
adam-james
3ef4d5df66 Handle unknown column-settings keys instead of passing a nil key. (#37606)
* Handle unknown column-settings keys instead of passing a `nil` key.

The issue #27941 called out pivot table static-viz failing when a sort was added to the column-viz.

This led to a null pointer exception in a formatter when the table render was attempted.
Following the chain a bit, I noticed that there's a map of 'db' keys -> 'norm' keys defined in `metabase.shared.models.visualization-settings`

```clojure
(def ^:private db->norm-column-settings-keys
  {:column_title       ::column-title
   :date_style         ::date-style
   :date_separator     ::date-separator
   :date_abbreviate    ::date-abbreviate
   :time_enabled       ::time-enabled
   :time_style         ::time-style
   :number_style       ::number-style
   :currency           ::currency
   :currency_style     ::currency-style
   :currency_in_header ::currency-in-header
   :number_separators  ::number-separators
   :decimals           ::decimals
   :scale              ::scale
   :prefix             ::prefix
   :suffix             ::suffix
   :view_as            ::view-as
   :link_text          ::link-text
   :link_url           ::link-url
   :show_mini_bar      ::show-mini-bar})
```

Which doesn't contain the key `:pivot_table.column_sort_order`, which is the key added by the frontend when you sort
the column via the viz settings.

This would cause the transform to leave a `nil` key in its place which ultimately led to the NPE further down the
line.

I've made the change that any unknown key gets namespaced with `unknown`. So, `:pivot_table.column_sort_order` ->
`:unknown/pivot_table.column_sort_order`.

This prevents the NPE.

* Use a simpler approach to achieve the same result!
2024-01-11 22:07:07 +00:00
Jeff Bruemmer
a3a6170464 48.3 (#37610) 2024-01-11 16:42:03 -05:00
shaun
7d369288ab API Keys UI (#37097)
* API Keys: add auth card and manage page

* update deletion copy

* add groups data to snapshot

* update e2e tests to work with backend

* update strings and formatting

* update e2e tests

* remove e2e tests from other pr

* update unit tests

* e2e test update

* mock api key endpoints in settingsEditor unit tests

* remove console log

* use dumb quotes

* handle monospace better

* better form validation

* no need to wait

* update test to work with validation

* contrain table width

* remove monospace variant

* API Keys: Handle Groups UI (#37099)

* API Keys: Show in Group members table

* API Keys: Show count in Group listing

* tweak and test group settings views for api keys

* fix sad lint rebase sitch

* update group manager tests

* better loading behavior

* handle all users api keys

* update types and tests

---------

Co-authored-by: Ryan Laurie <iethree@gmail.com>

---------

Co-authored-by: Ryan Laurie <iethree@gmail.com>
2024-01-11 20:47:20 +00:00
Mark Bastian
d58bc3e9ee Fixing macro scope capture of with-skip-if-empty-pulse-result (#37597)
As a follow on to #37546, this fixes an issue in which the macroexpansion of `with-skip-if-empty-pulse-result` doesn't capture the scope of the arguments in `skip-if-empty-test`.

The solution is just to _correctly_ wrap all of the `mt/id` functions in `mt/dataset`.
2024-01-11 20:36:03 +00:00
Sloan Sparger
be73bb2650 Improve admin logs page loading and error experience (#37540) 2024-01-11 13:28:58 -06:00
metamben
cf95e7d2a4 Add advanced option for quoting the database name (#37469) 2024-01-11 21:27:03 +03:00
Sloan Sparger
3288a543d9 Truncate tooltip content for table items with large descriptions (#37466) 2024-01-11 12:15:59 -06:00
Jeff Bruemmer
f47caa0ed0 docs - api update (#37445) 2024-01-11 11:32:50 -05:00
Nemanja Glumac
bcd4448b61 Increase the request timeout for instance-analytics E2E flake (#37582) 2024-01-11 16:42:15 +01:00
Nicolò Pretto
5af39ef94c Embedding settings cleanup - Milestone 2 (#37430)
* fix color button when it's disabled (#37053)

* new utm tags for embed settings (#37403)

* new utm tags for embed settings

* use paid plan utm sourcein premium unit tests

* fix e2e

* revert un-needed changes

* Use new docs url for quickstart link (#37523)

* use new docs url

* use realistic version numbers instead of latest for doc urls
2024-01-11 16:36:43 +01:00
Nemanja Glumac
c4c2d3c378 Remove isEmpty method in StructuredQuery (#37567)
* Migrate `isEmpty` check for structured queries in DatasetEditor

Resolves #37515

* Remove `isEmpty` method from StructuredQuery

* Remove related unit test
2024-01-11 16:25:17 +01:00
metamben
6eb60172bd Unwrap value expressions when converting to legacy expression (#37481)
Fixes #37461.
2024-01-11 18:00:32 +03:00
Alexander Polyankin
c9ee43f33f Fix segmented control and menu colors (#37568) 2024-01-11 14:54:03 +00:00
bryan
8a689248f0 make fn-name consistent between mu/defn and mu.fn/fn (#37550) 2024-01-11 09:43:05 -05:00
Alexander Polyankin
a9d88327b2 Moves icons to metabase/ui (#37441) 2024-01-11 16:21:55 +02:00
Alexander Solovyov
e685acd2ea fix serialization when there is a slash in click_behavior id (#37503)
Resolves #37555
2024-01-11 12:23:16 +00:00
Oisin Coveney
f9195a3138 Fix transparent embedding menu option text (#37547) 2024-01-11 19:03:08 +07:00
Jeff Bruemmer
2557cece28 fix link title (#37530) 2024-01-11 06:58:35 -05:00
Denis Berezin
32313d71cb Static Embedding Modal redesign (#36181)
* Migrate EmbedModalContent to TS

* Add basic UI changes to Embed modal

* More styling

* Add more styling

* Self review fixes

* Self review fixes

* Fix action button

* Fix unit tests

* Fix e2e tests

* Fix e2e tests

* Code review and design fixes

* Fix unit test

* Fix for e2e tests

* Code review fixes for e2e tests

* Fix for e2e tests
2024-01-11 18:56:38 +07:00
Alexander Solovyov
b8cc687973 collections in 'analytics' namespace should not be extracted (#37495)
Resolves #37453
2024-01-11 09:44:18 +00:00
Chris Truter
478cb8f73f Validate json settings during init (#36182) (#37313)
* Validate json settings during init (#36182)

* Use correct translation for error message

Co-authored-by: Cal Herries <39073188+calherries@users.noreply.github.com>

* Make extensible, only throw on env vars

* Better check for whether a setting came from an environment variable

Co-authored-by: Cal Herries <39073188+calherries@users.noreply.github.com>

* Resuse existing parser validation, improve security

* Add example of better exception

* Add precise exception messages as exmaples

* DRY up tests

* Add test for realize

* make the example actually deep

* better hygiene around ex-cause

* Use strict json parsing for all settings

* Disable validation on non-json configuration

---------

Co-authored-by: Cal Herries <39073188+calherries@users.noreply.github.com>
2024-01-11 09:00:57 +00:00
Ngoc Khuat
1461fb96fc with-premium-features to metabase.test (#37112) 2024-01-11 08:00:59 +00:00
Nemanja Glumac
bb51edb086 [MLv2] Add TypeScript wrappers around native CLJS functions (#37518)
* Add TS wrapper for CLJS `native-query`

* Add TS wrapper for CLJS `raw-native-query`

* Add TS wrapper for CLJS `with-native-query`

* Add TS wrapper for CLJS `with-template-tags`

* Add TS wrapper for CLJS `template-tags`

* Add TS wrapper for CLJS `extract-template-tags`

* Add TS wrapper for CLJS `has-write-permission`

* Add TS wrapper for CLJS `with-different-database`

* Add TS wrapper for CLJS `engine`

* Fix types

* Replace the direct ML reference with a new wrapper

* Simplify the return type for `extractTemplateTags`
2024-01-11 06:21:57 +01:00
Mark Bastian
6f0161ac44 Don't send results works at the card level (#37546)
* Don't send results works at the card level

When a user enables **Don't send if there aren't results** this was the previous behavior:
- If no results appeared on any card, no emails was sent. This was expected.
- If any card contained results, all cards were sent in the email, including those that had no results.

This PR modifieds that behavior to only send those cards that contain results for a dashboard pulse. For example, if 5 cards are present on a dashboard and 3 have no results, only results for the 2 cards containing data are included in the pulse.

Primary changes:
- `metabase.pulse/execute-dashboard` now removes any card with a row count of 0 in its computed result if `skip_if_empty` is true for the pulse.
- The addition of tests covering the matrix of tests where `skip_if_empty` is true or false, all cards contain data, some cards contain data, and no cards contain data.
- The `with-skip-if-empty-pulse-result` makes the above set of tests nice and concise.

Minor changes:
- Fixing a minor issue in `with-metadata-data-cards` in which the macroexpansion logic would go bad if the user used a different symbol name for `base-card-id`.
- Spelling and formatting issues in `metabase.pulse`

Fixes #34777

* lint fix for #_{:clj-kondo/ignore [:unresolved-symbol]}
2024-01-11 01:50:20 +00:00
bryan
0f9cf7c91f Apply selective malli mu.fn enforcement for certain namespaces to improve performance (#37428)
* rough approach for per-namespace schema checking

* Added tests

* cleanup + add a namespace to skip

* use stringified namespaces instead of ns objects

* move to `instrument-ns?`+ trying to not emit an if

* WIP, working on tests

* eval

* Fixup tests and remove some errant junk

tests are a bit tricky because the the reader expands the macro so we
can't do anything at runtime to affect the binding. This is why we use
eval so we can coordinate when the binding happens

* some notes and remove the pulse ns from ad-hoc exclusions

* add docstrings and comments

* remove redundant case statement

* swapped branches in mu/defn, so that when `skip?` we emit deparameterized fn

* skip logging message about calculating display name in prod

- it was suspected as part of the high cpu usage issue here:
  https://github.com/metabase/metabase/issues/37144

* config/is-prod? is not avaliable in cljs

* use the right kind of quote

* actually it's ok to use binding if we delay the evaluation of the macro

* use :cljs-dev and :cljs-release to skip printing sus message in prod

* use cljs-dev and cljs-release to control printing message

* add more tests for defn, and move fn_skip_test into fn_test

* add info in mu/defn docstring about instrument-ns? skipping behavior

* fix test

---------

Co-authored-by: dan sutton <dan@dpsutton.com>
2024-01-10 23:23:12 +00:00
Sloan Sparger
4a9b1162c6 Fix external landing page urls locking users out of Metabase (#37322)
* updates enterprise appearance settings ui to validate that landing page urls are relative

* adds e2e test, impls feedback to use isMetabaseUrl util

* makes new e2e tests more resilient

* fixes logical mistake in e2e test

* removes old e2e test that accounted for invalid landing page urls being saved

* impls pr feedback

* extracts out url validation logic and adds unit tests
2024-01-10 17:11:21 -06:00
Alexander Polyankin
1f9e03f664 Remove getQuery selector (#37450) 2024-01-10 21:29:25 +00:00
adam-james
0f4ee775f0 Add :link to Lato Font for the Dashboard Subscription Preview endpoint (#37521) 2024-01-10 19:30:16 +00:00
bryan
2d73f40e0e Adds option to skip backfill, and skips it during auditdb loading (#37482) 2024-01-10 14:17:54 -05:00
Alexander Polyankin
41d996bab7 Make it easier to track Structured legacy query usages (#37500) 2024-01-10 21:39:27 +03:00
Alexander Polyankin
0031c090aa Migrate core.js in QB to MLv2 (#37460) 2024-01-10 18:29:32 +02:00
Nemanja Glumac
e9ea44270b Deprecate metabase-lib/queries aggregation utils (#37472)
* Deprecate metabase-lib/queries aggregation utils

* Mark additional breakout utils as deprecated
2024-01-10 16:17:26 +01:00
Nemanja Glumac
c295b82f64 Replace ML references with Lib (#37497)
* Replace `ML` references with `Lib` in Question class

* Replace `ML` references with `Lib` in StructuredQuery class

* Replace `ML` references with `Lib` in query builder selectors

* Replace `ML` references with `Lib` in unit tests

Fixes #37496.
2024-01-10 16:05:29 +01:00
Kamil Mielnik
ba9375171c Migrate sourceTableId, sourceTable to use sourceTableOrCardId from MLv2 (#37436)
* Migrate Question.prototype.databaseId to MLv2

* Migrate Question.prototype.database to MLv2

* Migrate databaseId() to MLv2 in QuestionRowCount

* Rename query to legacyQuery in DataSourceSelector & NewQuestionView

* Migrate databaseId() to MLv2 in NewQuestionView

* Remove unused StructuredQuery.prototype.setDatabase & StructuredQuery.prototype.setDatabaseId

* Ensure MLv2 query is used only in case of structured questions

* Migrate StructuredQuery.prototype.database to MLv2 in checkCanBeModel

* Migrate StructuredQuery.prototype.database to MLv2 in QuestionActions

* Migrate StructuredQuery.prototype.database to MLv2 in FilterPopover

* Migrate StructuredQuery.prototype.database to MLv2 in TagEditorSidebar

* Migrate StructuredQuery.prototype.database to MLv2 in QuestionDataSource

* Do not redundantly expose databaseSupportsPivotTables

* Migrate StructuredQuery.prototype.database to MLv2 in databaseSupportsPivotTables

* Migrate StructuredQuery.prototype.database to MLv2 in getSourceQueryTable

* Move AtomicQuery.prototype.canNest to StructuredQuery.prototype.canNest

* Migrate StructuredQuery.prototype.database to MLv2 in NativeQueryEditor

* Avoid circular dependency on Question.prototype._getMLv2Query and Question.prototype.databaseId

* Revert "Remove unused StructuredQuery.prototype.setDatabase & StructuredQuery.prototype.setDatabaseId"

This reverts commit 0dcb00c2d8.

* Fix isPromptInputVisible as question is not always available there (e.g. in ActionCreator)

* Format code

* Fix databaseSupportsPivotTables

* Post-merge fix

* Post-merge fix

* Migrate NativeQuery.prototype.database to MLv2 in native-query-table

* Migrate StructuredQuery.prototype.database to MLv2 in NativeQueryEditor

* Deprecate database() and databaseId() on MBQL Query

* Migrate NativeQuery.prototype.database to MLv2 in DataSourceSelectors

* Use _databaseId instead of _database

* Pass question to getStructuredQueryTable

* Update unit tests

* Fix test, remove casts

* Migrate Query.prototype.sourceTableId to MLv2

* Migrate Query.prototype.sourceTable to MLv2, drop Query.prototype.sourceTable

* Deprecate sourceTableId

* Drop StructuredQuery.prototype.setTableId

* Drop StructuredQuery.prototype.setTable

* Drop StructuredQuery.prototype.tableId

* Fix tests

* Fix tests

* Migrate Query.prototype._databaseId to MLv2 in Question.prototype.query

* Use Question.prototype.isStructured

* Format code

* Bring back isStructured check

* Use Question.prototype.isStructured

* Migrate Question.prototype.table in Question.prototype.supportImplicitActions

* Remove redundant nullish coalescing operator

* Bring back previous Question.prototype.table & Question.prototype.tableId definitions

* Temporary tests fix

* Sort out getNestedCardTable

* Bring _sourceTableId back

* Fix mainTable in ModelDetailPaGE

* Format code
2024-01-10 21:05:53 +07:00
Nemanja Glumac
06400bc667 Rename Question.setQuery to Question.setLegacyQuery (#37440)
* Rename `setQuery` to `setLegacyQuery`

* Rename `_setMLv2Query` to `setQuery`

* Update new `_setMLv2Query` references from `master`
2024-01-10 10:33:57 +01:00
Ryan Laurie
30fff3b714 Update slack web api version (#37484) 2024-01-09 16:38:56 -07:00
Jeff Bruemmer
522ad4b781 docs - updates to usage analytics (#37413) 2024-01-09 17:10:50 -05:00
Jeff Bruemmer
3b66cb4c86 docs - replace questions on dashboards (#37411) 2024-01-09 17:10:17 -05:00
Mark Bastian
a5b27f75c8 Adding replay upload logic for crashes and ~1/10 passes (#37471)
Previously, replays were recorded on failure only, as shown here:

```javascript
filter: r => r.metadata.test?.result === "failed"
```

This filter has been enhanced to include crashes as well as an upload in approximately 1/10 passing instances, as shown:

```javascript
filter: r => {
  const hasCrashed = r.status === "crashed";
  const hasFailed = r.metadata.test?.result === "failed";
  const randomlyUploadAll =
    convertStringToInt(r.metadata.test.run.id) % 10 === 1;

    console.log("upload replay ::", {
      hasCrashed,
      hasFailed,
      randomlyUploadAll,
    });
    return hasCrashed || hasFailed || randomlyUploadAll;
},
```

Note that this closely follows the example provided by replay [here](https://github.com/replayio-public/flake/pull/89/files#diff-3f62e885350a48939f240b9daf40f6b06d41da7751f2b613238fc7669ac0a1b2R32).

Closes #37467
2024-01-09 14:52:01 -07:00
Jeff Bruemmer
e75fc12142 docs - clarify uploads (#37477) 2024-01-09 16:06:56 -05:00
Cal Herries
ad89a77c03 Restore GET /api/dashboard endpoint (#37458) 2024-01-09 18:18:44 +00:00
Alexander Polyankin
37a5ea1afe Migrate QuestionDescription to MLv2 (#37457) 2024-01-09 19:57:50 +02:00
Alexander Polyankin
3127a7af54 Migrate QuestionDataSelector (#37454) 2024-01-09 19:57:41 +02:00
Alexander Polyankin
a51346d53e Remove unused legacy query in QueryVisualization (#37444) 2024-01-09 19:18:42 +02:00
Jeff Bruemmer
69de23a7d4 docs - add help menu option (#37406) 2024-01-09 11:10:12 -05:00
Roman Abdulmanov
cfbbdecc87 [WIP] Flaky test fix (models-metadata.cy.spec.js) (#37442) 2024-01-09 15:44:25 +00:00
Alexander Polyankin
cbfdbb2fe6 Use colors by names (as with color utility) instead of indexes in mantine (#37443) 2024-01-09 15:08:30 +00:00
ignacio
446defca23 Add MB_ATTACHMENT_TABLE_ROW_LIMIT to docs (#37261)
* Add MB_ATTACHMENT_TABLE_ROW_LIMIT to docs

With default set to 20

* Update docs/configuring-metabase/environment-variables.md

Co-authored-by: Jeff Bruemmer <jeff.bruemmer@gmail.com>

* remove version

* range

---------

Co-authored-by: Jeff Bruemmer <jeff.bruemmer@gmail.com>
2024-01-09 12:08:12 -03:00
Nemanja Glumac
4d680329b2 Remove unused method from StructuredQuery (#37451) 2024-01-09 16:07:52 +01:00
Kamil Mielnik
9fd149dcfe Migrate databaseId, database to use databaseID from MLv2 (#37252)
* Migrate Question.prototype.databaseId to MLv2

* Migrate Question.prototype.database to MLv2

* Migrate databaseId() to MLv2 in QuestionRowCount

* Rename query to legacyQuery in DataSourceSelector & NewQuestionView

* Migrate databaseId() to MLv2 in NewQuestionView

* Remove unused StructuredQuery.prototype.setDatabase & StructuredQuery.prototype.setDatabaseId

* Ensure MLv2 query is used only in case of structured questions

* Migrate StructuredQuery.prototype.database to MLv2 in checkCanBeModel

* Migrate StructuredQuery.prototype.database to MLv2 in QuestionActions

* Migrate StructuredQuery.prototype.database to MLv2 in FilterPopover

* Migrate StructuredQuery.prototype.database to MLv2 in TagEditorSidebar

* Migrate StructuredQuery.prototype.database to MLv2 in QuestionDataSource

* Do not redundantly expose databaseSupportsPivotTables

* Migrate StructuredQuery.prototype.database to MLv2 in databaseSupportsPivotTables

* Migrate StructuredQuery.prototype.database to MLv2 in getSourceQueryTable

* Move AtomicQuery.prototype.canNest to StructuredQuery.prototype.canNest

* Migrate StructuredQuery.prototype.database to MLv2 in NativeQueryEditor

* Avoid circular dependency on Question.prototype._getMLv2Query and Question.prototype.databaseId

* Revert "Remove unused StructuredQuery.prototype.setDatabase & StructuredQuery.prototype.setDatabaseId"

This reverts commit 0dcb00c2d8.

* Fix isPromptInputVisible as question is not always available there (e.g. in ActionCreator)

* Format code

* Fix databaseSupportsPivotTables

* Post-merge fix

* Post-merge fix

* Migrate NativeQuery.prototype.database to MLv2 in native-query-table

* Migrate StructuredQuery.prototype.database to MLv2 in NativeQueryEditor

* Deprecate database() and databaseId() on MBQL Query

* Migrate NativeQuery.prototype.database to MLv2 in DataSourceSelectors

* Use _databaseId instead of _database

* Pass question to getStructuredQueryTable

* Update unit tests

* Fix test, remove casts

* Migrate Query.prototype._databaseId to MLv2 in Question.prototype.query

* Use Question.prototype.isStructured
2024-01-09 15:04:46 +00:00
Mark Bastian
89cad7b33a Multiple Cypress Reporters (#37421)
* Multiple Cypress Reporters

This PR modifies our Cypress reporter to support multiple reporters, currently pretty mochawesome reports and junit xml files. This was enabled using the [cypress-multi-reporters](https://www.npmjs.com/package/cypress-multi-reporters) reporter. Additional reporters are added via yarn packages:
- [mocha-junit-reporter](https://www.npmjs.com/package/mocha-junit-reporter)
- [mochawesome](https://www.npmjs.com/package/mochawesome) which was already installed

One of the biggest challenges here is simply getting the config keys right, primarily `mochaJunitReporterReporterOptions` as opposed to the more sane `mochaJunitReporterOptions`, but I guess that the legacy of Java (☕). Also be aware that `mochawesomeReporterOptions` is NOT the same as `mochaAwesomeReporterOptions` but `mochaJunitReporterReporterOptions` is not `mochJunitReporterReporterOptions` for obvious reasons.

For future reference, note that multiple `mochawesome` reporters are available. Read more [here](https://glebbahmutov.com/blog/the-awesome-battle/) in the event that one of them is mochawesomer than the other and we want to level up.

Closes #37195

* Adding feedback per @iethree.

* Updated lock file
2024-01-09 08:01:07 -07:00
Jeff Bruemmer
d27cf2a8db fix aka (#37447) 2024-01-09 09:20:25 -05:00
Cal Herries
b031bf610c Fix CSV upload size in docs (#37432) 2024-01-09 09:19:50 -05:00
Alexander Polyankin
a5b10b2b4a Migrate data notebook step to MLv2 (#37302) 2024-01-09 14:17:06 +00:00
Ngoc Khuat
f83f88a38f Unify type of timestamp columns (#37160) 2024-01-09 12:14:52 +00:00
Alexander Polyankin
e11df0150b Remove legacyQuery from DashCardMenu (#37401) 2024-01-09 14:10:18 +02:00
Roman Abdulmanov
a996ec39e0 flaky test fix (#37435) 2024-01-09 11:46:35 +00:00
Nemanja Glumac
33d27d788f Migrate ViewTitleHeader to MLv2 (#37375) 2024-01-09 07:36:00 +01:00
Cam Saul
2476e2fa54 Make the with-premium-features test helper thread-safe (#37243) 2024-01-09 09:39:50 +07:00
Chris Truter
87ca1bd0b8 Add environ based suggestion for db config (#37298) 2024-01-09 09:37:38 +07:00
adam-james
9d25c26102 Fix static viz funnel chart rendering by changing row idx values (#37415)
* Fix static viz funnel chart rendering by changing row idx values

Pass into the js code the row data that the funnel component expects.

This means changing a row from for example, [0 120] to something like: ["January" 120] when :funnel.rows exists in the
viz-settings map.

Also add some helpers to the render test utils ns which will be used in the test.

* Add funnel test

* Add docstrings. Slight change in funnel render rows

* Slight rewrite for readability.
2024-01-08 17:54:46 -08:00
Jerry Huang
a08d0db559 add default sql server port (#37416) 2024-01-08 23:06:15 +00:00
Alexander Polyankin
65c00ab402 Move metric & segment based GUI query editor to Admin (#37371) 2024-01-08 19:10:23 +02:00
Jerry Huang
ed4e2970ba Fix collection/tree giving 500 error when there is only one user (#37381)
* Fix collection nil

* address comments
2024-01-08 09:09:23 -08:00
Case Nelson
510697255c [MLv2] Remove unused legacy MLv2 functions (#37325)
* Remove field_id

* Remove legacy-card-or-table-id

* Remove find_visible_column_for_legacy_ref
2024-01-08 10:08:50 -07:00
Jeff Bruemmer
0003c17efc docs - add max query rows limits (#36723) 2024-01-08 10:13:11 -05:00
Alexander Polyankin
95b2cbaa4d Use MLv2 to compute columns in parameter mapping (#37346) 2024-01-08 16:38:01 +02:00
Alexander Polyankin
3e61bc0794 Remove unused code (#37370) 2024-01-08 16:16:58 +02:00
Alexander Polyankin
8b0bcf2af5 Migrate topLevelFilters check to MLv2 (#37340) 2024-01-08 12:57:24 +00:00
Ngoc Khuat
fb59d1c0f1 log before syncing (#37339) 2024-01-08 10:24:52 +00:00
Uladzimir Havenchyk
a2d1fc39f2 Update browserslist db (#37336) 2024-01-08 09:04:44 +00:00
Chris Truter
8caeb58e0b Reduce boilerplate in permissions checks (#37319) 2024-01-08 10:52:00 +02:00
Lena
d87aeb8107 Add the rest of backend code to CODEOWNERS (#37333) 2024-01-08 09:44:24 +01:00
Cal Herries
c33f5cae6a Serdes for DashboardCardSeries (#37271) 2024-01-08 10:36:42 +02:00
Jerry Huang
6f4bf0e531 Remove other user collections defentively by adding other SQL query (#37240)
* add collection/list endpoint

* add children

* address changes

* address change

* fix test

* fix like

* address comments

* Update src/metabase/api/collection.clj

Co-authored-by: Noah Moss <32746338+noahmoss@users.noreply.github.com>

* address changes

* exclude other user collections in the sql query

* fix logic

* fix acrhive

* make remove-other-users-personal-collections cleaner

* fix tests

* fix errors

* fix other test

* add test

* fix merge

* fix formatting

* address comments

---------

Co-authored-by: Noah Moss <32746338+noahmoss@users.noreply.github.com>
2024-01-07 22:31:25 -08:00
Ngoc Khuat
37d9da3fd5 Drop then recreate a column should refingerprint and analyze the field (#37110) 2024-01-08 04:03:13 +00:00
Raphael Krut-Landau
2cc9cd9443 Avoid failing call to /api/model-index (#37284)
* When creating a new model, don't call /api/model-index because that returns error code 400
* Add two unit tests of DatasetEditor
* Fixes #31671
2024-01-05 17:48:30 -05:00
Case Nelson
1765f2f4ec add-implicit-clauses marks refs to ignore coercion (#36875)
* Don't coerce add-implicit-clauses

Fixes #33861

Renames `::nest-query/outer-select` to `qp/ignore-coercion` since it was
already applied outside nest-query and currently only controls that aspect.

* Fix whitespace

* Only add ignore-coercion if temporal-unit or binning are present

* Fix tests

* Only add ignore-coercion flag when coercion strategy is present
2024-01-05 20:36:09 +00:00
Jeff Bruemmer
3db339f81c update list of releases (#37323) 2024-01-05 15:13:56 -05:00
Jerry Huang
1249f38efe Increase Dashboard filters speed by putting field ids into set (#37318) 2024-01-05 19:04:32 +00:00
shaun
4c6d3e297a show error and disable save button when create metric fails (#36874)
* add reproducing e2e spec

* show failed button state and error message

* add failed button and error message to e2e spec

* Use findByLabelText and findByRole rather than cy.get

* Add role=alert and aria-label to FormErrorMessage

---------

Co-authored-by: Raphael Krut-Landau <raphael.kl@gmail.com>
2024-01-05 17:46:49 +00:00
Alexander Polyankin
a3d1c86265 Move FilterPanel to metabase/querying (#37260) 2024-01-05 17:26:47 +00:00
Braden Shepherdson
0ea582f5af [MLv2] Support = [End Date] - [Start Date] expressions (#37265)
Previously date arithmetic was only supported with a single date or
datetime +/- 0 or more intervals.

This adds a new flavour of temporal arithmetic - subtracting two
`:type/Date` or two `:type/DateTime` values yields a `:type/Interval`.

Fixes #37263.
2024-01-05 12:08:14 -05:00
Alexander Polyankin
0a9e9945ea Remove empty stages when modifying the list of query columns in viz settings (#37311) 2024-01-05 18:47:54 +02:00
Noah Moss
5e87c7b68a Fix issue with model index search (#37308) 2024-01-05 11:45:11 -05:00
andriibeee
9b3e51e018 Drop the *empty* and unused security holder dependency (#37283)
* Remove unused empty dependency

* Sync yarn.lock
2024-01-05 14:58:52 +01:00
Nemanja Glumac
02135eb41d Rename _getMLv2Query Question method to query (#37290)
#37233 made it possible to get rid of the temporary placeholder method name `_getMLv2Query` and replace with with the `query`.

* Rename `_getMLv2Query` method to `query`

* Update all references of `_getMLv2Query` to `query`
2024-01-05 14:42:17 +01:00
Nemanja Glumac
2edbf6badf Add nemanjaglumac to the Querying Components team (#37297) 2024-01-05 11:13:07 +01:00
Kamil Mielnik
a95e1a073c NotebookSteps, steps - migrate modifying queries to MLv2 (#36520)
* Rename query to legacyQuery

* Use step.query

* Port ExpressionStep to MLv2

* Use named export for ExpressionStep

* Move setup to the top of the file

* Add expressions parameter to createQueryWithClauses

* Update ExpressionStep unit tests

* Add a test for adding expressions

* Format code

* Add typing for openSteps and remove default parameter to prevent accidental omission

* Rename arguments

* Remove NotebookStep['update'] and update NotebookStepUiComponentProps['updateQuery']

* Remove NotebookStep['update'] from test util

* Add metadata argument to NotebookStepFn

* Remove unused NotebookStep['clean']

* Change previewQuery type to Query

* Update NotebookStep['revert'] to work with MLv2 only

* Use revert: null properly

* Clear breakouts before aggregations

* Update NotebookStepDef['active'] to work with MLv2 only

* Update NotebookStepDef['valid'], remove NotebookStepFn

* Remove TODO

* Update STEP.valid calls

* Port #36507 to master

* Migrate STEP.valid

* Format code

* Rename topLevelQuery to query and stagedQuery to legacyQuery

* Use INotebookStep["id"], simplify handleQueryChange

* Use database from metadata instead of question

* Format code

* Apply expressions before aggregations

* Improve typing in tests

* Fix expression name uniqueness

* Fix Lib.fields typing

* Use dropStageIfEmpty when removing expressions

* Fix unique name computation

* Port hasData

* Add stageIndex argument to NotebookStepDef['valid']

* Port query.isSourceQuery()

* Add junit.xml to .gitignore
- see https://github.com/metabase/metabase/pull/35929

* Make unit tests run

* Improve revert typing

* Update unit tests

* Update unit tests

* Update unit tests

* Rename filterStep1 to filterStep and filterStep2 to postAggregationFilterStep

* Update unit tests

* Update unit tests

* Update unit tests

* Update unit tests

* Convert unit tests to TS

* Simplify getQuestionStepsForMBQLQuery

* Refactor tests

* Remove test for new queries - a Lib.Query object cannot exist without the "data step"

* Lift database to reuse it

* Port getQuestionSteps

* Skip e2e test for metabase#19745 due to metabase#36574

- See https://github.com/metabase/metabase/issues/36574
- See https://metaboat.slack.com/archives/C04CYTEL9N2/p1702063378269379
- See https://metaboat.slack.com/archives/C0643FZ5E83/p1702365832126429?thread_ts=1702362649.548849&cid=C0643FZ5E83

* Update comment

* Revert type change

* Revert "Use dropStageIfEmpty when removing expressions"

This reverts commit d529503e79.

* Format code

* Skip 19745 tests

* Format code

* Use dropStageIfEmpty instead of cleanNesting

* Try to drop only the updated stage

* Use stageIndex instead of -1 in preview3

* Format code

* Ignore question.isStructured() check

* Finish migrating getQuestionSteps

* Migrate query.clean in Notebook to MLv2

* Use reduceRight instead of reverse + reduce

* Fix typo

* Move hasBreakouts computation until after the redundant stage is removed

* Update e2e sandboxing test to assert showing permissions error instead of magically dropping an unsupported join
- @see https://metaboat.slack.com/archives/C01LQQ2UW03/p1704294434403599

---------

Co-authored-by: Tamás Benkő <tamas@metabase.com>
Co-authored-by: Alexander Polyankin <alexander.polyankin@metabase.com>
2024-01-05 16:04:07 +07:00
adam-james
78b66bcae6 Number viz render method properly uses :scalar.field name to render value (#37274)
* Add number-viz test to pulse integration test.

This is a currently failing test. The first card succeeds because the 'narrowing' to 1 field is done in the query
directly, so the expected single value is shown.

The second (currently failing) card has the viz for a 'number' applied but the query isn't 'narrowed' at all, so we
see the failure.

* Fix the :scalar render to look at the column specified in :scalar.field

* Addressed feedback: improved get-col-by-name impl. and added test comment
2024-01-04 15:56:35 -08:00
John Swanson
b176982af6 Use simple Secrets for ApiKeys (#37205)
* Use simple `Secret`s for ApiKeys

I decided to POC the idea I had here:
https://metaboat.slack.com/archives/CKZEMT1MJ/p1703790833895029

This wraps the generated ApiKeys in a special Secret type. If the object
is accidentally printed, logged, etc. it will appear as "<< REDACTED
SECRET >>" rather than the actual value.

When we're actually *using* the Secret, we call `expose` on it to turn
it into a String.
2024-01-04 14:58:25 -08:00
Mark Bastian
27587264f4 Fixing case of invalid graph.dimension (#37279)
When trying to render a card with viz settings containing a nonexistent dimension, an error would result in `mult-x-axis-rowfn` causing a failure to render.

This fix simply replaces `map` with `keep` in `metabase.util.ui-logic/mult-x-axis-rowfn` and `metabase.util.ui-logic/mult-y-axis-rowfn` so that `nil` values are dropped if a bad dimension or metric name is provided.

The following easily shows the broken case (now fixed). Previously, an error was rendered. Now you get the chart.

```clojure
;; REPRO
(comment
  (ns tickets.37266-slack-error
    (:require
     [clojure.test :refer :all]
     [dev.render-png :as render-png]
     [metabase.models :refer [Card]]
     [metabase.pulse.render.body :as body]
     [metabase.query-processor :as qp]
     [metabase.test :as mt]
     [toucan2.core :as t2]))

  (let [busted? true]
    (mt/dataset test-data
      ;; Note that this uses orders since we have that as test data.
      (mt/with-temp [Card {base-card-id :id}
                     {:dataset_query          {:database (mt/id)
                                               :type     :query
                                               :query    {:source-table (mt/id :orders)
                                                          :aggregation  [[:count]]
                                                          :filter       [:between [:field (mt/id :orders :created_at) nil] "2019-05-16" "2019-08-16"]
                                                          :breakout     [:field (mt/id :orders :created_at) {:temporal-unit :week}]}}
                      :display                :line
                      :visualization_settings {:table.pivot_column      "state"
                                               ;; This is also intentionally broken
                                               :graph.metrics           (if busted?
                                                                          ["frooby"]
                                                                          ["count"])
                                               :graph.show_trendline    false
                                               :graph.x_axis.title_text "Week"
                                               :graph.y_axis.title_text "PR Review Activity"
                                               ;; Using a missing dimension name breaks the results
                                               :graph.dimensions        (if busted?
                                                                          ["_sdc_extracted_at"]
                                                                          ["created_at"])
                                               :graph.show_values       false
                                               :table.cell_column       "count"}}]
        (render-png/render-card-to-png base-card-id)))))
```
2024-01-04 14:31:09 -07:00
John Swanson
a2cfb6177b Error if DB downgrades are required (#37239)
* Error if DB downgrades are required

Before running migrations, check the major versions of:

- the latest database migration that was actually applied (e.g. if v49
ran migrations, this would be 49)

- the latest database migration that liquibase is aware of (e.g. if
we're currently running v48, this would be 48)

If the database has executed migrations that we don't know about, throw
an exception and exit with a helpful error message telling the user they
need to run `migrate down` from the newer version before they can
downgrade.

Fixes #27906
2024-01-04 12:34:18 -08:00
Alexander Polyankin
d1df0c6c68 Rename Question.query() to Question.legacyQuery() (#37233)
* Rename query to legacyQuery

* Fix legacy query ref
2024-01-04 21:52:34 +02:00
Case Nelson
e27760d6e5 [MLv2] Support exclude date filter for filter args display name (#37246)
* [MLv2] Support exclude date filter for filter args display name

* Update spec

* Add excludes to filter args display
2024-01-04 19:46:24 +00:00
Sloan Sparger
e8ebbb3f71 Localize text for filter apply button (#37273) 2024-01-04 13:36:48 -06:00
Case Nelson
8daa10adeb [MLv2] Fix field-values-search-info returning string ids (#37238)
* [MLv2] Fix field-values-search-info returning string ids

* Skip join test because the text prompt still doesn't match

* Fix the test

---------

Co-authored-by: Alexander Polyankin <alexander.polyankin@metabase.com>
2024-01-04 11:37:37 -07:00
John Swanson
b8a4e0d5fb Add last_name to ApiKey users (#37234)
When we generate a `:common_name` on Users, we check for the presence of
both `first_name` and `last_name`. If either is `nil`, we don't generate
a `common_name`.

ApiKey users only have one name (the name of the ApiKey itself) but we
should set the `last_name` to an empty string. This way, the common name
will still be generated.

Because the `metabase.models.user/insert-new-user!` function requires a
NonBlankString for `first_name` and `last_name` if they're present, I
went back to calling `t2/insert-returning-instances!` directly.
2024-01-04 10:11:09 -08:00
Lena
a300c41349 Create CODEOWNERS with camsaul owning src/metabase (#37267)
For auto-requesting the reviews on backend PRs.
2024-01-04 18:40:34 +01:00
Jerry Huang
c68c541851 Add shallow and location param to /api/collection/tree (#36919)
* add collection/list endpoint

* add children

* address changes

* address change

* fix test

* fix like

* address comments

* Update src/metabase/api/collection.clj

Co-authored-by: Noah Moss <32746338+noahmoss@users.noreply.github.com>

* address changes

---------

Co-authored-by: Noah Moss <32746338+noahmoss@users.noreply.github.com>
2024-01-04 08:55:34 -08:00
Braden Shepherdson
c157156ddc [MLv2] Removing a final JOIN condition removes the whole join (#37229)
This still throws an exception on trying to directly remove the final
JOIN condition. But if the condition is being removed because a field it
depends on is being removed (eg. a custom column, a breakout, a
previous stage aggregation) then the entire JOIN is also removed, in the
usual cascading fashion.

Fixes #36690.
2024-01-04 09:24:24 -05:00
Cal Herries
61849910e8 CSV uploads: support more date formats (#37078) 2024-01-04 14:36:59 +02:00
Nemanja Glumac
52b8d410ad Adapt the stress-test workflow to work with replay-chromium (#37255)
* Fix stress-test workflow

Use `replay-chromium' browser for these tests as well.
This gives us a bit more confidence because we're using
the same browser in both "regular" and "stress-test" runs.

[ci skip]

* Enable Replay via envvar

[ci skip]
2024-01-04 12:47:49 +01:00
Cal Herries
2e3a43675d Redshift support for CSV uploads (#37005) 2024-01-04 10:38:22 +00:00
Chris Truter
ff9a04cea1 Guard against version duplication (#33803) (#37237) 2024-01-04 10:09:46 +00:00
Mark Bastian
055561b434 Consistent formatting of all columns in Excel exports (#37208)
* Removing Time portion of Timestamp when formatted as Date in Excel

This is a starting changeset for fixing the issue "Timestamp is always present in dates when exporting to Excel in the embedded application. #14393", which demonstrates a failure mode in applying column-formatting to Excel downloads. This commit should fix the underlying issue as well as update formatting for remaining CSV file download discrepancies.

The goal of this commit is to get us to a baseline state for some small refactorings to combine our formatting paths for CSV, JSON, and Excel exports.

* Updating common logic and tests to reflect how global settings are passed in and applied to format-temporal-str

* Updating `number-format-strings` to not need semantic type.

* Adding tests for new Excel-export logic.

* Fixing cases for currency where we must specify that `::mb.viz/currency-in-header` is false.

* Fixing formatting tests

* Updating unit test to reflect a global abbreviated dates preference.

* Adding column type defaults for certain test cases.

* Updating logic and tests in xlsx exports

Logic in `metabase.query-processor.streaming.common` further unifies the idea of merging all settings first, then making decisions based on that. It also makes the downstream code more functional, as that code doesn't repeatedly reach for global settings.

`metabase.query-processor.streaming.xlsx-test` has been updated to reflect this change. In particular, the helper function `format-string` now builds the right input settings rather than passing settings through to be accumulated later.

* Fixing two more tests.

* Fixing remaining unit tests

- Update `metabase.api.card-test` with multiple test cases for different formats.
- Update `export-format-test` to lock temporary settings for consistency.
- `default-number-format?` to `unformatted-number?` and include "currency" as a potential unformatted type.

* Consistent application of global viz settings

This PR adds a function that will inject the global viz settings into `viz-settings-for-col` if not provided by the query processor. This also simplifies the `xslx-test` ns.

* Treating :default unit as no unit.
2024-01-04 06:07:37 +00:00
Ngoc Khuat
c537fddf2b RFC: new migration id format vMM.TIMESTAMP (#36787) 2024-01-04 10:13:01 +07:00
Cam Saul
a1769aebc0 Finally introduce the mt/test-helpers-set-global-values! pattern (#37241) 2024-01-04 08:57:19 +07:00
Uladzimir Havenchyk
2b8123d95f Make e2e tests less flaky (#37236)
* Make brush filter tests more stable

* Make repro for 34382 less flaky

* fixup! Make repro for 34382 less flaky

* More asserts
2024-01-03 21:26:01 +00:00
Cam Saul
7427b45aa6 Implement brush filter helper functions (#37211)
* Implement truncate, add, and unit-diff date util functions for Cljs

* Implement filter update util fns (#37103)

* Fix circular references

* Test fixes 🔧

* PR feedback

* Clarify things
2024-01-03 21:19:37 +00:00
Raphael Krut-Landau
9c2fed9db6 When updating an alert, don't also update the question (#36866)
The additional call to apiUpdateQuestion is not needed, since you can't edit an alert without first saving the question

Fixes #36395
2024-01-03 15:55:22 -05:00
Cam Saul
064b052484 Implement truncate, add, and unit-diff date util functions for Cljs (#37210)
* Implement truncate, add, and unit-diff date util functions for Cljs

* Fix circular references

* Test fixes 🔧
2024-01-03 20:31:27 +00:00
Sloan Sparger
9dacf8071e Add sloansparger to AdminWebapp team (#37242) 2024-01-03 14:23:08 -06:00
Case Nelson
e05ebc41b6 [MLv2] Normalize expression-clause (#37206) 2024-01-03 10:58:51 -07:00
Nemanja Glumac
51ade7aa59 Upload only failed Replay e2e recordings (#37235) 2024-01-03 18:58:12 +01:00
Uladzimir Havenchyk
43fa865167 Add e2e test for a line chart with axis - number (#37221) 2024-01-03 16:43:38 +00:00
Nemanja Glumac
ae0060c84c Cypress E2E tests: Switch to using ReplayIO (#37228)
* Remove Cypress cloud integration

* Remove custom Chromium

From now on, we'll use `replay-chromium` browser.

* Start using ReplayIO for all E2E test runs

* Use the default Chrome for Percy visual tests

* Mark flaky tests
2024-01-03 17:29:03 +01:00
metamben
46d3779b51 Support replacing expression with modified names (#37204) 2024-01-03 19:22:31 +03:00
Alexander Polyankin
2a860398fe Add segment editor tests (#37225) 2024-01-03 18:02:08 +02:00
lbrdnk
7e89a176af Use counter instead of gensym to make mongo field aliases unique (#37189)
* Add test

* Use atom to track next alias index

* Update testing string

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>

* Use volatile instead of atom for index tracking

---------

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>
2024-01-03 16:10:14 +01:00
Ryan Laurie
e92ba9f339 upcoming release status (#37223) 2024-01-03 15:02:57 +00:00
Jeff Bruemmer
58c16dce59 docs - upload privileges (#37091) 2024-01-03 10:00:22 -05:00
Kyle Doherty
7912f5dbe0 Tighten visual design of charts (#36991)
* remove box-shadow from dashboard cards, add border

* set scalar font weight to 700

* remove extra bold style from dash headings

* set font weight for row and line axis ticks and labels to 700, adjust size

* tweak gridline dash array size for cleaner lines

* make scalar value titles the same as other dashcard titles

* even out legend title spacing on cards

* lighten axis domain line

* use border color for axis line on RowChart

* make legend 2nd read, adjust spacing & alignment

* adjust dashcard legend size for non linebar viz

* use color instead of colors for theme safety (code review)

* update expectedWidth value to account for new smaller font size

* account for new dash card border in comparisons

* update card border

* specs

* flakes

---------

Co-authored-by: Aleksandr Lesnenko <alxnddr@gmail.com>
Co-authored-by: Aleksandr Lesnenko <alxnddr@users.noreply.github.com>
2024-01-03 11:44:42 -03:00
Alexander Polyankin
c8ab535cf3 Filter modal date tests (#37218) 2024-01-03 16:37:48 +02:00
Jeff Bruemmer
927f29b16d docs - sections on cloud (#37198) 2024-01-03 09:21:35 -05:00
Alexander Polyankin
71b73668b7 [MLv2] [FE] MultiSelect-based filter fixes (#37072) 2024-01-03 13:41:32 +00:00
Alexander Polyankin
0ef5af2b53 Fix incorrect time format strings in filters (#37217) 2024-01-03 13:22:09 +00:00
Chris Truter
521b019f30 Add Chris Truter to team.json (#37214) 2024-01-03 13:51:58 +02:00
Ngoc Khuat
26c94e76cd Modify type metabase_field.database_required to bit(1) in mysql (#37213) 2024-01-03 11:05:44 +00:00
Noah Moss
70f0207415 Create metabase.permissions.util namespace (#37177) 2024-01-02 23:28:16 +00:00
Braden Shepherdson
c382f56ecb [MLv2] Drop redundant :fields clauses from stages and joins (#36959)
If they're equivalent to the default, they can be removed (for stages)
or replaced by `:all` (on joins).
2024-01-02 17:20:49 -05:00
Vamsi Peri
a1bc636633 Update enterprise readme to 2024 (#37207) 2024-01-02 17:10:14 -05:00
shaun
c1f3086239 Add FormGroupWidget component (#37096)
* Add FormGroupWidget component
* add loading state and placeholder text

Co-authored-by: Ryan Laurie <iethree@gmail.com>
2024-01-02 21:59:49 +00:00
John Swanson
f5a1a9f1ff Oops - remove API bits from ApiKey model (#37085)
Noah pointed out that the ApiKey model shouldn't have API-layer bits in it (like referring to the `api/*current-user-id*`), so I made `metabase.api.api-key` populate those fields instead.

... except I forgot to delete the code from the model that populated them as well. Let's do that now.
2024-01-02 21:45:53 +00:00
shaun
2b62c217e4 Add CopyTextInput component (#37095)
* Add CopyTextInput component

* add default props

---------

Co-authored-by: Ryan Laurie <iethree@gmail.com>
2024-01-02 14:38:15 -07:00
Ryan Laurie
7a597a3da3 Automated release status updates in Slack (#36830)
* daily automated slack reminders about releases

* fix things that don't work at all

* Update .github/workflows/release-status.yml

Co-authored-by: Uladzimir Havenchyk <125459446+uladzimirdev@users.noreply.github.com>

* make synk happy?

---------

Co-authored-by: Uladzimir Havenchyk <125459446+uladzimirdev@users.noreply.github.com>
2024-01-02 14:37:24 -07:00
shaun
9ce47053cf Fix Typo in FormSelect (#37092) 2024-01-02 14:34:01 -07:00
John Swanson
377b713b7c Return group, not group_name with ApiKeys (#37061)
The frontend needs the group ID as well as the name, so let's return both in a similar shape as `updated_by`.
2024-01-02 12:41:52 -08:00
John Swanson
fbb1202102 Add a DELETE endpoint for API Keys (#37051)
When the endpoint is hit, we delete the ApiKey from the database. The
user is left behind to ensure that we don't break foreign keys, and to
enhance auditability.
2024-01-02 11:58:07 -08:00
Noah Moss
6c89e943a6 Update copyright year in EE code (#37190) 2024-01-02 18:37:35 +00:00
Ryan Laurie
cfd6485f75 Update relative date filter tests for 2024 (#37200) 2024-01-02 11:07:28 -07:00
Noah Moss
53c19b2b3e remove metabase.models.permissions.util (#37178) 2024-01-02 12:49:25 -05:00
Jeff Bruemmer
958cfdf1b6 docs - embed quick start (#37059) 2024-01-02 10:37:09 -05:00
Luis Paolini
65ebed465c Update readme to 2024 (#37181) 2024-01-01 17:28:03 -03:00
Uladzimir Havenchyk
1284066a68 Add e2e tests for brush filters in line chart (#37163)
* Add e2e tests for brush filters in line chart

* Wait for dataset

* debug

* Explicitly set viewport

* Get a bit left

* Shift left

* Do not set viewport

* Revert "Do not set viewport"

This reverts commit b41a039aa8.

* Remove duplicated test
2023-12-29 18:28:43 +00:00
Alexander Polyankin
af308469b3 Filter modal hooks tests (#37136) 2023-12-29 17:33:24 +00:00
Uladzimir Havenchyk
1c33e4dcaa Add e2e tests for brush filters in map (#37164)
* Add e2e tests for brush filters in map

* Add force

* Simplify assertion

* Specify viewport
2023-12-29 18:59:47 +03:00
Uladzimir Havenchyk
c3d6f71e3d Show dots if tab content is too wide in Filter Modal (#37148) 2023-12-29 17:33:20 +03:00
adam-james
dc667f2c7c Add internal setting for table render row limit (#36996)
* Add internal setting for table render row limit

This change will keep default behaviour of a 10 row limit but allow users to set an env variable to change this default.

* test that table render row limits can be adjusted w/ env var.

Add a test that shows the table render respects the default 10 row limit, and also show that if the user uses the
environment variable `MB_ATTACHMENT_TABLE_ROW_LIMIT`, then they can change the row limit.

* Explicitly unset env. var in the test so it truly tests the default

* Adjust :getter for setting so that defaults are used appropriately

* Fix tests that expected exact text matches on some hiccup nodes

* New default of 20.

* Add a limit of 100 to the rows and add a test for it too.
2023-12-28 15:19:57 -08:00
Noah Moss
d467106efa Wrap can-append-test with mt/with-empty-db to fix seemingly unrelated download perms test (#37159) 2023-12-28 22:06:12 +00:00
Noah Moss
f9d653bba5 Try again to fix failing perms tests by making testing macro more robust (#37141)
* Adds a new `metabase.permissions.test-util` namespace
* Adds a new `with-restored-perms!` macro which ensures that permissions are reset after the test body runs
* Updates `with-all-user-data-perms` to use `with-restored-perms!` under the hood, and renames it to `with-all-user-data-perms!`

This is my attempt to fix the state issues with permission tests in a more robust way. Generally, the `permissions` and `sandboxes` tables aren't too large, so it shouldn't be a ton of overhead to just fully reset these tables after a test runs—and certainly doesn't compare with the time lost to debugging state issues between perms tests. (I actually saw this test namespace run one second _faster_ with these changes, in a very unscientific test.)

I'm planning on adding more utils to the `metabase.permissions.test-util` namespace to make perms tests easier to write. But want to keep this PR focused on the change that will (hopefully) fix the tests failing on master.
2023-12-28 12:13:16 -05:00
Nemanja Glumac
665c6a6ee8 Prevent Admin > People header from "jumping" (#37130)
Fixes #37129.
2023-12-28 17:50:34 +01:00
Nemanja Glumac
ccbeab32e6 Fix typo in ChartSettings props in a FE unit test (#37153)
quesiton ---> question
2023-12-28 16:43:10 +01:00
Oleg Gromov
ae2c135400 Fix tabs ee test (#37152) 2023-12-28 15:27:17 +00:00
Alexander Polyankin
2c7b08d214 Deprecate TokenField (#37137) 2023-12-28 15:57:41 +02:00
Bas Beelen
88fc9d18ca Match SparkSQL database-type case insensitive (#27444)
* Match SparkSQL database-type case insensitive

* Use lower-case-en to match SparkSQL database-type

---------

Co-authored-by: Bas Beelen <bas.beelen@channable.com>
Co-authored-by: lbrdnk <lbrdnk@users.noreply.github.com>
2023-12-28 14:17:33 +01:00
Oleg Gromov
22dd37bebc Fix card loading state in different tabs when parameters change (#37134)
* Compare parameters in fetchDataCards to clearCache
* Fix click-behavior suite
* Add tabs/card loader e2e test
* Add a comment
* Update test name to include issue number
2023-12-28 13:12:26 +00:00
Noah Moss
36055cd53d Remove extra clj-kondo library config (#37138)
Ignore another clj-kondo library config missed by https://github.com/metabase/metabase/pull/36889

This was causing dirty changes to be left in the repo after running `bin/kondo.sh`. The script should be clean after this change, I think.
2023-12-27 22:50:39 -05:00
Noah Moss
01041921c5 Fix misc clj-kondo issues in tests (#37139)
Fixes misc clj-kondo errors in tests (and one random whitespace issue in a src namespace).
2023-12-27 16:18:37 -05:00
Alexander Polyankin
913c0b0455 Migrate dashboard with parameters -> query with filters transformation to MLv2 (#37107) 2023-12-27 18:20:05 +02:00
Noah Moss
c963029d3f fix failing download perms test (#37093) 2023-12-27 10:05:18 -05:00
Anton Kulyk
2c249bfa48 Add right padding to filter picker back button (#37131) 2023-12-27 14:23:48 +00:00
Uladzimir Havenchyk
1a176e8803 Upgrade chromatic and sync storybook packages (#37124)
* Upgrade chromatic

* Revert back to NODE_ENV

* Sync storybook packages

* Replace imports from clients-api to addons
2023-12-27 15:30:56 +03:00
Alexander Polyankin
e73d74152f Mantine MultiSelect & Autocomplete (#37013) 2023-12-27 13:09:11 +02:00
Alexander Polyankin
b14003c6de Add umbrella isQueryEditable function to ease migration from MLv1 query (#37108) 2023-12-27 13:03:10 +02:00
Alexander Polyankin
b8d02bf5d2 Remove unused dashboard code (#37106) 2023-12-27 13:02:21 +02:00
Filip Hric
6296d32f1e Fix flaky E2E #25322 reproduction (#37041)
Add delay instead of throttle.

Fixing a flake analyzed in this document.
https://replayio.notion.site/dashboard-filters-reproductions-25322-loading-list-19324262f19d404ba03787c9f70968ab

The test `25322-loading-list-values.cy.spec.js` has become flaky because the period of time to find loading-spinner element is too short. This is thanks to API response being fast.

in the past, this was partially remedied by adding `setThrottle()` method to slow the API response down. while it is a good initial approach, it is not resilient to a situation when the data transfer size becomes smaller.

I’m suggesting changing the method to setTimeout that will give the test enough time to catch the loading state.

In the future, this particular test would be a good candidate for a component test as it is quite granular.
2023-12-27 11:10:50 +01:00
Nemanja Glumac
570cda6a88 Upgrade Replay Cypress plugin to v1.7.11 (#37116)
From the maintainer: "includes a fix for a bug your tests were hitting in a couple places".
2023-12-27 09:52:39 +01:00
Nemanja Glumac
6ffa86b55a Delete unused code in entities (#37117)
This code has been commented out for the last six years!
2023-12-27 09:07:29 +01:00
Oisin Coveney
d2f9e43753 Design Fixes for Setup Flow (#37060)
* Add fixes

* Quick changes

* Fix e2e issues

* Attempt to fix public-question test

* Update embedding setup icons and disabled card state

* Potential fix for failing e2e

* Remove failing e2e tests as it is covered by unit tests

---------

Co-authored-by: Denis Berezin <denis.berezin@metabase.com>
2023-12-26 18:45:39 +07:00
Nicolò Pretto
08d7467f4a Embedding settings cleanup - Milestone 1 (#37043)
* feat: single view for embedding settings regardless of setting status (#36802)

* feat: single view for embedding settings regardless of setting status

* refactor: rename component as now it doesn't container legalese

* rename component and refactor

* remove unused prop type

* test: update e2e

* fix not handling null value

* fix: keep same behaviour for event

* Update frontend/src/metabase/admin/settings/components/widgets/EmbeddingSwitchWidget/EmbeddingSwitchWidget.tsx

Co-authored-by: Mahatthana (Kelvin) Nomsawadi <me@bboykelvin.dev>

* use target instead of currentTarget

---------

Co-authored-by: Mahatthana (Kelvin) Nomsawadi <me@bboykelvin.dev>

* remove deprecated event on embedding settings (#36857)

* feat: Update the UI and copy of the embedding options cards (#36819)

* feat: adds icon and some other small ui change

* update buttons and ui

* update links/buttons for  interactive embed option

* update unit tests

* make e2e pass with the new changes

* make unit test pass

* integration/unit tests for embedding settings

* fix herf -> href 🫠

* fix e2e suite

* refactor: splti components in two

* update url as by updaterd product doc

* fix imports

* update width as by design

* fix linting error

* fix copy

* update layout, paddings, fontsize etc

* add upgrade text

* other ui fixes

* last minute copy change

* inline variable in tests to avoid beforeEach

* fix typo

* fix e2e by moving assertion on the correct page

* fix typo in unit

* update link as per product doc

* inlie urls

* only return used parts in setup function

* e2e: update e2e upgrage url

* remove oss version of the interactive embedding settings page (#36938)

* remove oss version of the interactive embedding settings page

* fix redirect logic + add tests

* add key to make react not complain

* merge lists of embedded questions and dashboards to have new heading structure (#36944)

* feat: adds icon and some other small ui change

* update buttons and ui

* update links/buttons for  interactive embed option

* update unit tests

* make e2e pass with the new changes

* make unit test pass

* integration/unit tests for embedding settings

* fix herf -> href 🫠

* fix e2e suite

* refactor: splti components in two

* update url as by updaterd product doc

* fix imports

* update width as by design

* fix linting error

* remove oss version of the interactive embedding settings page

* merge lists of embedded questions and dashboards to have new heading structure

* fix redirect logic + add tests

* add key to make react not complain

* use plain strings instead of regex when possible

* remove regex for testids

* fix copy

* update layout, paddings, fontsize etc

* add upgrade text

* other ui fixes

* last minute copy change

* inline variable in tests to avoid beforeEach

* fix typo

* fix e2e by moving assertion on the correct page

* fix typo in unit

* update link as per product doc

* inlie urls

* only return used parts in setup function

* e2e: update e2e upgrage url

* update interactive embedding settings page ui (#36949)

* feat: adds icon and some other small ui change

* update buttons and ui

* update links/buttons for  interactive embed option

* update unit tests

* make e2e pass with the new changes

* make unit test pass

* integration/unit tests for embedding settings

* fix herf -> href 🫠

* fix e2e suite

* refactor: splti components in two

* update url as by updaterd product doc

* fix imports

* update width as by design

* fix linting error

* remove oss version of the interactive embedding settings page

* merge lists of embedded questions and dashboards to have new heading structure

* update interactive embedding settings page ui

* fix redirect logic + add tests

* add key to make react not complain

* use plain strings instead of regex when possible

* remove regex for testids

* fix copy

* update layout, paddings, fontsize etc

* add upgrade text

* other ui fixes

* last minute copy change

* inline variable in tests to avoid beforeEach

* fix typo

* fix e2e by moving assertion on the correct page

* fix typo in unit

* update link as per product doc

* inlie urls

* only return used parts in setup function

* e2e: update e2e upgrage url

* rename test files with correct naming (#37044)

* rename test files with correct naming

* test: fix setup functions and add enterprise suite

* Fix interactive embedding link target

* Update embedding toggle copy

* Use default setting labels

* Fix failed E2E test

---------

Co-authored-by: Mahatthana (Kelvin) Nomsawadi <me@bboykelvin.dev>
Co-authored-by: Denis Berezin <denis.berezin@metabase.com>
Co-authored-by: Mahatthana Nomsawadi <mahatthana.n@gmail.com>
2023-12-25 11:35:20 +00:00
Ngoc Khuat
d3dabc63c6 Bigquery sync partitioned fields (#36892) 2023-12-25 11:10:54 +07:00
Nicolò Pretto
39769b6ad2 add "application-colors" in createMockSettings (#37077)
* adds "applications-colors" to the settings type and to createMockSettings
this removes errors in jest output when using enterprise plugins

* use EnterpriseSettings to avoid typechecking errors
2023-12-22 22:12:52 +01:00
Noah Moss
761d533b7b BE analytics events for embedding (#36962) 2023-12-22 14:59:59 -05:00
Denis Berezin
3ba26345e0 Add SegmentedToggle component from mantine (#37007)
* Add SegmentedToggle component from mantine

* Code review fixes

* Fix dependencies issue
2023-12-23 02:06:49 +07:00
Braden Shepherdson
9c2cf97ab8 [MLv2] Resolve a string :fk-field-id to a numeric ID if possible (#37079)
Progress towards #37067, might not fix it entirely. There may be other
bugs stemming from the string `:fk-field-id`, but I can't reproduce it
locally.
2023-12-22 13:21:00 -05:00
Alexander Solovyov
1c06fac73c Clear error message when unable to decrypt encrypted json field (#36701) 2023-12-22 21:00:55 +03:00
Oisin Coveney
1d97082c80 [Epic #35961] Milestone 3 - Add Interactive Embedding CTA to Embed Modal (#36890)
Co-authored-by: Mahatthana (Kelvin) Nomsawadi <me@bboykelvin.dev>
2023-12-22 09:18:40 -08:00
Uladzimir Havenchyk
fdfaf27f12 Address vulnerabilities found by snyk (#36461)
* Upgrade path-parse to 1.0.7

* Upgrade color package to 4.2.3

* Upgrade d3-color to 3.1.0
2023-12-22 20:18:06 +03:00
Cal Herries
8d56226c5c Fix flaking database-schema-filtering-test for bigquery (#36900) 2023-12-22 18:24:58 +02:00
John Swanson
2550abbbc1 Add updated_by to API Keys (#37014)
This required a bit of modification of the DB.

First, I had named the column meant to hold the ID of the user who last updated an API key as `updated_by`. But it seemed like `updated_by` was the natural field to hold the user name that FE wanted, and I didn't want to clobber an existing field with `hydrate`.

So, I renamed the existing column to `updated_by_id` and used `updated_by` to hold the hydrated user that updated the ApiKey.

Second, for consistency, I renamed `created_by` to `creator_id`.

The logic for presenting an ApiKey was getting a bit complicated and spread out over many different endpoints, so I pulled it out into its own function that's called from almost every endpoint defined in the `metabase.api.api-key` namespace. Note that it calls `(t2/hydrate api-key :updated_by :group_name)` - but I verified that this will not result in additional DB calls if the model was already hydrated.
2023-12-22 06:38:23 -09:00
Cal Herries
f59b18a1a0 CSV appends Milestone 0, Merge 1: add endpoint to append to table (#36640) 2023-12-22 15:04:54 +00:00
Oleg Gromov
922e6fd7b0 Fix flaky e2e notebook / should work on custom column with case (#37049) 2023-12-22 14:00:27 +00:00
John Swanson
e25f2ab9f0 Api key update, regenerate, and list (#37001)
While implementing this, I realized that I made a mistake when
implementing the Create endpoint - I returned a `group_id` instead of
the `group_name` that frontend had requested to get back from the List
endpoint. I think for consistency's sake it's best to return
`group_name` from both endpoints.

To achieve this, I added a hydration method to the ApiKey. It adds the
name of a single group to each ApiKey, preferring group names that
aren't "All Users".

Beyond that, the 3 new endpoints are pretty straightforward. All are
audit logged, and I added audit logging to creation as well.

Note that the API Key prefix is audit logged. I don't think this should
be a problem - we can think of the prefix as the "public" portion of the
key, like a username.
2023-12-22 04:58:58 -09:00
Alexander Polyankin
2b8f519833 Remove inconsistency with readOnly and isEditable (#36970) 2023-12-22 15:33:04 +02:00
lbrdnk
ebb9d909b5 Update with-report-timezone-id and related (#36858)
* Use driver multi instead of jdbc specific calls

* Factor out `notify-database-updated` function

* Add notify databases test utils

* Remove parallel and add TODO comment
2023-12-22 13:08:35 +01:00
lbrdnk
501c8bccce Add remove remark functionality to Athena (#37011)
* Add remove remark functionality to athena

* Update frontend/src/metabase/databases/constants.tsx

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>

* Update comment

---------

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>
2023-12-22 12:53:35 +01:00
Ngoc Khuat
9f690db208 Kondo: ignore all libraries config (#36889)
* Kondo: ignore all libraries config

* Add README

* Update .gitignore
2023-12-22 02:30:43 +00:00
Oleg Gromov
5f968e6bb5 Fix e2e notebook / "should process the updated expression when pressing Enter" (#37045) 2023-12-21 16:49:01 +00:00
Anton Kulyk
72893a8f1b Fix dashcard query sometimes errors after replacing its card (#36987) 2023-12-21 13:11:00 +00:00
shaun
61025e0340 Add types to custom cypress commands for auth (#36958) 2023-12-21 06:30:15 +00:00
Mahatthana (Kelvin) Nomsawadi
780e632464 Remove deprecated page (#36967) 2023-12-21 06:17:33 +00:00
Lars Klingen
c7f1d37040 Bigquery - Ignore retry on query cancellation (#36625)
* Dont retry cancelled queries on Bigquery

* Add test coverage for ignoring retry on cancellation

* Cancel running BQ jobs on cancellation request

* Fix indentation

* Throw exception with cancelled flag

* Join lines

* Change unique query string

* Fix parentheses

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>

* Change e to ex-data

* Set namespace explictly in mock exception

* Rename query identification string

* Use bigquery namespace

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>

* Remove query cancellation code

* Remove comment

---------

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>
2023-12-21 06:40:28 +01:00
Noah Moss
362ef924a0 Tweak Malli schema in update-users-recent-views! (#37031) 2023-12-21 04:20:30 +00:00
Noah Moss
7305c326db Bump liquibase (#36964)
Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>
2023-12-21 04:13:29 +00:00
Mark Bastian
f8b533c904 Renamed columns are displayed correctly in downloads (#18572) (#37016)
* Renamed columns are displayed correctly in downloads (#18572)

When custom viz settings or metadata is applied to questions and models, the downloaded artifact labels do not always mirror what is displayed on the tabular view in Metabase. This happens for several reasons:

- The `:visualization_settings` were not applied to CSV and JSON downloads
- `update-card-viz-settings` in `metabase.query-processor.middleware.visualization-settings` did not correctly merge keys, resulting in dropped column names in Excel file
- The logic for reconciling column metadata in a result set and the keys in `:visualization_settings` of a query result is not straightforward

This PR is an attempt to move this consistency in the right direction without fixing all the challenges of field matching as discussed in [this thread](https://metaboat.slack.com/archives/CKZEMT1MJ/p1703091539541279) and [this issue](Duplicated columns in a source query cannot be distinguished #36185) as this sounds like a significant effort.

The following changes were made:

1. Update `metabase.query-processor.middleware.visualization-settings/update-card-viz-settings` to merge field settings, if present, into `column-viz-settings` without introducing new keys, especially ambiguous keys as follows:

```clojure
(defn- update-card-viz-settings
  "For each field, fetch its settings from the QP store, convert the settings into the normalized form
  for visualization settings, and then merge in the card-level column settings."
  [column-viz-settings field-ids]
  ;; Retrieve field-level settings
  (let [field-id->settings (reduce
                             (fn [m field-id]
                               (let [field-settings      (:settings (lib.metadata/field (qp.store/metadata-provider) field-id))
                                     norm-field-settings (normalize-field-settings field-id field-settings)]
                                 (assoc m field-id norm-field-settings)))
                             {}
                             field-ids)]
    ;; For each column viz setting, if there is a match on the field settings, merge it in,
    ;; with the column viz settings being the default in the event of conflicts.
    (reduce-kv
      (fn [coll {field-id ::mb.viz/field-id :as k} column-viz-setting]
        (assoc coll k (merge (get field-id->settings field-id {}) column-viz-setting)))
      {}
      column-viz-settings)))
```

The primary difference is rather than merging in new keys as `{::mb.viz/field-id field-id} -> field-settings` this code will merge settings found by field id with any `column-viz-setting` containing that field id as part of its key. The merge prefers `column-viz-settings`.

This should be an improvement over what already exists.

2. Move `column-titles` from `metabase.query-processor.streaming.xlsx` to `metabase.query-processor.streaming.common` and use this common function for CSV and JSON export names.

Note that the lifted `column-titles` has some erroneous logic:

- It relies on column `:name` or `:id` as unique identifiers -- they are not always unique.
- It expects the `col-settings` key format to be exactly `{::mb.viz/field-id id}` or `{::mb.viz/column-name name}` -- Sometimes these keys have additional keys. One change made to this function is normalizing `col-settings` to conform to the expected format by removing extra keys. While this isn't a perfect solution, it conforms with the intent of what already exists and is an improvement in the majority of cases.

The _right_ thing to do is _probably_ to use `metabase.lib.equality/find-matching-column` to match the column and settings keys, _but_ the `col-settings` keys are in a weird format that isn't really conducive to doing this. I'd rather we make an incremental step forward and try doing this in another effort.

This second change should not make anything that wasn't already problematic worse, while making the general case better.

* Updated `update-card-viz-settings` for unique fields case

When `update-card-viz-settings` is called, sometimes fields have ids that aren't part of the `column-viz-settings` map. For cases where they are part of the viz settings map, they are merged in, potentially more than once. For cases where the field ids aren't found in the column viz settings but do have settings, we add these in as new entries.

* Test for JSON keys

* Fixed broken unit test that had the wrong data shape.
2023-12-21 02:07:50 +00:00
Oleg Gromov
7a4ebb5acc Fix handling signals in cleanup (#37022) 2023-12-20 23:33:46 +00:00
shaun
eff2be2a02 Fix warning copy when changing table permissions (#36243) 2023-12-20 23:23:23 +00:00
adam-james
e2e6f1385d Add dev fn to render dashboards with static-viz renderers (#36451)
* Add dev fn to render dashboards with static-viz renderers

Run `(dev.render-png/render-dashboard-to-html 1)` to render the dashboard with id 1 to a handy html file.

This file will render each dashcard in the dashboard 3 ways:
 - as a png, like you would see in Slack or in an email body (if it's a chart)
 - as html/svg, like you'd see in the email body (for tables).. might also be helpful to inspect the svg output from
 the graaljs interpreter
 - 10 row table representing what the .csv attachment for the dashcard would look like

Note: to get this branch working properly, there are a couple lines commented out to pass the linter... it's a work in
progress and will be cleaned up for better use.

Todo:
 - [ ] avoid with-redefs to pass the linter
 - [ ] add a preview endpoint that can be used so that you don't need to run a Clojure repl to get the same result.

* Eliminate with-redefs to allow csv 'render'

* Make a 'preview' ns to power `api/pulse/preview_dashboard/:id`

* Make dev.render-png dashboard preview fns the same as the preview ns

* Dashboard Subscription preview ns now also uses csv attachment code

This change now uses the csv attachment code to include an html table representing what we expect to see from csv exports.

* Add dev fn to render dashboards with static-viz renderers

Run `(dev.render-png/render-dashboard-to-html 1)` to render the dashboard with id 1 to a handy html file.

This file will render each dashcard in the dashboard 3 ways:
 - as a png, like you would see in Slack or in an email body (if it's a chart)
 - as html/svg, like you'd see in the email body (for tables).. might also be helpful to inspect the svg output from
 the graaljs interpreter
 - 10 row table representing what the .csv attachment for the dashcard would look like

Note: to get this branch working properly, there are a couple lines commented out to pass the linter... it's a work in
progress and will be cleaned up for better use.

Todo:
 - [ ] avoid with-redefs to pass the linter
 - [ ] add a preview endpoint that can be used so that you don't need to run a Clojure repl to get the same result.

* Eliminate with-redefs to allow csv 'render'

* Make a 'preview' ns to power `api/pulse/preview_dashboard/:id`

* Make dev.render-png dashboard preview fns the same as the preview ns

* Dashboard Subscription preview ns now also uses csv attachment code

This change now uses the csv attachment code to include an html table representing what we expect to see from csv exports.

* Collect all element styles into a single style tag to use with the server's nonce

This allows the dashboard_preview endpoint to render properly by gathering all of the element styles into a single
style tag, which can then be given the server's nonce value so that CSP doesn't strip the style out.

This is useful for the preview endpoint so that we get an accurate picture of what our tables will look like in
emails, plus it makes the presentation look just a bit more readable.

* dev render_png fns match output used on the endpoint now too.

* Hickory dependency out of dev into regular deps
2023-12-20 14:17:20 -08:00
Jeff Bruemmer
ab5b06736e update release list (#37010) 2023-12-20 16:10:28 -05:00
John Swanson
2191e1fa17 count :model/User, not :core_user (#36985)
I noticed that this was doing a `(t2/count :core_user ...)` instead of
`(t2/count :model/User ...)`. I think the only difference is that our
transforms aren't being run (which is why we needed to pass `:type
"personal"` instead of `:type :personal`).
2023-12-20 08:47:16 -09:00
Nemanja Glumac
bdd567d45f Upgrade Replay Cypress plugin to v1.7.10 (#36993) 2023-12-20 11:40:59 -06:00
Anton Kulyk
658caf5181 Add PopoverBackButton to Metabase UI (#36941)
* Add `PopoverBackButton`

* Use `PopoverBackButton` in `DatePicker`

* Use `PopoverBackButton` in `FilterPicker`
2023-12-20 17:38:15 +00:00
Jeff Bruemmer
12829e15b1 correct permissions (#36986) 2023-12-20 10:23:26 -05:00
John Swanson
7ca324a511 Exclude api key users from endpoints and billing calcuations (#36905)
- To exclude API Key users from the User API endpoints, use the new `type` field on the User model to add conditions to each of the endpoints to ensure that we're only listing, selecting, or modifying "personal" users (as opposed to "internal" or "api-key"). Theoretically this means the `(check-not-internal-user)` calls are no longer necessary, but I'm keeping them around to keep the nicer error messages in that case.

- Only count `:personal` users for the count of users.

- Only include `:personal` users in the analytics stats. We might want to include `:api-key` users separately at some point but for now we can just exclude them to maintain the status quo.
2023-12-20 05:02:32 -09:00
Ryan Laurie
3f5606ee01 Fix "latest" detection for enterprise releases (#36940) 2023-12-20 06:41:08 -07:00
Jeff Bruemmer
57549329ab docs - monitoring links (#36477) 2023-12-20 07:58:55 -05:00
Oisin Coveney
56a2ebd4d1 Remove pain (#36972) 2023-12-20 12:23:39 +00:00
Oisin Coveney
4658e28a0d [Epic #35961] Milestone 2 - Create the Embed Modal (#36170)
Co-authored-by: Mahatthana (Kelvin) Nomsawadi <me@bboykelvin.dev>
2023-12-20 12:17:17 +00:00
Alexander Polyankin
96a26e6db7 Remove MLv1 FilterModal (#36969) 2023-12-20 12:02:39 +00:00
Oisin Coveney
d1cd2593ba Change HTMLAttributes in MenuItem to ButtonHTMLAttributes<HTMLButtonElement> (#36971) 2023-12-20 11:33:20 +00:00
Oisin Coveney
02fa2c9850 [Epic #35961] Milestone 1 - Refactor Public Links and Static Embed Flow (#36048)
Co-authored-by: Mahatthana (Kelvin) Nomsawadi <me@bboykelvin.dev>
2023-12-20 10:21:07 +00:00
Ngoc Khuat
ede142b943 Bigquery sync table require filter (#36677) 2023-12-20 16:40:06 +07:00
Raphael Krut-Landau
9bca2f2f64 Do not cache recently viewed items (#35379) 2023-12-19 20:18:00 -05:00
Braden Shepherdson
e21bde8b5d Adjust Malli enforcement to log/warn by default and throw in dev (#36942) 2023-12-19 22:58:10 +00:00
John Swanson
7d9413330f Auth with API Key (#36593)
In terms of the actual application code, things are pretty straightforward: if an API key is passed, find the
associated user, check the hash against the passed API key, and attach the user if everything went well.

We have existing functions related to the `MB_API_KEY` setting, that I've renamed here. This allows users to set a static API key that can
provide an additional layer of authentication to some routes. I'm keeping the setting name unchanged to avoid issues with backwards incompatibility.
2023-12-19 20:40:09 +00:00
shaun
9c940e1b50 Wait for verification request to complete before fetching updated status (#36904) 2023-12-19 20:36:12 +00:00
shaun
6047a453d9 Stress test EE specs by default, and add mb_edition input (#36952) 2023-12-19 13:59:57 -06:00
Alexander Polyankin
7581b82597 [MLv2] Filter modal integration (#36539) 2023-12-19 19:02:40 +00:00
Noah Moss
1cabfc20a8 Tiny style tweak in audit-db-installation-test (#36928) 2023-12-19 09:21:03 -09:00
Jesse Devaney
efac125132 handle date display when missing date unit (native queries) (#36912) 2023-12-19 12:44:52 -05:00
Anton Kulyk
eeb2aaefd2 Remove "@flaky" tag from fixed E2E test (#36931) 2023-12-19 17:14:48 +00:00
Jason Laster
d650362ff9 Fix Replay before:browser:launch ordering (#36907)
* Fix Replay before:browser:launch ordering

* Wrap method before we use it

---------

Co-authored-by: Nemanja Glumac <31325167+nemanjaglumac@users.noreply.github.com>
2023-12-19 16:51:59 +01:00
John Swanson
959292cf5f Create an API key with POST /api/api-key (#36595)
This creates a new endpoint, `POST /api/api-key` that takes two arguments, a `group_id` and a `name`, and creates an
API key (along with a special API key user).

I also went ahead and threw in the `api-key/count` endpoint here since
it's so small.
2023-12-19 05:50:02 -09:00
Luis Paolini
65183a0c8a Update min mysql version (#36935)
tested which is the min mysql version
2023-12-19 09:16:47 -05:00
Ryan Laurie
66726f91c1 Prevent milestone from closing before release notes are generated (#36924) 2023-12-19 06:06:30 -07:00
Anton Kulyk
6372e20dd0 Fix actions-on-dashboards flakes (#36855)
* Attempt to fix flakes

* Fix test names
2023-12-19 11:22:36 +00:00
Raphael Krut-Landau
1501a98235 Disallow invalid values for the 'humanization strategy' setting (#35469) (#36782)
* Disallow invalid values for the 'humanization strategy' setting (#35469)
* No longer regard :advanced as valid input to human-readable-name

Co-authored-by: dan sutton <dan@dpsutton.com>
2023-12-18 18:08:10 -05:00
bryan
5e15b9c7b3 Update hardcoded plugins to use MB_PLUGINS_DIR (#36860) 2023-12-18 15:45:04 -05:00
Nemanja Glumac
4e6ea4b45f Fix model metadata remapped field overflow (#36792)
SelectButton's container had a `flex-full` CSS class, which we set to `flex: 1 0 auto`.
`flex-basis` (the last value) is set to auto and that is causing the overflow.

Ideally, we need to set the flex-basis to `fit-content` but we don't have such a class.
I can create one, if needed.

In meantime, forcing the `flex-basis` to `0` through the class `flex-basis-none` will
have the same effect.

Fixes #36163
2023-12-18 21:18:15 +01:00
Oleg Gromov
17623ec815 HK: Change unused vars naming rule (#36909) 2023-12-18 19:10:10 +00:00
Jeff Bruemmer
9277e27afc update release-list (#36903) 2023-12-18 12:24:57 -05:00
Anton Kulyk
4a4c518914 Fix dashboard filter panel spacing and border (#36814)
* Clean up sticky filters container code

* Hide parameters container border until scrolling

* Add margin between grid and parameter list bottom border

* Always keep the vertical margin for cards container

* Fix filters panel had different top/bottom padding
2023-12-18 15:52:02 +00:00
Cam Saul
ed7295b5d6 Remove lots of dead MLv1 code (#36873) 2023-12-18 17:31:20 +02:00
shaun
13f12d9751 allow cypress specs to be written in TypeScript (#36813) 2023-12-18 09:30:38 -06:00
Mahatthana (Kelvin) Nomsawadi
0b0098117b Trim space and normalize empty string in admin settings (#36693)
* Trim space and normalize empty string in admin settings

* Attempt to use `SettingInput`

* Fix the input doesn't change value to the normalized value

This happened when the normalized value is the same value before we call
`onChange`

* Remove unnecessary type check + prevent rerendering
2023-12-18 13:10:34 +00:00
Cam Saul
e21e425b01 Add field values search info (#36839) 2023-12-15 18:40:49 -08:00
Jerry Huang
cb322642a9 Fix embed error message to make sense for cards (#36765)
* fix embed error message

* add card test

* update code
2023-12-15 17:49:09 -08:00
Noah Moss
e0eb104c2a Routine dependency bumps (#36870) 2023-12-16 00:51:44 +00:00
adam-james
85d3120526 Migrate PulseCards include_csv = true when the card has :display table (#36383)
* Migrate PulseCards include_csv = true when the card has :display table

Why? This is so that we can eliminate the behaviour of csv attachments being included in emails even when a user
doesn't have them seleted in the dashboard subscription pane. This is confusing behaviour and undesirable in many
cases.

The likely better behaviour is that attachments for any card are only included if explicitly asked for by a user. But,
in order to change the app to behave this way, we should first migrate things so that any user who relies on this old
behavior will still see the attachments they have come to expect.

This PR is still draft and some things must happen still:

 - [ ] the migration is incomplete! At the moment, this will include .csv attachments even for tables with n-rows <
 10. This migration would cause users to see more .csv attachments than before. So, the migration should only set
 include_csv = true when the row count of the results is greater than 10.
 - [ ] the migration # is NOT claimed in the slack channel yet. This should be claimed as soon as the migration
 approach is reviewed to work and an appropriate issue for this change is linked.

* Use the proper migration # which is now claimed appropriately

* Change SQL to work with H2

* Attachment message logic depends on include_csv/xls values now

Also lift the attachment message inclusion up a level so that it can be applied to all card types, not just tables.

* Fix a failing test

* Change copy for when attachments are included

Also change a test to explicitly include csv (since now that's the only way csvs will be attached).

* Fix test
2023-12-15 14:47:28 -08:00
Oleg Gromov
d45bae641c Add e2e front-end healthcheck to cypress (#36872) 2023-12-15 21:01:40 +00:00
Mark Bastian
2dc9567479 Apply formatters to JSON streaming results (#36863)
* Apply formatters to JSON streaming results

As is done in `metabase.query-processor.streaming.csv`, we now use column formatting in `metabase.query-processor.streaming.json`. This was done by creating a formatter for each column in the `:json` implementation of `qp.si/streaming-results-writer` (in the `begin!` function). These formatters were then applied on each row write.

One important design decision that had to be made here was the handling of JSON numeric types. In Metabase, we do several default formats of numbers and allow custom formatting that would alter the basic presentation of a json number. Examples:
- Integers default to showing a comma separator for large numbers
- Decimals round to 2 significant digits
- Percent, scientific, and currency formats may be applied

The only time a raw JSON number will look identical to what is shown in metabase is if formatting is removed for integers and just the right amount of digits are shown for floats.

Since the goal of exports is to preserve the data as shown in Metabase, the ony way to guarantee this outside of a few corner cases is to export all values as strings. Attempting to parse ints and floats after formatting may also cause unexpected behavior, as `3.14159` may be shown as `3.14` in Metabase and exported as this truncated number (if we parsed it). A user most likely would want to see exactly what they see in Metabase (so default to strings) or the original, unmodified value).

This PR also updates the CSV export code to use a `volatile!` rather than an `atom` for consistency.

* Fixing `json-download-test` to reflect string values.

* Fixing `test-query-results` to reflect stringified json values.

* Fixing `execute-public-card-test` to reflect stringified json values.
2023-12-15 12:57:04 -07:00
Braden Shepherdson
da55306747 [MLv2] Be more forgiving in the schemas for := filter clauses (#36865)
This is probably not the full story; we should look into overhauling
how we validate plausible comparisons.

Fixes #36841.
2023-12-15 19:03:20 +00:00
Alexander Polyankin
c769b1c5e7 Fix MLv1 filter validation (#36810) 2023-12-15 20:18:41 +02:00
bryan
7c399c4581 Remove redundant is call from test.check defspec (#36777) 2023-12-15 10:46:25 -06:00
Jeff Bruemmer
7a121fd9e7 docs - update minimum version for mysql (#36853)
* update minimum version for mysql

* format
2023-12-15 12:55:20 -03:00
Jeff Bruemmer
8062975ca6 format (#36838) 2023-12-15 10:08:53 -05:00
Oleg Gromov
e46a64f957 Fix dashcard-filter connection edge cases (#36760)
* Issue FETCH_DASHBOARD_DATA on Dashboard save
* Clean up repetitions in the parameters e2e test
* Add e2e tests
2023-12-15 14:09:43 +00:00
Oleg Gromov
483c638238 Add e2e/spyRequestFinished (#36818) 2023-12-15 12:34:35 +00:00
Jeff Bruemmer
56141a6ec4 docs - date formats for CSV uploads (#36815) 2023-12-15 07:32:02 -05:00
Mahatthana (Kelvin) Nomsawadi
9a38587f64 Fix embedding flaky test (#36791)
Co-authored-by: Oisin Coveney <oisin@metabase.com>
2023-12-15 09:32:59 +00:00
metamben
51e7f99d44 Add sourceTableOrCardId (#36778) 2023-12-14 23:10:21 +00:00
Ryan Laurie
35a17d84ee Publish Releases Granularly (#36816) 2023-12-14 14:42:36 -07:00
Ryan Laurie
51be6a14cc Update Translations for Metabase v48 (#36812) 2023-12-14 14:36:40 -07:00
Jesse Devaney
c877264892 fix broken helper (#36823) 2023-12-14 15:37:44 -05:00
Raphael Krut-Landau
5602abd2b9 Add rafpaf to team (#36807) 2023-12-14 12:42:56 -05:00
Jesse Devaney
493beea6c6 Fix Flaky Subscriptions E2E Test (sharing/subscriptions.cy.spec.js) (#36768)
* fix flaky subscriptions E2E test

* remove flaky tag
2023-12-14 12:31:51 -05:00
Mark Bastian
3e694d9592 Fixing :time-enabled is nil time formatting (#36803)
For date time and time strings, when the viz settings contains the `:time-enabled` key with a `nil` value this means we should not show the time portion of the item.

This means for date times, we just show the date and for times we don't show anything.
2023-12-14 10:15:16 -07:00
Jerry Huang
34b921c152 Audit Log should also allow statistics for Public/Embedding - including downloads (#36646)
* Audit Log should also allow statistics for Public/Embedding - including downloads

* add tests, product input

* fix linter

* update test

* fix spacing

* address comments

* fix test

* fix whitespace
2023-12-14 10:07:41 -06:00
John Swanson
e8f3a45300 Rename max-*-query-row-limit to *-query-row-limit (#36753)
@jeff-bruemmer pointed out that these names are redundant in #36723.

Theoretically one could argue that the settings aren't actually setting the "query row limit" - when you make a new
question, you can enter whatever limit you like. Instead, they're setting the *maximum* possible "query row limit."

That said, applying two limits is the same as applying the minimum of two limits, so calling it a "query row limit"
makes sense too, and might be more clear.
2023-12-14 07:12:34 -08:00
Anton Kulyk
d478a7854c Add "Replace question" action to dashboard cards (#36744) 2023-12-14 14:34:36 +00:00
Lena
d18cac4417 Remove levex from team.json (#36783) 2023-12-14 13:25:19 +01:00
Cal Herries
f06b24a555 CSV uploads: Use DATETIME instead of TIMESTAMP for datetime columns with MySQL (#36790) 2023-12-14 12:22:34 +00:00
Ngoc Khuat
4908696acb Sync index info: mongo (#36624) 2023-12-14 11:51:28 +00:00
Cal Herries
b031c91e2b Comment flaky test in metabase.metabot.metabot-util-test/inner-query-name-collisions-with-joins-test (#36786) 2023-12-14 10:13:50 +00:00
Ryan Kienstra
26bbec6367 Move sample-dataset into test-data for backend tests (#35973)
* Move sample-dataset.edn into test-data.edn

Replace (mt/dataset sample-dataset with (mt/dataset test-data

Replace more references to sample-dataset with test-data

Fix the format of the combined data

Might revert: remove test that doesn't apply, now that there's 1 DB

Make api.database-test pass, though expected could be wrong

* Update unit tests for combined dataset

* Bump Bigquery version from v3_ to v4_

* Bump v3_test-data to v4_test-data

* Remove wrapping with mt/dataset

Alphabetize fk-mappings

* Remove needless whitespace edits

* Fix failed e2e_test by removing reference to sample-dataset

* Fix tests for Mongo, Oracle, Snowflake, and Presto

* Fix unit tests again for Mongo, Presto, and Snowflake

* Will revert: run driver tests on my fork

* Will revert: run driver tests on my draft fork

* Revert "Will revert: run driver tests on my draft fork"

This reverts commit 078c8af1de.

* Revert "Will revert: run driver tests on my fork"

This reverts commit e3e2922f98.

* Make the postgres driver test pass again by reverting a change

* Apply Case Nelson's patch to fix Athena test

https://github.com/metabase/metabase/pull/36064#issuecomment-1824837705
Props @snoe

* Remove (mt/dataset sample-dataset) from new tests

* Maybe fix Athena driver tests

Revert needless deletions of (mt/dataset test-data
Maybe those deletions caused the
failing Athena driver tests.
But those deletions are out of scope
for this PR either way.

* Remove sample-dataset reference from a test in the master merge

* In card_test.clj, replace sample-dataset with test-data

* Merge in master, resolve conflict in pivot-from-model-test

* Merge in master, resolve conflict in pivot-from-model-test

* Must revert: allow databse creation

To see if it will fix:
https://github.com/metabase/metabase/actions/runs/7120808552/job/19388845720?pr=36064#step:3:441
Athena database creation is disabled: not creating database v2_test_data. Tests will likely fail.

* Revert "Must revert: allow databse creation"

This reverts commit d4c8f12946.

* Add back in (mt/dataset where I deleted it

But replace sample-dataset with test-data.
This might be wrong, or maybe it's not needed in
so many places.
But it could show if this is the problem.

* Fix the failed sync test

---------

Co-authored-by: Case Nelson <case@metabase.com>
2023-12-14 06:17:43 +01:00
bryan
7a681dbf39 add skip-graph query param to PUT api/permissions/graph (#36724)
* Adds skip-graph qp to ellide graph for PUT + test

* Adds test for data perms graph skip-graph param

improve and cleanup errors on PUT data perms graph

* cleanup test

* include revision-num and groups in new graph api

* rename test helper

* fix alignment

* improve tests by checking for rev. numbers

* check groups in the response
2023-12-13 16:38:17 -06:00
Mark Bastian
f618fcbbce Consistent time formatting for metabase.formatter.datetime (#36726)
* Consistent time formatting for `metabase.formatter.datetime`

This PR makes changes to `metabase.formatter.datetime` so that the output of these functions is as close to what is presented in the Metabase UI as possible. Note that since the codes are currently not on the same rendering path, this may not be 100% possible, but it looks to be correct ATM.

Changes include:
- Refactoring `metabase.formatter.datetime/format-temporal-str` into two clear stages:
  - Merge the viz settings
  - Format the string
- Rather than being a case statement nested in an if, formtting is now a multimethod based on the unit type of the column or the column type, in that order. This seems a lot cleaner and allows for specialization on our type system as desired.
- Dispatches for `:type/Time`, `:type/Date`, and `:type/DateTime` now handle the different formatting options available on the FE for each type.
- Tests are added to the `metabase.formatter.datetime` and `metabase.pulse.pulse-integration-test` nses.

A few important discoveries made in the course of this PR are:

- We have to exercise care in the use of a/A in time formatting strings because of our FE library (Moment.js) uses `a` to mean `am/pm` and `A` to mean `AM/PM`. Meanwhile, Java [DateTimeFormatter](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html) uses `a` for AM/PM and `A` for millseconds of day. So, if `A` in a pattern like `HH:mm A` makes it to a formatter on the BE it is almost certainly a logic error.
- At some point we should collaborate with the metabase lib team to see if we can unify all of this logic. Whatever path we choose must take into account the time zone, column metadata, and viz settings when producing a consistent formatter.
- To get around this, the `metabase.formatter.datetime` ns had a pattern like `(str/replace (or time-style default-time-style) #"A" "a")` to replace `A` with `a`. This was an undocumented feature that might leave you wondering, but is now part of a documented function. Note that this replacement means you really can't use millis of day in most of our code paths, but IDK that you'd ever want this formatting as we generally use it anyways.
- `metabase.shared.util.internal.time/format-unit` has similar, but not identical, logic to the unit-based rendering in `metabase.formatter.datetime` that we might want to consolidate.

* Updates for custom column settings

This PR merges in column settings from the result column as would be provided via user metadata. This setting takes precedence over all others.

* Updating tests to reflect new formatting capabilities which reflect the UI defaults.

* Adding comments

* Fixing e2e test

* e2e fixes

* Updating tests to reflect consistent CSV formatting.
2023-12-13 15:30:52 -07:00
John Swanson
25089c878d Api key migrations (#36316)
* Part 1: Add `core_user.type`

With the addition of API keys and "api key users", we want to add a `type` field to users to easily distinguish
between "regular" users and API key users.

The one non-standard user we have right now is the "internal" Metabase user. We don't actually need this field for
that one (because we fix that user's ID to `13371338`), but we might as well set the `type` correctly anyway.

* Part 2: API Key table

Create an API Key table to contain, uh, API keys.

The table has the following fields:

- id

- user_id (the associated API key user, who this API key "acts as")

- key (the hash of the API key itself)

- key_prefix (the first 7 digits of the *raw* API key, beginning with `mb_XXXX`)

- created_by (the user that created the API key)

- created_at

- updated_at

* Part 3: Set the type of the internal user

The internal user is actually identified by the ID, but we might as well set the type correctly.


Finally: don't condition view recompilation on is-prod? since Cypress actually runs the backend in prod mode

---------

Co-authored-by: Noah Moss <noahbmoss@gmail.com>
2023-12-13 13:34:02 -08:00
Nick Fitzpatrick
2401726b3f UserCollectionList usePagination (#36767) 2023-12-13 17:25:27 -04:00
Case Nelson
a33f8133cc Bump dependencies based on vulnerabilities (#36504)
* Bump dependencies based on vulnerabilities

* More deps bumped

* Bump more deps

* Rollback H2 dependency bump

* Add comments and make guava match elsewhere.
2023-12-13 13:34:59 -07:00
Jeff Bruemmer
3ec2c7da41 docs - csv upload id name (#36600) 2023-12-13 14:53:43 -05:00
Ryan Laurie
b7d6dc77b7 Evaluate Cypress Cloud (#34866) 2023-12-13 12:00:07 -07:00
Ryan Laurie
e5f54264bc Fix sandbox e2e test flake (#36725) 2023-12-13 11:27:42 -07:00
Mark Bastian
b4408e033f Updating honeysql alias in dev ns (#36758)
* Updating honeysql alias in dev ns

This just fixes a broken require to align with the work in #36670.

Fixes #36757
2023-12-13 16:31:40 +00:00
metamben
c3a926ab10 Support segment and metric metadata -> legacy reference conversion (#36718)
Co-authored-by: Uladzimir Havenchyk <125459446+uladzimirdev@users.noreply.github.com>
Co-authored-by: Uladzimir Havenchyk <uladzimir.dev@gmail.com>
2023-12-13 19:19:06 +03:00
Ryan Laurie
4218535ac4 Remove flake tag and follow lint rule in recents e2e test (#36727) 2023-12-13 15:53:10 +00:00
Cam Saul
92124df05f Expose version of query that takes Card or Table metadata (#36713) 2023-12-13 07:34:45 -08:00
Uladzimir Havenchyk
54fe0d3cfa Cleanup legacyQuery from ExpressionWidget (#36735) 2023-12-13 15:18:15 +00:00
Anton Kulyk
9b4f53905f Fix onLeftEdge prop getting into a plain DOM element (#36751)
* Fix leaking `DashCardActionsPanelContainer` props

* Remove unused `DashboardCardActionsPanel` component

* Fix type name

* Update `@container` selector
2023-12-13 14:56:12 +00:00
Anton Kulyk
6fd01a19f9 Handle metabase/ui/Modal in e2e modal helper (#36743)
* Handle new `Modal` in e2e `modal` helper

* Fix `modal` e2e helper

* Fix tests
2023-12-13 14:34:37 +00:00
Uladzimir Havenchyk
dc0fcede6c Migrate ExpressionWidget and ExpressionEditorTextfield to MLv2 (#36344)
Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>
2023-12-13 17:12:18 +03:00
Kamil Mielnik
83ebbf3b43 Remove dead BreakoutPopover & AggregationPopover usages from View (#36745)
* Remove dead AggregationPopover usage from View

* Remove dead BreakoutPopover usage from View

* Remove onAddSeries/onEditSeries/onRemoveSeries props from LegendHeader

* Remove unused onAddSeries & onEditSeries props from visualizations

* Remove dead code from LegendHeader
2023-12-13 13:45:47 +00:00
Anton Kulyk
1617c5082c Fix nested a tags dashboard card action panel (#36747)
* Add `as` prop to `DashActionButton`

* Avoid nested `a` tags
2023-12-13 13:29:43 +00:00
Mahatthana (Kelvin) Nomsawadi
9552ea570c Fix dashboard result download not working on static embed (#36739)
* Fix dashboard result download not working on static embed

* Add an E2E test

* Revert accidental export removal that caused unit tests to fail

* Match the logic when comparing null with the previous version

* Fix the logic
2023-12-13 13:29:25 +00:00
Kamil Mielnik
fa997583ac Convert ExpressionStep to MLv2 (#36455) 2023-12-13 11:59:48 +00:00
metamben
d3bb48844a Port #36507 to master (#36533) 2023-12-13 12:37:34 +02:00
Anton Kulyk
fea5d8cb4d 🚧 Fix createMockCard returns a query without a source table (#36715)
* Use sample products table ID in `createMockStructuredQuery`

* Simplify things

* Fix failing tests
2023-12-13 10:21:56 +00:00
Nicolò Pretto
4e823852e1 test(whats-new-notification): add test case for white labeling scenario (#36694)
* test(whats-new-notification): add test case for white labeling scenario

* refactor: address PR feedback

* fix test that was failing
2023-12-13 11:04:30 +01:00
Cam Saul
2575d0f9e5 Finish removing Honey SQL 1 (#36670) 2023-12-13 10:00:48 +00:00
Cal Herries
bb467d09b8 Use driver/database-supports? instead of supports-schema? (#36571) 2023-12-13 10:33:21 +02:00
Ngoc Khuat
185436ea21 Migration to remove the legacy pulses (#35841) 2023-12-13 04:27:50 +00:00
Jeff Bruemmer
083f3bb82a docs - max retention (#36418) 2023-12-12 16:26:31 -05:00
Noah Moss
130a8ec412 Fixes for audit DB permission checks & defaults (#36697)
Co-authored-by: bryan <bryan.maass@gmail.com>
2023-12-12 20:21:27 +00:00
Jeff Bruemmer
3d1962b6e9 docs - linked filters limit (#36603) 2023-12-12 13:50:57 -05:00
lbrdnk
41692f441e Revert all server side generated timestamps commits (#36702)
Those are:
- 8eb45851c4
- 930bbc5a5a
- 16988f50d6

Reason is that I'm not yet able to explain UTC night CI failures. That is WIP.
More context can be found on slack in https://metaboat.slack.com/archives/C5XHN8GLW/p1702332392764369?thread_ts=1701772468.810829&cid=C5XHN8GLW
2023-12-12 19:07:10 +01:00
Cal Herries
8404e44ec3 Fix uploading CSV columns with boolean and integer values (#36641) 2023-12-12 19:49:33 +02:00
Jeff Bruemmer
d8eac1a9b4 add percentage to list of field types (#36599) 2023-12-12 11:58:35 -05:00
Jeff Bruemmer
c8622f46e5 add Finnish to list of languages (#36645) 2023-12-12 11:58:22 -05:00
Ryan Laurie
edb8cfa0a3 Prevent release artifacts colliding with test artifacts (#36663) 2023-12-12 09:40:50 -07:00
Nemanja Glumac
511618088f Retry failed Cypress tests only once (#36704) 2023-12-12 17:36:30 +01:00
Nemanja Glumac
a5c7d1d93d Rerun workflows only once on important branches (#36703) 2023-12-12 17:36:09 +01:00
Braden Shepherdson
a702935d0e [MLv2] Reorder column filter and distribution drills (#36700)
Column filter is supposed to come first in the list.

Fixes #36674.
2023-12-12 19:23:35 +03:00
Alexander Polyankin
98bcd7fc31 Remove dead FE code after migrating drills (#36673) 2023-12-12 15:03:49 +00:00
Nemanja Glumac
8bf73a6d6e Cypress TypeScript PoC (#36474)
* Add a simple Cypress TS helper example

* Convert simple custom Cypress commands to Ts

* Convert a bit more complex set of helpers to Ts

* Make selectors more resilient

This solves linter errors.

* Fix tests

* Type response as unknown

* Reuse FE types

* Improve JSDoc comments

* Use generic string type for aggregation metrics

* Use camelCase

* Use `CyHttpMessages.IncomingResponse` to type a response
2023-12-12 15:08:17 +01:00
Oleg Gromov
e7165b0f6c HK in API client: move reversal of exponential delay list where it be… (#36695)
HK in API client:
* move reversal of exponential delay list where it belongs
* simplify the array creation
2023-12-12 13:02:34 +00:00
Mahatthana (Kelvin) Nomsawadi
e09323b6d6 Fix whitelabeled application name replaces Metabase in admin settings (#36032)
* Make it explicit when we want to replace the app name for whitelabeling

* Remove the ttag hack so we can verify this solution works

* Review: Remove unnecessary translation on the app name

* Delete unused files

* WIP replacing application names

* Fix more places

* Replace application names in more places

* Replace the rest of the application name

* Remove debug comment: admins

* Remove debug comments: setup flow

* Remove debug comments: misc

* Remove debug comments: screenshots

* Fix failed unit tests

Because we're changing some components to get the application name from
redux store, we need to update certain tests that still use `render` to
`renderWithProvider` instead.
2023-12-12 10:50:25 +00:00
Alexander Polyankin
4577e730f0 [MLv2] Drills FE integration branch (#35952) 2023-12-12 10:01:52 +00:00
Cam Saul
fdff94e65c Generate sane queries for native query models with renamed columns (#36616) 2023-12-11 20:51:39 -08:00
Ngoc Khuat
743f724833 Task to send emails warn user about pulse removal (#36392) 2023-12-12 03:09:06 +00:00
metamben
6a81db7e4b Make replace-clause use custom expression name if set (#36650) 2023-12-12 02:26:29 +03:00
bryan
19401c1bd9 adding perm-graph filtering on db or group id (#36543)
* a more refined first crack at adding perm-graph access for db or group id

* new routes: filter data-perm-graph on db or group

add tests

* remove inline defs

* code review responses

* fix typo

* fix the other tests

* update the tests to use the right malli schema

* reuse private vars in tests

* pull graph checker into test util ns and apply it
2023-12-11 23:19:11 +00:00
Cam Saul
c0de0ba37f Underlying records drills: preserve the temporal bucket on a breakout column in the previous stage (#36613) 2023-12-11 21:04:53 +00:00
Braden Shepherdson
5e873d1350 [MLv2] fk-filter drills should not appear on native queries (#36660)
They were added incorrectly in fixing #35689.

Fixes #36633.
2023-12-11 21:02:12 +00:00
Ryan Laurie
a4192548b4 Metabase analytics everywhere (#36605) 2023-12-11 13:09:25 -07:00
Luiz Arakaki
06e50685dc fix some questions with problems re: models (#36653) 2023-12-11 19:06:46 +00:00
Jeff Bruemmer
886c5e44e1 basic action limitations (#36652) 2023-12-11 13:25:11 -05:00
metamben
bee2403fb6 Support changing the expression when the type and the name don't change (#36558) 2023-12-11 20:58:38 +03:00
Ngoc Khuat
a9d2006745 Sync index info (#36462) 2023-12-11 15:21:50 +00:00
Alexander Solovyov
2ad1103e35 fix sending backport error message (#36635) 2023-12-11 13:53:41 +00:00
Ryan Laurie
f492fbc619 Add Finnish language support (#36607) 2023-12-11 13:42:19 +00:00
Ryan Laurie
faf72609cc Handle latest release check correctly for s3 (#36551) 2023-12-11 06:08:19 -07:00
Kamil Mielnik
bb8e115d2e Add junit.xml to .gitignore (#36627)
- see https://github.com/metabase/metabase/pull/35929
2023-12-11 12:48:15 +00:00
Alexander Solovyov
0d5bf036b3 understandable error when export target directory is not writable (#36535) 2023-12-11 12:31:13 +00:00
Cam Saul
6d8cefdc8a Fix underlying-records drill with nil binned value (#36611) 2023-12-10 00:46:04 +03:00
Anton Kulyk
53a1cff555 Extract dashboard QuestionPicker from AddCardSidebar (#36589) 2023-12-09 11:23:00 +00:00
Cam Saul
54bddc1ad7 Use sorted-set for locales.clj so order doesn't change every time we add a new language (#36617) 2023-12-09 01:23:53 +00:00
Cam Saul
62939c1ac0 Copy drills dox from #36253 (#36511)
Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>
2023-12-08 15:34:12 -08:00
metamben
f156e0cdd2 Pretty print #>> and != as operators when possible (#36606) 2023-12-09 01:54:38 +03:00
Luiz Arakaki
9208fb6019 fix some questions with problems re: models (#36597) 2023-12-08 20:51:36 +00:00
John Swanson
fa4339bc43 Workaround for an H2 bug (#36578)
There's a fun bug in H2: https://github.com/h2database/h2database/issues/3942

To reproduce:

- create a table, then
- create a view based on the table, then
- modify the original table, then
- generate a snapshot

The generated snapshot has the `CREATE VIEW` *before* the `CREATE TABLE`. This results in a view that can't be queried
successfully until it is recompiled. Our workaround is to recompile ALL views immediately after we restore the app DB
from a snapshot.
2023-12-08 11:25:55 -08:00
Luis Paolini
b06d0a043b Add title to funnel chart that became a bar chart (#36523)
* Add title to funnel chart that became a bar chart

Simple fix for https://github.com/metabase/metabase/issues/36227

* Fix whitespaces

* Add prettier on the file

* add specs

---------

Co-authored-by: Aleksandr Lesnenko <alxnddr@gmail.com>
2023-12-08 16:19:41 -03:00
lbrdnk
8eb45851c4 Unskip one and skip another relative datetime test (#36580)
* Revert "Temporarily skip server-side-relative-datetime-honeysql-form (#36567)"

This reverts commit 769b5eb439.
This was not flaking.

* Skip test that flakes
2023-12-08 19:38:56 +01:00
Aleksandr Lesnenko
a7bb596967 convert user reducer to RTK (#36353) 2023-12-08 15:35:59 -03:00
Braden Shepherdson
1f2447e01d [MLv2] Fix warning in CLJS build (#36541)
This was introduced by #36443.
2023-12-08 17:11:45 +00:00
Ryan Laurie
860af72f2f Upload test results to S3 (#35929) 2023-12-08 16:10:15 +00:00
Braden Shepherdson
663756e1c8 [MLv2] Only mark selected columns for aggregations with columns (#36572)
If the aggregation is based on `:case` or another non-column
value, errors were being thrown trying to generate refs.
2023-12-08 16:01:18 +00:00
shaun
177a6b345a Migrate SettingsLdapForm to formik (#36054) 2023-12-08 15:57:26 +00:00
Jeff Bruemmer
86bd5e3f96 docs - pulse removal (#36415) 2023-12-08 08:56:31 -05:00
Ngoc Khuat
355c35ed20 Sync remove log translation (#36565) 2023-12-08 10:04:18 +00:00
Braden Shepherdson
0b231c5721 [MLv2] Fix pivot drills integration with the FE (#36509)
These were broken because `lib.js/pivot-types` was returning CLJS
keywords rather than strings.

Also makes applying drill-thrus less noisy (`log/info` -> `log/debug`).

Unskips the FE integration tests for pivot drills. Fixes #33559.
2023-12-08 08:56:50 +00:00
Ngoc Khuat
769b5eb439 Temporarily skip server-side-relative-datetime-honeysql-form (#36567) 2023-12-08 08:53:06 +00:00
Cal Herries
f0100e1783 Fix BE flake: metabase-enterprise.advanced-permissions.common-test/upload-csv-test (#36475) 2023-12-08 10:02:10 +02:00
Mark Bastian
58f22594ae Refactoring formatting code for common utility (#36490)
* Apply column formatting to CSV exports

This PR applies the same formatting logic to CSV exports as it does to pulse bodies (e.g. HTML).

Formerly, there were two related formatting paths:
- `metabase.query-processor.streaming.common/format-value`, which is from a protocol that takes an object and returns a string. It is what was used to export csv data. It applies no actual formatting, only converts objects to strings.
- `metabase.pulse.render.body/get-format`, which builds a formatter from an optional time zone, column metadata, and visualization settings. This formatter takes a string and formats it. It was only used for rendering inline artifacts, such as embedded HTML in emails.

The first function is insufficient to format row data as it is unaware of the column metadata and viz settings. We need to use that data everywhere data is exported in a uniform way.

The solution is to lift `get-format` from `metabase.pulse.render.body` to a more common location (`metabase.pulse.render.common` in this PR step, but needs to be moved out of the pulse code to be a more shared concern) and use it everywhere artifacts are generated.

For csv export, this was achieved as follows in `metabase.query-processor.streaming.csv`:

```clojure
(defmethod qp.si/streaming-results-writer :csv
  [_ ^OutputStream os]
  (let [writer     (BufferedWriter. (OutputStreamWriter. os StandardCharsets/UTF_8))
        formatters (atom {})]
    (reify qp.si/StreamingResultsWriter
      (begin! [_ {{:keys [ordered-cols results_timezone]} :data} viz-settings]
        (swap! formatters (constantly (zipmap
                                        ordered-cols
                                        (map (fn [col]
                                               (p.common/get-format results_timezone col viz-settings))
                                             ordered-cols))))
        (csv/write-csv writer [(map (some-fn :display_name :name) ordered-cols)])
        (.flush writer))

      (write-row! [_ row _row-num cols {:keys [output-order]}]
        (let [[ordered-row
               ordered-cols] (if output-order
                               (let [row-v  (into [] row)
                                     cols-v (into [] cols)]
                                 [(for [i output-order] (row-v i))
                                  (for [i output-order] (cols-v i))])
                               [row cols])]
          (csv/write-csv writer [(map (fn [c r]
                                        (let [formatter (@formatters c)]
                                          (formatter (common/format-value r))))
                                      ordered-cols ordered-row)])
          (.flush writer)))

      (finish! [_ _]
        ;; TODO -- not sure we need to flush both
        (.flush writer)
        (.flush os)
        (.close writer)))))
```

The formatters for each column are build in the `begin!` function and then looked up in each `write-row!`.  The existing `format-value` is used to produce a string then passed into our looked up column formatter.

Note that the new unit tests simulate a pulse and grab the provided temp files as attachments and analyzes those for correctness. This should work in a CI environment so long as the test process has permission to both write attachments to the temp directory and read those attachments back out. Also note that these tests can be slow (but not terribly so).

Primary changes:
- `metabase.email.messages` - fix spelling
- `metabase.pulse.render.body` - move `get-format` out of this ns
- `metabase.pulse.render.common` - move `get-format` into this ns
- `metabase.query-processor.streaming.csv` - new logic to apply pulse renderer formatting to csv exports
- `metabase.pulse.pulse-integration-test` - adding unit tests

One TODO before a final commit of this PR is to move the `get-format` logic out of a pulse ns into something more general. Ultimately, it would be nice if this was a common capability used by both BE and FE.

* Refactoring formatting code for common utility

This PR refactors `metabase.pulse.render.common` to `metabase.formatter` as this is code we want applied to several locations, not just in pulses. It also updates references to these nses and the consistent alias.

A key observation of this formatting code, and reason for the refactor, is that it is "metabase-aware" in that it takes into account metadata columns and visualization settings when building formatters rather than just being a simple generic date or number formatter. This is a common code path that should be used any time we are rendering static assets and could potentially be used as common FE code with future development.

Moves:
- `metabase.pulse.render.common` to `metabase.formatter`
- `metabase.pulse.render.datetime` to `metabase.formatter.datetime`
- `metabase.pulse.render.common-test` to `metabase.formatter-test`
- `metabase.pulse.render.datetime-test` to `metabase.formatter.datetime-test`

* Ordering consistent aliases in kondo config

* Rebase fix to use formatter ns in streaming.csv

* Adding `metabase.formatter` require.

* Updating require alias on new test.
2023-12-07 13:36:27 -08:00
lbrdnk
930bbc5a5a Update server side relative datetime generation honeysql (#36528)
* Use date instead of timestamp

* Update logging and add code for local testing

* Rename datetime to date
2023-12-07 21:15:08 +01:00
Ryan Laurie
f5d6697a21 Use stretch variant on switch (#36503) 2023-12-07 12:47:21 -07:00
Anton Kulyk
bbdbf09b90 Add icon search to Storybook (#36547) 2023-12-07 14:44:54 -05:00
Anton Kulyk
b3e6f9c641 Add "refresh_downstream" icon (#36546) 2023-12-07 19:37:04 +00:00
Uladzimir Havenchyk
bb6febc8e1 Upgrade @testing-library/jest-dom to address security issue with its dependency (#36518) 2023-12-07 21:57:43 +03:00
Anton Kulyk
9120c17cc9 Revert "Fix card filter connected to a field not causing an update" (#36534)
This reverts commit 2af32bbc73.
2023-12-07 18:33:12 +00:00
shaun
83bf74cf7c Fix settings jwt (#36189)
* fix types
* swap unit test step order
2023-12-07 18:06:42 +00:00
Nicolò Pretto
f79a58ed75 [Help link] feature branch (#36172)
feat:: white labeling option for help link
2023-12-07 17:57:43 +00:00
Case Nelson
3281075fdd [MLv2] drop-stage-if-empty (#36500)
* [MLv2] drop-stage-if-empty

* Addressing PR comments
2023-12-07 10:52:27 -07:00
Mark Bastian
356c4986a7 Apply column formatting to CSV exports (#36484)
* Apply column formatting to CSV exports

This PR applies the same formatting logic to CSV exports as it does to pulse bodies (e.g. HTML).

Formerly, there were two related formatting paths:
- `metabase.query-processor.streaming.common/format-value`, which is from a protocol that takes an object and returns a string. It is what was used to export csv data. It applies no actual formatting, only converts objects to strings.
- `metabase.pulse.render.body/get-format`, which builds a formatter from an optional time zone, column metadata, and visualization settings. This formatter takes a string and formats it. It was only used for rendering inline artifacts, such as embedded HTML in emails.

The first function is insufficient to format row data as it is unaware of the column metadata and viz settings. We need to use that data everywhere data is exported in a uniform way.

The solution is to lift `get-format` from `metabase.pulse.render.body` to a more common location (`metabase.pulse.render.common` in this PR step, but needs to be moved out of the pulse code to be a more shared concern) and use it everywhere artifacts are generated.

For csv export, this was achieved as follows in `metabase.query-processor.streaming.csv`:

```clojure
(defmethod qp.si/streaming-results-writer :csv
  [_ ^OutputStream os]
  (let [writer     (BufferedWriter. (OutputStreamWriter. os StandardCharsets/UTF_8))
        formatters (atom {})]
    (reify qp.si/StreamingResultsWriter
      (begin! [_ {{:keys [ordered-cols results_timezone]} :data} viz-settings]
        (swap! formatters (constantly (zipmap
                                        ordered-cols
                                        (map (fn [col]
                                               (p.common/get-format results_timezone col viz-settings))
                                             ordered-cols))))
        (csv/write-csv writer [(map (some-fn :display_name :name) ordered-cols)])
        (.flush writer))

      (write-row! [_ row _row-num cols {:keys [output-order]}]
        (let [[ordered-row
               ordered-cols] (if output-order
                               (let [row-v  (into [] row)
                                     cols-v (into [] cols)]
                                 [(for [i output-order] (row-v i))
                                  (for [i output-order] (cols-v i))])
                               [row cols])]
          (csv/write-csv writer [(map (fn [c r]
                                        (let [formatter (@formatters c)]
                                          (formatter (common/format-value r))))
                                      ordered-cols ordered-row)])
          (.flush writer)))

      (finish! [_ _]
        ;; TODO -- not sure we need to flush both
        (.flush writer)
        (.flush os)
        (.close writer)))))
```

The formatters for each column are build in the `begin!` function and then looked up in each `write-row!`.  The existing `format-value` is used to produce a string then passed into our looked up column formatter.

Note that the new unit tests simulate a pulse and grab the provided temp files as attachments and analyzes those for correctness. This should work in a CI environment so long as the test process has permission to both write attachments to the temp directory and read those attachments back out. Also note that these tests can be slow (but not terribly so).

Primary changes:
- `metabase.email.messages` - fix spelling
- `metabase.pulse.render.body` - move `get-format` out of this ns
- `metabase.pulse.render.common` - move `get-format` into this ns
- `metabase.query-processor.streaming.csv` - new logic to apply pulse renderer formatting to csv exports
- `metabase.pulse.pulse-integration-test` - adding unit tests

One TODO before a final commit of this PR is to move the `get-format` logic out of a pulse ns into something more general. Ultimately, it would be nice if this was a common capability used by both BE and FE.

* Updated formatter state

The rows in qp.si/StreamingResultsWriter are ordered, so there should be no need to do a lookup by col. We should just be able to map the ordered-formatters (using the same order as the cols) with the ordered row data.

* Updating tests in `metabase.query-processor.streaming-test` to reflect new csv formatting.

* Updated fomatter for tests and consistency

This updates several tests (metabase.query-processor.streaming.csv-test) to reflect the new and correct behavior of using a common csv formatter as well as update the formatting code to correctly handle relational types and datetimes.

* require fmt

* Updating metabase.pulse.render.body-test to reflect `:type/DateTime` formatting.

* Updating sqlite test

* Updating report-timezone-test to reflect new CSV rendering

* Fixing e2e test
2023-12-07 17:52:00 +00:00
Jerry Huang
2805014a56 Throw better error message when passing a resource id as string instead of number (#36491) 2023-12-07 09:28:02 -08:00
Braden Shepherdson
25ce6e4cf8 [MLv2] Unskip FE integration tests for automatic-insights drills (#36529)
This was missed from #36443.

Fixes #33558.
2023-12-07 11:39:56 -05:00
metamben
e97a889f34 Enable converting simple value expressions from pMBQL to legacy (#36493)
Fixes #36459.

Also makes sure that legacy to pMBQL works and that simple value expressions can be named.
2023-12-07 15:04:32 +00:00
Anton Kulyk
8b0fe5b6e4 Fix dashboard filter width in edit mode (#36483)
* Use `minWidth` instead of `width`

* Reserve left padding for the settings icon
2023-12-07 10:53:11 +00:00
Gustavo Saiani
79074fa7e1 Tweak code block in doc (#36501) 2023-12-07 11:42:52 +01:00
Alexander Solovyov
10596a2d11 add target branch name to backporting branch for less conflicts (#36479) 2023-12-07 12:45:55 +03:00
Noah Moss
1475898165 Fix erroring migration and add test to exercise MB_DB_AUTOMIGRATE=false option (#36387) 2023-12-06 22:39:05 -05:00
Cam Saul
b9f55626b9 Misc zoom-in-timeseries drill fixes (#36505) 2023-12-06 17:59:32 -08:00
Braden Shepherdson
b95eb1a48d [MLv2] Implement automatic-insights drill (#36443)
Automatic insights drills have some unusual conditions.
This adds `metabase.lib.metadata/editable?` and checks it before
returning any drills.

On settings:
In the app, `MetabaseSettings` is a global singleton and the settings
are sometimes updated in place. In the JS testing environment several
mock settings instances can exist at once, and the global singleton does
not necessarily have the values we want for any given test.

This PR makes `metabase.lib.metadata/setting` check for `describe` and
`it` to see if we're in the testing environment, and to trust the
metadata's `settings` in that case.
2023-12-07 01:36:17 +00:00
Cam Saul
e87c11e923 Misc zoom-in-geographic drill fixes (#36448) 2023-12-06 17:35:51 -08:00
Cam Saul
3da3f9c909 quick-filter drill should return contains and does-not-contain for text columns (#36449) 2023-12-06 23:59:49 +00:00
Cam Saul
40b3574303 Misc zoom-in-bins drill fixes (#36445) 2023-12-06 18:26:49 -05:00
Noah Moss
dfab35bfaf Ensure that admin perms override group manager in GET /api/user (#36446) 2023-12-06 13:47:11 -05:00
Cal Herries
19e1f98d62 Move upload-csv! to metabase.upload (#36404) 2023-12-06 14:23:00 +00:00
Alexander Solovyov
a46cad0ea9 put reaction on the comment ASAP when reacting to backport command (#36460)
so that user knows that workflow has started
https://octokit.github.io/rest.js/v20#reactions-create-for-issue-comment
2023-12-06 12:46:01 +03:00
Alexander Solovyov
f2b7f78d42 add Snyk workflow (#36349)
Resolves #35677
2023-12-06 08:32:24 +00:00
Alexander Polyankin
f8ec8b309e Move drills FE tests to master (#36454) 2023-12-06 09:46:51 +02:00
Kamil Mielnik
2dc72a8ba2 Expressions in FilterPicker without legacy query (#36396)
* Add expression-clause-for-legacy-expression

Fixes #34830.

* Add legacy-expression-for-expression-clause

* Fix wrapper function name

* Include ExpressionClause in Aggregatable type

* Use Aggregatable type in aggregate function

* Rename query to legacyQuery in Expressions (part 1)

* Rename query to legacyQuery in Expressions (part 2)

* Rename query to legacyQuery in Expressions (part 3)

* Support MLv2 expressionClause in processSource and ExpressionWidget

* Revert changes to ExpressionStep as it's out of scope of this task

* Use new expressionClause in ExpressionWidget

* Use onSelect instead of onSelectLegacy in handleExpressionChange

* Remove onSelectLegacy from AggregationPicker

* Use nullish coalescing operator

* Assert new onChangeExpression argument in test

* Assert new onChangeExpression argument in test

* Update AggregationPicker tests

* Replace toEqual + expect.objectContaining with toMatchObject

* Add stageIndex to setup, use destructuring for onSelect arguments

* Deal with awkward assertions

* Use props in a conservative way

* Replace legacyQuery.database() with query + metadata

* Add a TODO comment

* Add clause prop to AggregationPicker

* Migrate clause name

* Replace 3rd argument in onChangeExpression with onChangeExpressionClause

* Use destructuring

* Allow AggregationClause, drop expression from ExpressionEditorTextfield

* Make withExpressionName work with AggregationClause

* Rename expressionClause to clause

* Update tests with new interface

* Use overloading instead of generics

* Add function body

* Rename operator to clause

* Revert "Use overloading instead of generics"

This reverts commit 3953f85b8f.

* Fix tests failing due to useSelect usage in AggregationPicker

* Omit aggregation options converting expressions to legacy

Fixes #36120.

* Remove temporary hack

* Get rid of props spread

* Migrate isExpressionEditorInitiallyOpen to MLv2

* Omit aggregation options converting expressions to legacy

Fixes #36120.

* Normalize legacy expressions as MBQL expressions

* Fix isExpressionEditorInitiallyOpen

* Update expressionName signature

* Pass props in ExpressionStep tests in a usual way

* Drop a conditional statement

* Bring back expression prop for backwards-compatibility

* Update ExpressionWidget validation & tests

* Bring back using expression in componentWillReceiveProps

* Bring back removed assertion

* Remove legacyQuery prop from AggregationPicker

* Add a test case for isExpressionEditorInitiallyOpen (which uses Lib.expressionName)

* Fix legacyQuery creation

* Add assertion for expression name

* Fix committing expression with done button

* Improve assertions in tests

* Make with-expression-name set the display-name of the clause

Fixes #36167.

This is needed to be able to set/change the display name of custom aggregation columns too.

* Add expression name assertion

* Add expression name assertion

* Add expression name assertion

* Add expression name assertion

* Add expression name assertion

* Add expression name assertion

* Add expression name assertion

* Unskip an e2e test

* Add expression name assertion

* Add expression name assertion

* Use displayInfo instead of displayName
- see https://github.com/metabase/metabase/pull/36203#discussion_r1410496658

* Deprecate displayName in favor of displayInfo
- see https://metaboat.slack.com/archives/C0645JP1W81/p1701341786914219?thread_ts=1701335646.088359&cid=C0645JP1W81

* Use clearer notation

* Format code

* Use displayInfo instead of expressionName in tests

* Add isNamed attribute to ColumnDisplayInfo and ClauseDisplayInfo

* Use displayInfo instead of expressionName in AggregationPicker

* Drop expressionName

* Drop redundant cast

* Simplify isExpressionEditorInitiallyOpen interface

* Use display-info with :named? instead of expression-name

* Improve comment

* Add :named? to the schema of display-info

* Use conditional types for ExpressionWidget prop

* Use getNotebookStep

* Simplify condition

* Simplify assertions

* Use .lastCall

* Remove isNamed attribute from ColumnDisplayInfo

* Use .lastCall

* Fix typing

* Bring back legacyQuery prop to AggregationPicker

* Fix isExpressionEditorInitiallyOpen for new clauses

* Fix unit tests

* Remove wrong assertion

* Fix assertion

* Trigger a change

* Revert "Trigger a change"

This reverts commit 254913dd85.

* Fix assertion

* Allow FilterClause

* Drop legacyFilter usage from FilterPicker, FilterStep & QuestionFilters

* Update FilterPicker unit tests

* Remove unused function

* Fix types in unit test

* Remove redundant waitFor

* Update ColumnDisplayInfo type

* Revert changes to ColumnDisplayInfo, avoid using semanticType & effectiveType attributes

* Introduce NamedClause and CustomExpressionClause types

* Simplify assertions

* Remove casting from FilterPicker

* Rename NamedClause to CustomNameClause

* Exclude AggregationClause from FilterPicker's interfaces

* Avoid casting using generics
2023-12-06 14:45:25 +07:00
Denis Berezin
2ffee750cb Set embedding visual settings before initial render (#36095)
* Move embedding settings prep before rendering

* Revert not needed change

* Add dynamic embedding settings for preview mode, add e2e tests for embedding settings

* Refactor test, remove not needed code

* Updates for e2e test based on code review
2023-12-06 07:35:51 +00:00
Levente Kurusa
18742132b6 team: add levex to BEC (#36434) 2023-12-06 07:00:09 +01:00
Mahatthana (Kelvin) Nomsawadi
d4f85c244c Fix click behavior link to dashboards/questions not using client router (#35975)
* Fix click behavior link to dashboards/questions not using client router

* Make the code cleaner

* Fix unit tests

* Make API clearer

* Address review: Handle case insensitive subpath

* Add E2E tests

* Fix failed E2E tests

* Fix another fail E2E test

* Add a test to ensure invalid URL won't break navigation

* Add tests + ensure multiple level subpath works
2023-12-06 05:40:08 +00:00
Cam Saul
51757c4a01 Return row count: 2 instead of negative row count (#36389) 2023-12-05 18:11:20 -08:00
Cam Saul
117fee84ea Return :pk drills for non-PK values in rows with multiple PKs (#36440) 2023-12-05 15:37:45 -08:00
Alexander Polyankin
562b09483d Fix scrolling in filter picker (#36375) 2023-12-05 23:34:17 +02:00
Mark Bastian
0521497a7c Updating default number-formatter for percents (#36431)
* Updating default `number-formatter` for percents

The number formatter used in some static viz rendering (e.g. tables) in `metabase.pulse.render.common/number-formatter` had logic to render only integer-valued percents for values between 1 and 100 and render two significant digits otherwise.

The FE default formatter uses 2 significant digits consistently in `frontend/src/metabase/lib/formatting/numbers.tsx`:

```js
const PRECISION_NUMBER_FORMATTER = d3.format(".2f");
```

This change modifies `number-formatter` to consistenly use 2 significant digits for percentage types.

Note that this does NOT apply to fields with custom formatting. Presently, custom column formatting does not appear to be applied for HTML tables at all for BE rendering while it is applied on the FE. This is a separate issue. This PR just brings the baseline behaviors based on typing into alignment.

* Fixing formatting test
2023-12-05 20:38:03 +00:00
Jeff Bruemmer
19f8bc1d25 docs - hide when empty (#36427) 2023-12-05 14:58:36 -05:00
Nick Fitzpatrick
37d701680b Adding markdown support to search result descriptions (#36360)
* Adding markdown support to search result descriptions

* adding e2e test
2023-12-05 15:53:56 -04:00
Jerry Huang
f4448046ee Filter values leaked in API request on Embedding (#36152) 2023-12-05 10:32:36 -08:00
Braden Shepherdson
a0c3e90a04 [MLv2] Underlying records: show drills on clicks with no :column (#36319)
That fixes "chart legend" clicks and "pivot cell" clicks, which should
show underlying records and automatic insights drills.

Fixes #35343 and #35394.
2023-12-05 13:32:15 -05:00
Nick Fitzpatrick
e1c4687d32 Adding pagination to All Personal Collections page (#36255)
* Adding pagination to All Personal Collections page

* adding unit test

* test adjustments
2023-12-05 13:51:40 -04:00
Oleg Gromov
2af32bbc73 Fix card filter connected to a field not causing an update (#36206)
* Rename DashboardHeaderView to match filename
* Fix non updating cards on filter mapping to a field
* Clean up DashboardApp tests a bit
* Clean up Dashboard.jsx cruft
* Add Dashboard componentDidUpdate "unit tests"
* Simplify setup code as per feedback
* Add test for changing dashboard prop in componentDidMount
* Change constant names
* Fix optional chaining in Dashboard
2023-12-05 16:27:49 +00:00
Ryan Laurie
2aae0cdfed Handle Release Notes for Release Candidates (#36378) 2023-12-05 09:02:09 -07:00
Luis Paolini
358920868e Add Metabase version argument to Dockerfile (#36402)
* Add version to Dockerfile

When you want to build with a specific version, you need to pass it on the build args

* Update Dockerfile
2023-12-05 12:39:08 -03:00
Kamil Mielnik
6e8e6f076b Expressions in AggregationPicker without legacy query (#36031)
* Add expression-clause-for-legacy-expression

Fixes #34830.

* Add legacy-expression-for-expression-clause

* Fix wrapper function name

* Include ExpressionClause in Aggregatable type

* Use Aggregatable type in aggregate function

* Rename query to legacyQuery in Expressions (part 1)

* Rename query to legacyQuery in Expressions (part 2)

* Rename query to legacyQuery in Expressions (part 3)

* Support MLv2 expressionClause in processSource and ExpressionWidget

* Revert changes to ExpressionStep as it's out of scope of this task

* Use new expressionClause in ExpressionWidget

* Use onSelect instead of onSelectLegacy in handleExpressionChange

* Remove onSelectLegacy from AggregationPicker

* Use nullish coalescing operator

* Assert new onChangeExpression argument in test

* Assert new onChangeExpression argument in test

* Update AggregationPicker tests

* Replace toEqual + expect.objectContaining with toMatchObject

* Add stageIndex to setup, use destructuring for onSelect arguments

* Deal with awkward assertions

* Use props in a conservative way

* Replace legacyQuery.database() with query + metadata

* Add a TODO comment

* Add clause prop to AggregationPicker

* Migrate clause name

* Replace 3rd argument in onChangeExpression with onChangeExpressionClause

* Use destructuring

* Allow AggregationClause, drop expression from ExpressionEditorTextfield

* Make withExpressionName work with AggregationClause

* Rename expressionClause to clause

* Update tests with new interface

* Use overloading instead of generics

* Add function body

* Rename operator to clause

* Revert "Use overloading instead of generics"

This reverts commit 3953f85b8f.

* Fix tests failing due to useSelect usage in AggregationPicker

* Omit aggregation options converting expressions to legacy

Fixes #36120.

* Remove temporary hack

* Get rid of props spread

* Migrate isExpressionEditorInitiallyOpen to MLv2

* Omit aggregation options converting expressions to legacy

Fixes #36120.

* Normalize legacy expressions as MBQL expressions

* Fix isExpressionEditorInitiallyOpen

* Update expressionName signature

* Pass props in ExpressionStep tests in a usual way

* Drop a conditional statement

* Bring back expression prop for backwards-compatibility

* Update ExpressionWidget validation & tests

* Bring back using expression in componentWillReceiveProps

* Bring back removed assertion

* Remove legacyQuery prop from AggregationPicker

* Add a test case for isExpressionEditorInitiallyOpen (which uses Lib.expressionName)

* Fix legacyQuery creation

* Add assertion for expression name

* Fix committing expression with done button

* Improve assertions in tests

* Make with-expression-name set the display-name of the clause

Fixes #36167.

This is needed to be able to set/change the display name of custom aggregation columns too.

* Add expression name assertion

* Add expression name assertion

* Add expression name assertion

* Add expression name assertion

* Add expression name assertion

* Add expression name assertion

* Add expression name assertion

* Unskip an e2e test

* Add expression name assertion

* Add expression name assertion

* Use displayInfo instead of displayName
- see https://github.com/metabase/metabase/pull/36203#discussion_r1410496658

* Deprecate displayName in favor of displayInfo
- see https://metaboat.slack.com/archives/C0645JP1W81/p1701341786914219?thread_ts=1701335646.088359&cid=C0645JP1W81

* Use clearer notation

* Format code

* Use displayInfo instead of expressionName in tests

* Add isNamed attribute to ColumnDisplayInfo and ClauseDisplayInfo

* Use displayInfo instead of expressionName in AggregationPicker

* Drop expressionName

* Drop redundant cast

* Simplify isExpressionEditorInitiallyOpen interface

* Use display-info with :named? instead of expression-name

* Improve comment

* Add :named? to the schema of display-info

* Use conditional types for ExpressionWidget prop

* Use getNotebookStep

* Simplify condition

* Simplify assertions

* Use .lastCall

* Remove isNamed attribute from ColumnDisplayInfo

* Use .lastCall

* Fix typing

* Bring back legacyQuery prop to AggregationPicker

* Fix isExpressionEditorInitiallyOpen for new clauses

* Fix unit tests

* Remove wrong assertion

* Fix assertion

* Trigger a change

* Revert "Trigger a change"

This reverts commit 254913dd85.

* Fix assertion

---------

Co-authored-by: Tamás Benkő <tamas@metabase.com>
2023-12-05 15:35:58 +00:00
Cam Saul
d9676b6a2f Do not return zoom/pk/fk-details drills for null cell values (#36385) 2023-12-05 15:26:35 +00:00
metamben
93240c31cd Make with-expression-name set the display-name of the clause (#36203)
Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>
2023-12-05 18:01:25 +03:00
metamben
4f1b430d34 Add column-name and table-name to fk-filter drill's display-info (#36217) 2023-12-05 17:59:23 +03:00
Alexander Solovyov
7faf1d7869 dashboard_tab.entity_id is nullable now, makes drop-entity-ids work (#36401)
resolves #36365
2023-12-05 13:47:57 +00:00
Alexander Polyankin
5699abe2ca Move filter components to area folder (#36393) 2023-12-05 11:53:14 +00:00
Ryan Laurie
2f3d88850d Update node and java versions for v48 release (#36379) 2023-12-05 11:59:04 +01:00
Cal Herries
064555e679 Uploads: Make the display name for the _mb_row_id column "_mb_row_id" (#36361) 2023-12-05 10:50:40 +00:00
Oleg Gromov
6fbc94fe67 Update e2e docs to emphasize running FE for testing (#36352) 2023-12-05 13:40:03 +03:00
Ngoc Khuat
52ce152c4b Task ns cleanup: use malli and remove log translation (#36394) 2023-12-05 10:39:38 +00:00
Cal Herries
05ce228a73 Use malli=? instead of #hawk/malli etc (#35481) 2023-12-05 12:09:33 +02:00
Ngoc Khuat
6515ea7597 Sync dynamic tables for snowflake (#36121) 2023-12-05 01:58:34 +00:00
Mark Bastian
25c9addf98 Ensure Metadata is Propagated for Standalone Pulse Cards (#36357)
Pulse cards based on models with user-curated metadata were not showing proper formatting for percentages. This is because the singe `execute-card` function in `metabase.pulse.util` was not adding in the card `:result_metadata` when the card was a model.

The metadata is now properly added.

Additionally, `metabase.pulse.pulse-integration-test` has been refactored for reuse. The `with-metadata-data-cards` macro provides 3 examples of cards that should be tested (a base card, a model card, and a derived question) and a function that executeds the pulse and returns the resulting data in the last column (The one we are asserting on).

Note that as we develop the test scenario in this ns there may be further refactoring opportunities, such as returning the attachments from the pulse email as well.
2023-12-04 17:58:11 -07:00
bryan
a6cba791f2 MB_CLOUD_GATEWAY_IPS is settable from env var (#36257)
* MB_CLOUD_GATEWAY_IPS is settable from env var

it can be set to a comma delimited sequence of ips like: "1.2.3.4,5.6.7.8".

* lint fix

* uncomment cloud-gateway-ips setter

* Make sure there's a value for mb-cloud-gateway-ips

- before testing that it gets printed out

* use .first to call .within on a single value
2023-12-04 18:15:46 -06:00
Braden Shepherdson
0e044b963e [MLv2] Underlying records: use card name as label for nested queries (#36318)
Fixes #35340 by using the card's name if this question's source is a card.
2023-12-04 18:04:32 -05:00
Aleksandr Lesnenko
8d2b239631 fix backport comment command (#36380) 2023-12-04 19:32:33 -03:00
dpsutton
9b5af86bfe fix flaky audit tests (#36331)
* fix flaky audit tests

somehow (and _only_ in cloverage running) we seem to end up with the
audit collection but no cards in it. Then all of the tests are failing
which check permissions.

```
ERROR in (cannot-edit-audit-content-dashboards-over-api) (metabase/util.cljc:114)
expected: (= "You don't have permissions to do that." (mt/user-http-request :rasta :put 403 (str "dashboard/" (u/the-id dashboard)) {:name "My new title"}))
  actual: java.lang.Exception: Not something with an ID: nil
 at metabase.util$error.invokeStatic (metabase/util.cljc:114)
```

This is failing

```clojure
(deftest cannot-edit-audit-content-dashboards-over-api
  (install-audit-db-if-needed!)
  (let [dashboard (t2/select-one :model/Dashboard :collection_id (:id (perms/default-audit-collection)))]
    (is (= "You don't have permissions to do that."
                                                                   ;; this dashboard is nil
                                                                   ;; and u/the-id errors
           (mt/user-http-request :rasta :put 403 (str "dashboard/" (u/the-id dashboard)) {:name "My new title"})))))
```

So let's ensure that all of the cards, dashboards, and collection exist,
otherwise install them. Previously it was just checking that the
collection existed, and for some reason it was empty

* uncomment audit tests

* remove excess comments + rewrite exists? queries

---------

Co-authored-by: bryan <bryan.maass@gmail.com>
2023-12-04 15:40:22 -06:00
Case Nelson
26ddaa11c5 Test for #35319 (#36218)
* Test for #35319

Closes #35319

* Address review comment and fix linter
2023-12-04 18:13:14 +00:00
Jacob Joseph
44c1342fd7 Update collections.md (#36356)
changed format to bullets and added note about the badge showing up for Questions in official collections on dashboards not in official collections
2023-12-04 12:05:08 -05:00
Alexander Polyankin
aaf4a43816 [MLv2] Filters FE integration branch (#34191) 2023-12-04 18:47:35 +02:00
Kyle Doherty
f9d03e2c9e Allow toggling of the dashboard subscription sidebar from the icon (#36244)
* allow for toggling of isSharing state from the icon trigger

* add a test for sidebar toggling

* use a more standard method of toggling the state

* account openDashboardSubscriptions starting with the sidebar open

* switch to using sidebar to check for existence, do it once

* update openPulseSubscription helper to account for new behavior
2023-12-04 11:29:50 -05:00
metamben
a10bf2bd3a Enable auto commit (#36094) 2023-12-04 18:12:37 +03:00
Ryan Laurie
138f6a110f Ensure collections are loaded before showing entity copy form (#36329) 2023-12-04 07:46:41 -07:00
Oisin Coveney
33e24dd523 Fix broken auto-wiring when adding a new card to a dashboard (#36312) 2023-12-04 16:23:07 +02:00
Mahatthana (Kelvin) Nomsawadi
efa2aca074 Fix all unused arg errors (#36269)
* Fix all unused arg errors

* Address review: Clean up default + remove unused args
2023-12-04 12:06:40 +00:00
Uladzimir Havenchyk
d208140a03 [webpack] Always write to disk (#36335)
Co-authored-by: Mahatthana (Kelvin) Nomsawadi <me@bboykelvin.dev>
2023-12-04 11:49:36 +00:00
Cal Herries
320d699424 Comment flaky BE tests (#36341) 2023-12-04 12:37:11 +01:00
Uladzimir Havenchyk
5cd985ce32 [webpack] Do not restore yarn cache twice (#36337) 2023-12-04 11:34:26 +00:00
Uladzimir Havenchyk
7d375928c6 [Storybook] Build cljs with NODE_ENV=development to override default settings (#36340) 2023-12-04 14:26:36 +03:00
Ngoc Khuat
560cf7087c Includes question name to the archived alert email (#36069) 2023-12-04 11:10:53 +00:00
metamben
6e0b739ad7 Make sure the app DB is initialized (#36333) 2023-12-04 12:03:11 +02:00
Mahatthana (Kelvin) Nomsawadi
129018c767 Fix failed E2E from 61f2b28dd6 (#36339) 2023-12-04 10:10:18 +01:00
Alexander Solovyov
c3f7e594e6 store query_execution.cache_hash (#36223) 2023-12-04 10:06:50 +03:00
metamben
41a2247d72 Omit aggregation options converting expressions to legacy (#36155) 2023-12-02 01:59:30 +03:00
Ryan Laurie
61f2b28dd6 [Auditv2] Reproduce #36228 (analytics content is editable) (#36239) 2023-12-01 19:57:25 +00:00
Ryan Laurie
6139931386 Update visitDashboard e2e helper to be tabs-aware (#36314) 2023-12-01 12:56:29 -07:00
Braden Shepherdson
1599779c5d [MLv2] Implement drillThru() for pivot drills; add BE unit tests (#36281)
Fixes #33559.
2023-12-01 14:25:29 -05:00
lbrdnk
16988f50d6 Use server side generated timestamps for :relative-datetime (#35995)
* WIP: Use server side generated timestamps for :relative-datetime

* Use correct timestamp in :relative-datetime and add tests

* Update tests

* Remove combinations of tzs test

I've added those to commit in case we
need to refer to it in future. Tests like that take ~500 seconds,
hence good for one off testing.

* Update docstrings and comments

* Use string formatted qp.timezone/now as a base

* Address review remarks

* Remove redundant data from "last queries" query

* Update tests

- Add comment that points on discussion on flake potential of a test.
- Correct the order of expected and actual in another test.
- Add formatting to rows and select only necessary for testing in a test.
2023-12-01 20:25:05 +01:00
Mark Bastian
0684896893 Document and test adding results_metadata to qp middleware for static viz (#36245)
* Adding results_metadata to qp middleware

This adds two middlewares to `metabase.query-processor.middleware.results-metadata`:
- `inject-result-metadata`: Adds `result_metadata` from the context, if present, into the query map during preprocessing.
- `merge-existing-metadata`: A post-processing middleware that merges `results_metadata` (if present) from the query data into the metadata.

This has the effect of preserving existing metadata, which is particularly important for user-curated metadata, such as semantic type overrides.

This may also facilitate addressing the following TODO in the same ns:

```
;; 1. Is there some way we could avoid doing this every single time a Card is ran? Perhaps by passing the current Card
;;    metadata as part of the query context so we can compare for changes
```

* Preserving result_metadata in query processor

This PR uses `qp.util/combine-metadata` to simplify the combination of provided `:result_metadata` with computed metadata. It also updates pulse rendering code to use this new code path and adds and updates tests to vet this logic.

* fmt

* Modifying PR to document and use existing fns

The current qp pipeline will correctly propagate custom metadata if a question is derived from a model or if the model is processed like so:

```clojure
(qp/process-query
  (assoc-in dataset_query [:info :metadata/dataset-metadata] result_metadata))
```

This PR fixes rendering unit tests to clarify this and provides a much better working example in the `dev.render-png` ns.

* Updating test

* Adding Pulse w/Metadata Tests

This pr adds a unit test that constructs a dashboard and simulates a pulse email, then checks the resulting HTML for correctness.

A dependency on the [hickory](https://github.com/clj-commons/hickory) library was added to dev. This allows us to easily parse HTML into data and navigate the parse tree.

Note that it does NOT check the attachments for formatting correctness.

Spelling and import consistency changes were also made.
2023-12-01 18:31:22 +00:00
metamben
e57355fefe Restrict available-segments to the first stage (#36276) 2023-12-01 21:07:17 +03:00
Nick Fitzpatrick
11a710d99f fetching specific collections for file upload toasts (#36241) 2023-12-01 14:03:42 -04:00
Cal Herries
2bad0d2688 Rework auto-generated PKs for CSV uploads (#36249) 2023-12-01 16:39:00 +00:00
Jeff Bruemmer
b394546c38 update release list (#36279) 2023-12-01 10:12:38 -05:00
Ryan Laurie
c6be297db2 [Auditv2] Don't show broken move and archive buttons for analytics collections (#36238) 2023-12-01 08:03:59 -07:00
Nemanja Glumac
b1bbfbe1e6 Increase the number of Cypress test snapshots locally (#36271) 2023-12-01 13:05:26 +00:00
Aleksandr Lesnenko
8824ebae3c fix dashcard table visual lag (#36226) 2023-12-01 02:51:42 +00:00
bryan
49cbb576c6 disable can-write for cards in default audit collection (#36237)
* Fixes can-write? for:

- cards/dashboards that are direct children of the audit collection
- root collection + oss
- adds tests for both

* test root collection read/write semantics with audit-app

- remove comments

* check for :id on default-audit-collection

* in audit-content perms: ensure the audit db exists

* [skip ci] add comment

* reword comment
2023-11-30 16:17:37 -06:00
Nick Fitzpatrick
d5b36c592f Mapping editor update (#36093)
* mapping editor uses state

* fixing button alignment

* adding unit tests
2023-11-30 17:09:39 -04:00
Mark Bastian
6f2876f9f7 Update dashboard and card api POST and PUT endpoints to return as GET (#36205)
* Adding stub for POST+GET same result

This commit just stubs in the `post-same-as-get-test` test in `metabase.api.dashboard-test`.

* Hydrating POST /api/dashboard results to = GET

This is the first stage of "PUT and POST and endpoint should return data just like calling GET #34828" in which a POST to create a dashboard also hydrates the details needed to return the identical results as if it were a GET.

This enables a single API call vs. two (a POST and and immediate GET).

* Adding updated value to PUT /api/dashboard response

This change adds the same hydration logic to PUT responses as POST responses.

Also added a span around `update-dashboard` to have parity with `get-dashboard`.

* Changed span name for consistency

* Updating create-dashboard-test to include GET comparison

To be consistent with the PUT test this just combines two tests for dashboard creation into one.

* POST/PUT api/card now returns same value as GET

The primary change is using the same hydration logic across the board.

This ensures the same object shape is returned for all operations an removes the need for a GET immediately after a POST or PUT when a create or update action occurs.

* Removing GET on Dashboard Save

When a dashboard is updated via PUT, the succeeding GET operation is no longer needed and has been removed.

* Restored fetch unrelated to dashboard creation.

* Adding =? to `create-a-card` test.

* Updated testing forms to reflect issue being addressed (#34828).

* Reduced expected e2e load count for 21556 test

This e2e test was example based and expected a PUT + 3 additional GETs. With the new code you only need to do 2 GETs since the PUT result is used.

* Renaming fns and reducing root collection hydration for cards

Rebased on master and merged with @calherries `metabase.api.card` changes.

Renamed `hydrate-for-frontend` to `hydrate-card-details` and added a span for observability.

Removed `collection.root/hydrate-root-collection` which makes cards returned from POST and PUT not identical to GET, but only because the `:collection` key is missing, which should already be present on the FE in these situations. Tests were updated to reflect this.

* Reverting FE changes

The FE changes for this are not a subtle as simply removing a follow on GET. It makes more sense to let the BE changes get merged then the the FE team work on leveraging those changes.
2023-11-30 12:44:29 -07:00
Aleksandr Lesnenko
5cf3ee64cc fix bad merge around dashboard reducers (#36246) 2023-11-30 19:19:08 +00:00
Cal Herries
6433ebc68c Add missing settings (#36236) 2023-11-30 16:12:10 -03:00
Aleksandr Lesnenko
f4415fec85 fix blank dashboard when opened from bookmarks (#35896) 2023-11-30 14:15:51 -03:00
Nemanja Glumac
1d7209de36 Remove getBrokenUpTextMatcher helper from E2E tests (#36234)
Cypress already has `cy.contains()` that is doing the exact same thing.
2023-11-30 17:37:11 +01:00
shaun
9cd2bdbfbd Disable autofocus on SettingsSAMLForm (#36150)
* Disable autofocus on SettingsSAMLForm

* Update index.js
2023-11-30 16:55:10 +01:00
Kamil Mielnik
5bc1ee389c Rename "Aggregatable" to "Aggregable" (#36165)
* Rename Aggregatable to Aggregable in frontend

* Rename Aggregatable to Aggregable in backend
2023-11-30 21:40:33 +07:00
Ngoc Khuat
4d3a6bd408 Alert/Dashboard subscription: render question title as <a> tag (#36220) 2023-11-30 14:23:54 +00:00
Cal Herries
9015166747 Extend "Add check for connection status before sync" to presto-jdbc, oracle, and vertica (#36119) 2023-11-30 13:02:58 +00:00
Ngoc Khuat
676fcd8c98 Install clojure before running clj-kondo (#36222) 2023-11-30 12:36:50 +00:00
Nemanja Glumac
24bed25059 Fix E2E replay stray job dependency (#36219)
* Fix stray job dependency

* Run every two hours
2023-11-30 11:50:38 +01:00
Fernando Brito
dc7c10735b Fix query remarks on Snowflake (#29888)
* Fix query remarks on Snowflake

* Move docstrings out of defmethod

* Add test to Snowflake query remarks

* Improve test on Snowflake query remark

* Remove unnecessary comment
2023-11-30 10:10:36 +01:00
Cal Herries
532a833a1f Move functions for creating and updating cards from api to models namespace (#36123) 2023-11-30 08:05:23 +00:00
Noah Moss
a8b3326651 Change default log level for publish-event! to debug (#36213) 2023-11-29 16:35:31 -05:00
Braden Shepherdson
78c167c0e4 [Mlv2] Make ambiguous matches a warning in lib.equality (#36197)
This mitigates the impact of an ambiguous case we can't quickly fix
properly; see #27521 for the crash and #36185 for the larger issue.

With this change the impact of #27521 is reduced so it is not blocking
48.
2023-11-29 14:19:39 -05:00
Nemanja Glumac
b85414cb5d Tweak ReplayIO E2E runs (#36138)
* Run ReplayIO E2E tests every three hours

* Fix the conditional and run all tests

* Upgrade replay runner to the latest version

* Use unique GitHub run id to tag Replay runs

* Make replay API key available to each run

* Use native replay upload

* Upgrade replay plugin to v1.7.5
2023-11-29 19:37:46 +01:00
adam-james
907ecd0d5e Attach dashcard's viz settings to the card's :data :viz-settings key (#36067)
* Attach dashcard's viz settings to the card's :data :viz-settings key

This flows through to the export format fn `metabase.email.messages/stream-api-results-to-export-format`
Where it is then properly used.

* Added test that gets the contents of .csv attachments

Not sure yet why it's not working. Locally, with a real db id it works as expected, so it's on the right track.

* Create a working test.

* Card qp merges dashcard viz when it exists. Viz middleware normalizes card/dashcard viz-settings

* Addressed feedback.

 - if viz settings map is empty in process viz settings middleware, use qp store.
 - now we don't have to do the (or ...) logic anywhere else
 - added comment in the test to try clarify what the 'viz' is setting up
2023-11-29 09:32:51 -08:00
Nemanja Glumac
e58d751f42 Mark additional E2E flakes (#36169)
* Mark pivot tables test that failed recently

A failure in `master` from November 23, 2023.
https://www.deploysentinel.com/ci/runs/655f74c4fcacf3cead2261a5

* Tag top 10-ish recent flakes
2023-11-29 12:29:34 -05:00
Noah Moss
c58a39ac55 Truncate audit_log and view_log based on AUDIT_MAX_RETENTION_DAYS env var (#35940) 2023-11-29 11:59:51 -05:00
Oleg Gromov
1dd62d96bf Housekeeping: remove default exports from dashboard/* (#36191)
* Remove default exports from dashboard/*
* Remove dashboard index.js/ts re-exports
2023-11-29 16:44:30 +00:00
Jacob Joseph
5eaac8ff18 [docs] Update athena.md (#36199)
* Update athena.md

Added notes about permissions requirements especially re: Lake Formation as a source and changed headings to have a H2 permissions heading with the example bucket policy under it.

* Update docs/databases/connections/athena.md

Co-authored-by: Jeff Bruemmer <jeff.bruemmer@gmail.com>

---------

Co-authored-by: Jeff Bruemmer <jeff.bruemmer@gmail.com>
2023-11-29 16:38:29 +00:00
Aleksandr Lesnenko
4c6e9089f7 support Percentage setting in the semantic type editor, infer percentage column formatting default (#36186) 2023-11-29 12:11:27 -03:00
Ryan Laurie
05d4eaffbc Release Without Github (#35937) 2023-11-29 08:04:17 -07:00
Aleksandr Lesnenko
9ea5ad2b53 Create stub backport PR when there are conflicts (#36188) 2023-11-29 10:56:41 -03:00
Ngoc Khuat
f97ef4f4cc Fix deadlock when running api tests in the repl (#36190) 2023-11-29 18:15:13 +07:00
shaun
0bb85bf4ae Migrate SettingsJWTForm to formik (#35969) 2023-11-28 23:17:34 +00:00
Mark Bastian
c35a6fe966 Adding Percent Metadata Type (#36145)
* Adding Percent Metadata Type

This adds the :type/Percentage metadata type to Metabase. It does
not currently do any fingerprinting. It just enables setting of the
type for the FE.

* Making :type/Percentage a semantic type as well as a decimal.

* support Percentage setting in the semantic type editor, infer percentage column formatting default

* Support for static-viz rendering when user metadata is `:type/Percentage`

This PR adds in user-defined metadata in `prep-for-html-rendering` so that `number-formatter` can properly render the column as a percentage. This may actually fix a family of issues as user-defined metadata doesn't appear to be used anywhere in this ns. We still need to consider cases where the formatting is specified by the viz settings, but this one step in the right direction.

* Percent semantic types render as percents in tables

This PR adds logic to properly capture a percent semantic type and renders it as such in a table static viz. Note that the `number-formatter` function in `metabase.pulse.render.common` has logic that renders the percent as a truncated int. IDK if this the desired long term behavior. I'll have to ask product that, but if we just make the change it could have potential impacts on places that expect this behavior. It seems like it would make more sense to be like Excel and allow each column to set its significant digits.

* Revert "support Percentage setting in the semantic type editor, infer percentage column formatting default"

This reverts commit e001e6312e6f0bd5700c1d9eb28c88829d87a70a.

---------

Co-authored-by: Aleksandr Lesnenko <alxnddr@gmail.com>
2023-11-28 21:48:33 +00:00
Mark Bastian
571030561d Fix event logging to print correct output (#36179)
The fix in #35895 included reducing the size of the printed object, but the drilled elements needed to be pulled from the object key in the event, not the event itself. This fixes that.
2023-11-28 19:53:23 +00:00
Ngoc Khuat
facb3cc4da Don't log a full exception when fetching a dashboard that has a stray param (#33613) 2023-11-28 15:21:45 +00:00
Oleg Gromov
7ebdea1757 Emotion: suppress SSR warnings (#36134) 2023-11-28 14:08:32 +00:00
Uladzimir Havenchyk
600d38c47b Add recommended vscode extensions (#36102) 2023-11-28 11:30:30 +00:00
bryan
e0e0646201 ✍️✉️: Dashboards and Cards in Custom Reports should be writable (#35890)
* `can-write?` dashboards + cards in Custom Reports

* use the audit-db-id which will always be there

* in tests, audit collection should have id 13371337

- and type = 'instance-analytics'

* throw in type just for fun

* Update test/metabase/models/collection_test.clj

don't use the magic number

* better default collection detection

---------

Co-authored-by: Ryan Laurie <iethree@gmail.com>
2023-11-27 17:39:17 -06:00
Jacob Joseph
6d71195d4c [docs] Update models.md (#36056)
* Update models.md

added a note about the timezone used for model caching cron schedules

* Update docs/data-modeling/models.md

Co-authored-by: Jeff Bruemmer <jeff.bruemmer@gmail.com>

---------

Co-authored-by: Jeff Bruemmer <jeff.bruemmer@gmail.com>
2023-11-27 18:24:49 -05:00
John Swanson
057149b606 make max results configurable (#35600)
This replaces the existing setting max-results-bare-rows with two settings:

- `max-unaggregated-query-row-limit`, and
- `max-aggregated-query-row-limit`
2023-11-27 22:27:22 +00:00
Noah Moss
d74c448936 Update audit yamls new keyorder (with index migration fix) (#36151)
Co-authored-by: Noah Moss <noahbmoss@gmail.com>
Co-authored-by: Ryan Laurie <iethree@gmail.com>
Co-authored-by: Noah Moss <32746338+noahmoss@users.noreply.github.com>
Co-authored-by: Luiz Arakaki <luiz.arakaki@metabase.com>
2023-11-27 16:53:32 -05:00
Jacob Joseph
b8ce977411 [docs] Update upgrading-metabase.md (#34578)
* Update upgrading-metabase.md

added note about major version upgrades taking longer

* Update docs/installation-and-operation/upgrading-metabase.md

Co-authored-by: Jeff Bruemmer <jeff.bruemmer@gmail.com>

---------

Co-authored-by: Luis Paolini <paoliniluis@gmail.com>
Co-authored-by: Jeff Bruemmer <jeff.bruemmer@gmail.com>
2023-11-27 16:35:49 -05:00
Jeff Bruemmer
43398d5b9d cc or bcc (#36142) 2023-11-27 11:05:36 -08:00
Noah Moss
dc3110a0df Revert "Update audit yamls new keyorder (#35634)" (#36139)
This reverts commit 210978dbcf.
2023-11-27 13:13:37 -05:00
Noah Moss
f6f941bf93 Add error handling around creating new SSO user, and fix with-model-cleanup macro (#36018) 2023-11-27 12:46:30 -05:00
Oleg Gromov
5375347e33 Remove unused humanizeCoercionStrategy and its test suite (#36136) 2023-11-27 17:30:28 +00:00
Luiz Arakaki
210978dbcf Update audit yamls new keyorder (#35634)
* update yamls for latest change on key order

* bring custom reports back

* add Metabase Analytics instance type

* add new view v_tasks, iterate content adding links

* add v_tasks to permissions

* fix double precision types for h2 and mysql

* add type to instance analytics col

* add mysql rollback

* fix paths in migration

* handle dynamic tab ids

* update yamls click behavior

* add namespace=analytics to audit collection

* add type to collection

---------

Co-authored-by: Noah Moss <noahbmoss@gmail.com>
Co-authored-by: Ryan Laurie <iethree@gmail.com>
Co-authored-by: Noah Moss <32746338+noahmoss@users.noreply.github.com>
2023-11-27 14:17:44 -03:00
Oleg Gromov
54a44772dd Remove divider in QueryBuild/ViewHeader when it's not needed (#36128) 2023-11-27 15:57:22 +00:00
Nemanja Glumac
ddfb64e9ff [E2E] Re-enable previously quarantined pie chart null test (#36077)
* Unskip previously quarantined pie chart nulls test

* Update card details
2023-11-27 16:06:16 +01:00
Oleg Gromov
2c968465a8 QueryBuilder and SQL questions: hide Explore results with parameters (#36105)
* QueryBuild and SQL questions: hide Explore results with parameters
* Fix AtomicQuery.canNest return type (so that it is always boolean)
* Add Question.canExploreResults tests
2023-11-27 13:36:42 +00:00
Alexander Solovyov
1d7ec26d58 rename deserialized snippet's name if it conflicts with existing one (#36083)
Co-authored-by: Ngoc Khuat <qn.khuat@gmail.com>
Co-authored-by: Cal Herries <39073188+calherries@users.noreply.github.com>
2023-11-27 09:24:39 +00:00
Cal Herries
53b5182db7 Fix BE flake 36089: metabase.api.search-test/search-db-call-count-test (#36100) 2023-11-27 10:21:12 +02:00
Cal Herries
4a6de48c05 Add check for connection status before sync (#35964) 2023-11-27 08:01:20 +00:00
Alexander Solovyov
d71ff9a280 collection serialization should export parent collections too (#36081)
adds new `ascendants` multimethod, which traverses tree upwards w/o looking for children.
2023-11-27 10:23:47 +03:00
Alexander Solovyov
dc05b2a65f check every model has serialization setup (#35874)
Pulse and related are skipped for now: they have a full serialization support, but are not serialized.
2023-11-27 10:14:21 +03:00
lbrdnk
f21c438523 Use mysql:latest for mysql CI job and update driver code accordingly (#36025)
* Adjust mysql container env

* Setting the HOST can cause trouble they said

https://hub.docker.com/_/mysql. Let's try it without then.

* Also MYSQL_USER doesn't play well with empty password

* Cast results of temporal extract to decimal

* Update test

* Update test

* Revert casting temporal-extract results to decimals

* Handle mysql YEAR type as a number instead of a date

* Cleanup
2023-11-24 20:00:39 +01:00
lbrdnk
e357b23802 Use sessions in mongo aggregation pipelines (#35680)
* Use mongo sessions in aggregation pipelines

Using sessions, cancel signal from streaming response can be handled
correctly - query is killed also on database side.

* Update tests

* Let the middleware handle the exception

While coding the other test, I've found out that if exception is handled
in the `reducible-results`, code clogs for 3 minutes,
which is `.maxTime` for aggregation. I don't know the exact reason yet,
but for time being I'm leaving the exception handling to middleware.

* Add testing string

* Encode aggregation results as `BasicDBObject`

Use this type instead of BSON's Document because code transforming
DBObject to clojure structures is already in place.

* Update exceptions handling and tests

Exception handling now more resembles code in other drivers. Tests were updated
to use mbql query instead of raw native to avoid differences between various
mongodb versions. `$dateTrunc` was not available in version 4.

* Increase cancelation interval in tests

* Address remarks and update test to handle cold start

By cold start I mean running it before dataset is initialized.

* Remove unnecessary hint
2023-11-24 19:59:30 +01:00
Alexander Solovyov
95e4946187 Handle CVE in commons-compress and org.json/json (#36106) 2023-11-24 21:50:11 +03:00
Braden Shepherdson
40ed065a9b [MLv2] Include query, stage and column for quick filter drills (#36092)
See #35878 which did the same for `column-filter` drills.

This reuses the logic from that PR to include the same information on
`quick-filter` drills as well. Most quick filters are a single click,
but there are a few special cases that are more involved and require
showing a complete filtering UI.

This renames `lib.js/column-filter-drill-details` to
`lib.js/filter-drill-details` as well.

---------

Co-authored-by: Alexander Polyankin <alexander.polyankin@metabase.com>
2023-11-24 12:00:54 -05:00
Cal Herries
dd42791e01 Uploads: Make empty values NULL for MySQL (#36088) 2023-11-24 14:42:23 +02:00
Cal Herries
d25c356a4d Tidy CSV uploads (#36082) 2023-11-24 13:54:15 +02:00
Nemanja Glumac
f3f5a93f5e [E2E] Re-enable previously quarantined audit v1 schemas test (#36080)
* Fix and unskip the previously quarantined audit v1 test

* Improve assertions
2023-11-24 10:28:37 +01:00
metamben
3ba6a357a7 Handle JS object input and output properly (#36087) 2023-11-23 23:30:32 +03:00
metamben
15f4c27823 Ensure testing select privilege works with and without auto commit (#36062) 2023-11-23 19:05:05 +00:00
Case Nelson
1643b15756 [MLv2] Short name display for filter clauses (#35933)
* [MLv2] Short name display for filter clauses

Fixes #35752

Built for the timeseries widget and the associated operators. Generally
shows the user selected dates and occasionally shows an operator.
The choices are about what looks correct more than following particular
rules.

* fix newline
2023-11-23 11:38:23 -07:00
Nick Fitzpatrick
c018882705 Update Admin User Form to use Formik (#35892)
* Update Admin User Form to use Formik

* typing LoginAttributesWidget

* Making first and last name not required

* PR Feedback

* adding unit tests

* fixing email selector
2023-11-23 11:19:29 -04:00
Oleg Gromov
db30a96b82 Update parameter input styles (#36047)
* Update parameter input styles
* Remove unused class
* Remove unused flex-basis
2023-11-23 13:46:14 +00:00
Alexander Polyankin
03ed7ccc06 Fix browserify-sign version (#36073) 2023-11-23 11:29:08 +00:00
Ngoc Khuat
3481e43964 makes sure delete tables will delete download/data permissions as well (#35983) 2023-11-23 10:19:56 +00:00
Nemanja Glumac
0f63e7ec61 Remove stray (misleading) audit readme (#36070)
We started running audit tests in the CI again, but forgot to
remove this file.
2023-11-23 08:44:16 +00:00
Cam Saul
b159e818a4 zoom, fk-details, fk-filter drills should be returned for a native query model (#35891) 2023-11-22 18:08:26 -08:00
Jeff Bruemmer
9fe9cdc690 update list of releases (#36065) 2023-11-22 17:59:52 -05:00
Nemanja Glumac
7577ebeb3e [E2E] Re-enable monitoring permissions test (#36050)
* Unskip previously quarantined test

* Improve test readability
2023-11-22 23:21:08 +01:00
Nemanja Glumac
c06f6d0d10 [E2E] Re-enable previously quarantined chart drill test (#35986) 2023-11-22 20:29:50 +01:00
shaun
3ed8f8ed67 Fix submit button in SettingsSAMLForm (#36017)
disable submit button if form is unchanged, and fix spacing
2023-11-22 12:38:33 -06:00
Uladzimir Havenchyk
044f937e04 Use swcMinify to speedup bundle minification (#36022) 2023-11-22 19:41:17 +03:00
John Swanson
f651588bee Skip excess keys on serialization load (#35748)
When loading from a backup, we should not fail if the previous version saved keys that are no longer needed in the
current version. This adds a step (after ingestion but before loading) that removes any "extra" keys from the ingested
entity.

How?

- make `load-xform-basics` remove extraneous keys from the ingested model.

- by default, it identifies the "extraneous keys" as keys *other than* keys corresponding to column names in the database.

- for *some* ingested models, there is not a 1:1 correlation between an ingested model and a `:metabase/model`. For example, when we ingest an `"Action"`, that corresponds to the `:model/Action` model. But that model has three "submodels" - `:model/QueryAction`, `:model/HttpAction`, and `:model/ImplicitAction` - and when we load the ingested map into the database, `action/insert!` will insert subsets of the map it receives into _two_ tables (`action` plus one of the submodel tables).

- to handle this case, `serdes/ingested-model-columns` is a multimethod, which we can override. For example, for `"Action", we override it to include the full set of columns that exist in any of the model/submodel tables.

Co-authored-by: bryan <343288+escherize@users.noreply.github.com>
2023-11-22 08:19:51 -08:00
Braden Shepherdson
cfe72f6994 [MLv2] Return query, stage index and column for column-filter drill (#35878)
If this drill is targeting an aggregation column, the query needs an
extra stage added. To enable the custom filtering UI, this (possibly 
updated) query, stage number, and the correct column
*in that new stage* are returned as part of the opaque `column-filter` drill.

`lib.js/column-filter-drill-details` is added to hand those details
to the FE as a JS object containing opaque CLJS values.
2023-11-22 15:59:35 +00:00
Nemanja Glumac
da976077b9 [E2E] Re-enable previously quarantined approved domains test (#36041)
* Unskip previously quarantined test

* Fix lint errors in subscriptions test

* Fix lint errors in the alert test
2023-11-22 15:25:05 +00:00
Oleg Gromov
626d240a01 Fix widget border in StringInputWidget, NumberInputWidget (n arity) (#36007) 2023-11-22 11:45:53 +00:00
Alexander Solovyov
d41964fdd7 Fix pivot table de/serialization (#35944)
resolves #30133 and #30134
2023-11-22 10:11:17 +00:00
Alexander Solovyov
c7eff8ddbb fix loading click_behavior (#35990)
extracting was fixed in 0f1c19433b, also resolves #35880
2023-11-22 12:47:08 +03:00
Kamil Mielnik
fc773670de Rename query to legacyQuery in expressions (#35989) 2023-11-22 08:55:19 +00:00
Nemanja Glumac
36c612715e [E2E] Re-enable custom mapping null test (#35984)
* Re-enable custom mapping null values test

* Remove misleading comment

* Address review comments
2023-11-22 08:47:52 +00:00
Ryan Laurie
4368da8b87 Add helpful label and comment for external PRs (#36019) 2023-11-22 09:10:12 +01:00
Nemanja Glumac
a8e3b5d1fd Remove @flaky tag from pivot tables sorting test (#35992) 2023-11-22 08:49:40 +01:00
metamben
3481ff301d Add expression-clause-for-legacy-expression (#35936) 2023-11-21 22:05:46 +03:00
Nemanja Glumac
e516a2232f Revert external workflow custom solution (#35993)
* Revert "Improve external filter checks (#35740)"

This reverts commit 8ef7eb5914.

* Revert "Make Chromatic workflow 3rd party friendly (#35708)"

This reverts commit 931029e0bd.

* Revert "Make E2E workflow 3rd party friendly (#35643)"

This reverts commit b547eb7eb4.

* Revert "PoC External workflow run trigger (#34951)"

This reverts commit df16fc89e9.
2023-11-21 19:01:16 +01:00
Jeff Bruemmer
4de1461ab1 update api docs (#35994) 2023-11-21 12:08:49 -05:00
Jeff Bruemmer
92e4964f99 docs - update filters (#35963) 2023-11-21 11:54:39 -05:00
Nemanja Glumac
beb2642deb [E2E] Fix pivot table sorting fields flake (#35912) 2023-11-21 15:58:21 +01:00
Nemanja Glumac
644b8c80e0 [E2E] Fix dashboard card "default sizes" flake (#35756)
* Fix E2E dashboard cards "default sizes" flake

* Increase the request timeout and remove the `@flaky` tag

* Add test to the "slow" E2E group
2023-11-21 15:57:45 +01:00
Ngoc Khuat
90538a8c0d Revert task to delete inactive tables (#35981)
* Revert "When attemp to delete inactive tables, skip tables that have active cards (#35693)"

This reverts commit 2586ef0d86.

* Revert "Daily task to delete old inactive tables (#35443)"

This reverts commit cd97591335.
2023-11-21 20:10:28 +07:00
Mahatthana (Kelvin) Nomsawadi
d149840374 Fix embedding crashes when one of the cards fails to load (#35851)
* Fix static/public embed crashes when query returns error

* Add E2E test to reproduce the issue

* Sort the key more consistently
2023-11-21 05:14:06 +00:00
Ngoc Khuat
2586ef0d86 When attemp to delete inactive tables, skip tables that have active cards (#35693) 2023-11-21 04:35:27 +00:00
Aleksandr Lesnenko
7ede1b1e27 Fix TableSimple styles (#35927)
* fix TableSimple styles

* tweak sorting icon opacity

* Update TableSimple.styled.tsx
2023-11-21 00:04:09 +00:00
Jerry Huang
f37af97ca5 Add analytics namespace (#35894) 2023-11-20 15:22:55 -08:00
shaun
5d9f3cbd2a Migrate SettingsSAMLForm to formik (#35731) 2023-11-20 17:07:55 -06:00
Cam Saul
010aef2130 Toucan 2 × MLv2 metadata (#35928) 2023-11-20 16:57:23 -05:00
Alexander Polyankin
458dd3e3dd Revert "Revert "Rollback mbqlv2 drills - sort, fk-filter, summarize-column-by-time (#35917)" (#35926)" (#35951) 2023-11-20 22:51:15 +01:00
dpsutton
1290ecf78d Alternative fix mu defn (#35939)
* Revert "Clarify stacktraces from malli validation errors (#34712)"

This reverts commit 1a0f2d6587.

* Alternative fix for mu/defn correctness issue

https://github.com/metabase/metabase/pull/34712 introduced a correctness
bug:

```clojure
(macroexpand '(metabase.util.malli/defn foo [x :- string?] :foo))

(def
 foo
 "Inputs: [x :- string?]\n  Return: :any"
 (clojure.core/fn
  ([a] (metabase.util.malli.fn/validate-input {:fn-name 'user/foo} string? a) ((clojure.core/fn [x] :foo) a))))
```

The simplest demo of the bug is

```clojure
user=> (metabase.util.malli/defn foo [x] a)
 #'user/foo
```

The macro used simple and predictable args for it's emitted
functions. This was not a problem with the original shape:

(different macroexpansions of `(mu/defn foo [x :- int?] (inc x))`):

prior to 34712:

```clojure
(def
 foo
 "Inputs: [x :- int?]\n  Return: :any"
 (clojure.core/let
  [&f (clojure.core/fn [x] (inc x))]
  (clojure.core/fn
   ([a] ;; simple argument name not a problem
    (metabase.util.malli.fn/validate-input
      {:fn-name (quote metabase.util.malli.fn-test/foo)}
      int?
      a)
    (&f a)))))
```

after 34712:

```clojure
(def
 foo
 "Inputs: [x :- int?]\n  Return: :any"
 (clojure.core/fn
  ([a] ;; simple argument name is now a problem
   (metabase.util.malli.fn/validate-input {:fn-name 'user/foo} int? a)
   ((clojure.core/fn [x] (inc x))
    a))))
```

after this PR:
```clojure
(def
 foo
 "Inputs: [x :- int?]\n  Return: :any"
 (clojure.core/let
  [&f (clojure.core/fn [x] (inc x))]
  (clojure.core/fn
   ([a] ;; again simple argument name is not a problem
    (try
     (metabase.util.malli.fn/validate-input
      {:fn-name (quote metabase.util.malli.fn-test/foo)}
      int?
      a)
     (&f a)
     (catch
      java.lang.Exception
      error
      (throw (metabase.util.malli.fn/fixup-stacktrace error))))))))
```

And the fix here is just to remove the StackTraceElements which
reference `validate`, `validate-input`, or `validate-output`.

* fix tests

tests are run in the user namespace similar to

```clojure
user=> (clojure.test/run-tests 'metabase.util.malli.fn-test)

Testing metabase.util.malli.fn-test

Ran 8 tests containing 43 assertions.
0 failures, 0 errors.
{:test 8, :pass 43, :fail 0, :error 0, :type :summary}
```

But we still want the namespace of _this_ file m.u.m.fn-test
2023-11-20 14:46:06 -06:00
Nemanja Glumac
a0004dea6c Print inputs in stress-test workflow summary (#35953) 2023-11-20 19:42:40 +01:00
lbrdnk
377fc675a6 Revert "update next.jdbc (release with the fix is out already) and honeysql (#35941)" (#35957)
This reverts commit 10cdb49db4.

CI fails because of commit that is being reverted.
2023-11-20 18:56:22 +01:00
Oleg Gromov
f298820ccd Add oleggromov to Team/QueryingComponents (#35956) 2023-11-20 17:43:51 +00:00
metamben
373f4c4ff2 Add expression-name and with-expression-name (#35932) 2023-11-20 18:32:22 +03:00
Nick Fitzpatrick
9849cfbab5 remove line height and add bottom margin (#35931) 2023-11-20 09:54:18 -04:00
Denis Berezin
7c4edc8a1b Revert "Rollback mbqlv2 drills - sort, fk-filter, summarize-column-by-time (#35917)" (#35926) 2023-11-20 15:18:04 +02:00
Alexander Solovyov
10cdb49db4 update next.jdbc (release with the fix is out already) and honeysql (#35941) 2023-11-20 14:58:16 +03:00
Mahatthana (Kelvin) Nomsawadi
e0e0abfe6d Add an E2E test (#35844) 2023-11-20 10:56:45 +00:00
Ngoc Khuat
79f54d6992 Remove POST ee/serialization/serialize/data-model (#35849) 2023-11-19 12:13:14 +07:00
Noah Moss
0bc5932bc6 Temporarily disable flaky auditv2 query test (#35934) 2023-11-17 23:30:15 +00:00
bryan
b4b5cb1c6d audit-log only when hosted or has-feature: audit (#35724)
* audit-log only when hosted or has-feature: audit

* lint fix

* check for the right feature name, and test better

* fix metabase.api.setting-test

* fix a bunch of tests

* fix a couple more tests

* bit of cleanup

* lint fixes

* fix testing function

* fix whitespace

* linter fix

* fix so many tests

* fix the rest of the tests, IIUC

* fix the last test

* lint fix

* remove outdated tests (from the merge conflict)

* disable-other-sso-types needs to _reset_ premium features.

- patches in the audit-app feature by default.

* Just need to re-add :audit-app as a premium feature

* try improving disable-other-sso-types
2023-11-17 17:20:53 -06:00
Jeff Bruemmer
a86be36c91 docs - metabase analytics (#35687) 2023-11-17 16:54:16 -05:00
Braden Shepherdson
30f1e9eea8 [MLv2] Disambiguate columns: :field refs shouldn't match expressions (#35872)
Expressions which just wrap a real Field get `:id`, `:table_id` etc. so
they match a `[:field {} 7]` ref. If that real field exists (table
default or joined), prefer that over the expressions.
2023-11-17 21:21:02 +00:00
Jerry Huang
3827a2b13c Add properties to query_execution (#35508) 2023-11-17 11:29:11 -08:00
Uladzimir Havenchyk
a1cee6276e Deduplicate babel dependencies in yarn.lock (#35712) 2023-11-17 22:03:13 +03:00
metamben
b08f93ac71 Port down migration and H2 dump loading test from 47 to 48 (#35805) 2023-11-17 21:52:57 +03:00
Mark Bastian
3e3e58c1a4 Cleanup of extra spans when diagnosing 33499 (#35918)
Fixes #33499

We added a bunch of OTEL spans to figure out what was going on with super long page loads. Turns out it was a slow pprint of massive objects.

This PR removes a few spans, but not all. The ones removed are either redundant or almost certainly not needed (I did remove the one around the offending code, but the negative space that would show if it happened again would reveal the issue -- LMK if we think we should put that one back).

One important thing to consider when reviewing this PR is if we like the current coverage level around the `metabase.events` code (plus a couple extra things that were instrumented). It feels right, but if it seems too onerous we could remove some.

As an observation, it _might_ make sense to add instrumentation to the high level functions in toucan2 itself, such as hydrate, select, etc. This would give us transparent instrumentation on the library and we could easily view traces to see the bounds of our db hot spots.
2023-11-17 11:42:09 -07:00
Denis Berezin
3f0f81c82c Rollback mbqlv2 drills - sort, fk-filter, summarize-column-by-time (#35917) 2023-11-17 18:22:14 +00:00
Jacob Joseph
ff43615a80 [docs] Update interactive-embedding.md (#35876) 2023-11-17 12:24:51 -05:00
Jeff Bruemmer
a197bee82b docs - samesite (#35888) 2023-11-17 12:11:44 -05:00
Roman Abdulmanov
8896c8c140 Slack notification about new issues (#35921) 2023-11-17 18:49:47 +02:00
Cal Herries
df6b1edfd9 Remove flaky remove-collection-color-test (#35847) 2023-11-17 17:26:58 +02:00
Alexander Solovyov
0f1c19433b fix exporting dashboard with configured click_behavior (#35911)
resolves #35880
2023-11-17 13:53:37 +00:00
Denis Berezin
69f7458992 Refactor drills unit tests structure, split huge file by drill type (#35883) 2023-11-17 13:08:32 +00:00
Nemanja Glumac
aa10916b67 [E2E] Fix "slugify collection name" flake (#35905)
* Fix "slugify collection url" flake

* Remove the `@flaky` tag
2023-11-17 13:06:10 +01:00
Uladzimir Havenchyk
59c90f6acd Drop dead code of the dashboard filters stickiness calculation (#35358) 2023-11-17 14:18:33 +03:00
Nicolò Pretto
fb50bcd80d try to restore correct position when undoing dashcard tab movement or deletion (#35502)
* try to restore the original position even when another card stole it

* avoid calling fetchCardData in undoRemoveCardFromDashboard for virtual dashcards

* test: e2e test for undo movement and card removal

* test to make the ci pass

* empty commit

* restore old scrollbehaviour

* refactored the magic number in a function so that also docs are in a single place
2023-11-17 10:03:11 +01:00
Nemanja Glumac
0f17ffb576 [E2E] Fix recent-views flake(s) (#35848)
* Fix recent-views flake(s)

* Remove the `@flaky` tag
2023-11-17 08:58:34 +01:00
Nemanja Glumac
6372597d68 [E2E] Fix flaky reproduction for 29951 (#35887)
* Visit model query directly

* Use helper to save model metadata changes

* Limit the number of results even more

* Improve assertions

* Increase the viewport width in order to see all columns
2023-11-17 08:53:59 +01:00
Cam Saul
887e8bf4d4 11x faster pretty printing (#35897) 2023-11-17 02:34:11 +00:00
Cam Saul
3841a66654 [MLv2] Strip question marks off of keys in JS version of display info (#35886) 2023-11-17 01:07:03 +00:00
Mark Bastian
f13a9d329b Fixing bad performance due to massive pprint statements (#35895)
Spans on stats for massive models are very long, on the order of 4s.

The bad span seems to encompass a small amount of logging and assertion
logic, including a with-out-str pprint, which I've found to be
notoriously slow for large objects. This PR slims down the logged object.

If this is the culprit we should see a substantial performance improvement.
2023-11-17 00:51:36 +00:00
Mark Bastian
c807ff52a8 Adding more spans to understand stats publish-event! (#35889)
* Adding more spans to understand stats `publish-event!`

https://stats.metabase.com/dashboard/2117 still takes 4s to load and
the current spans don't seem to provide fine granularity around the
hot spot, but it seems to be happening in the early stages of
`publish-event!`. These extra spans provide finer granularity.

* Adding what is probably a non-needed span, but we want to over-instrument this, if anything. Once we id the hotspot we can remove what we want.

* add more spans

* remove :object from new spans

---------

Co-authored-by: Noah Moss <noahbmoss@gmail.com>
2023-11-16 22:41:50 +00:00
Nemanja Glumac
2d9e0bf56b [E2E] Fix dashboard card resize flake (#35751)
* [E2E] Fix dashboard card resize flake

* Remove the `@flaky` tag

* Add test to the slow group
2023-11-16 20:39:30 +01:00
Case Nelson
4eead2477a [MLv2] Put duplicate implicit join columns in separate column-groups (#35436)
* [MLv2] Put duplicate implicit join columns in separate column-groups

* Add tests for cards without id fields in metadata

* Fix linter

* Fix test
2023-11-16 18:58:54 +00:00
Anton Kulyk
b5fba39c89 Mantine Modal (#35867)
* Add Mantine `Modal`

* Add guidelines link

* Fix heading in storybook
2023-11-16 18:58:26 +00:00
Nemanja Glumac
00d4072595 Remove non-existent input for download-uberjar (#35846) 2023-11-16 19:56:05 +01:00
Ryan Laurie
fa6918b9c2 Fix broken Root Collection permissions (#35716) 2023-11-16 11:46:51 -07:00
Uladzimir Havenchyk
36bf2568d6 Remove fromUrl parameter from QueryBuilder (#35861) 2023-11-16 21:34:25 +03:00
Nicolò Pretto
4e6d61ecdf type createThunkAction to avoid it leaking anys in all the codebase (#35784) 2023-11-16 18:23:30 +01:00
Oisin Coveney
ba7543a474 [Epic] Auto-wire up dashboard field filters (#35587)
* Auto apply dashboard filters with the same field (#35280)

* Add explanatory toast and `Undo` when auto-applying filters (#35461)

* Add data test ID to dashboard sidebar

* Auto apply filters to added cards

* Discard changes to frontend/src/metabase/parameters/utils/dashboards.ts

* Discard changes to frontend/src/metabase/dashboard/components/Sidebar.jsx

* Make sure that util functions work

* Attempt to split code to where it belongs

* Remove useless function

* Remove useless function

* Discard changes to frontend/src/metabase/dashboard/utils.ts

* Change names to match nomenclature

* Move more files around

* More fixes to types

* Move to helpers

* Solve some of the top levels

* Attempt to fix types

* Attempt to make types work without exploding

* Add undo elements for mapping existing parameters and adding a new card with a parameter

* Add undo toast to tests

* First attempt at setting up undos and disabling behavior for cards that have had their auto-wiring undone

* Add undo toasts and post-undo toast

* More changes

* Discard changes to frontend/src/metabase-lib/parameters/utils/targets.ts

* Discard changes to frontend/src/metabase-types/api/card.ts

* Split into files

* Split files

* Discard changes to e2e/test/scenarios/permissions/admin-permissions.cy.spec.js

* Fix typescript errors

* Make unit tests work

* Remove toasty states

* Add type for more complex parameter

* Fix type errors

* Remove disabled cards logic

* Fix e2e tests

* Add e2e tests to make sure everything works

* Update e2e/test/scenarios/dashboard-filters/parameters.cy.spec.js

Co-authored-by: Mahatthana (Kelvin) Nomsawadi <me@bboykelvin.dev>

* Use helpers in tests and refactor to keep dashcardAttributes in dashboard code

* fix undo timeout leak by clearing timeouts when undo is dismissed

* e2e: add e2e for timeout edge case

* test: add unit test for undo

* fix typo

---------

Co-authored-by: Mahatthana (Kelvin) Nomsawadi <me@bboykelvin.dev>
Co-authored-by: Nicolò Pretto <info@npretto.com>

* remove e2e test with cy.wait (#35850)

* removes a test that uses a cy.wait

* Revert "removes a test that uses a cy.wait"

This reverts commit 52d51140bbd3bc053fc7272d42a53feaa9c1c1bb.

* use cy.clock and cy.tick instead of cy.wait

---------

Co-authored-by: Mahatthana (Kelvin) Nomsawadi <me@bboykelvin.dev>
Co-authored-by: Nicolò Pretto <info@npretto.com>
2023-11-16 18:11:01 +01:00
Noah Moss
44f1e0e7c8 Add to view_log schema and clean up view events (#35732) 2023-11-16 11:38:31 -05:00
Alexander Solovyov
8a6d7d51ba export shouldnt break when click behavior can't be mapped to a model (#35865)
when linkType is "url", serialization broke since there is no corresponding model

Resolves #35855
2023-11-16 19:23:51 +03:00
Nicolò Pretto
45315fa445 fix tests failing because we are -45 days to the end of the year (#35860) 2023-11-16 13:18:29 +00:00
Kyle Doherty
517ff7cf49 UI Library text updates (#35833)
* use normal font weight for 'values'

* update label styles across inputs
2023-11-16 07:38:35 -05:00
Cal Herries
4b6677d789 Fix outdated serialization references in docs/comments (#35585) 2023-11-16 14:29:17 +02:00
Roman Abdulmanov
5d91e6b7da Slack notification about new issues (#35853) 2023-11-16 11:06:31 +00:00
Ngoc Khuat
8812adc396 Tracks .clj-kondo/com.github.steffan-westcott/ (#35845) 2023-11-16 11:02:06 +00:00
Uladzimir Havenchyk
3c54987ff5 Add tests verifying that #18817 has been fixed (#35744) 2023-11-16 10:53:47 +00:00
Case Nelson
4d929086ed [MLv2] Export find-matching-column (#35678) 2023-11-16 12:46:52 +02:00
Uladzimir Havenchyk
b6bfe3c06c Add test for #14648 'Pivot action on a scalar in an x-ray results in a broken visualization' (#35706) 2023-11-16 13:11:37 +03:00
Cam Saul
3c69865ac9 [MLv2] Fix reference generation for expressions with QP results metadata (#35831) 2023-11-16 07:44:03 +00:00
Ibe Dwi
15b7292f0b Add missing border-radius to the collection table (#35402) 2023-11-16 07:41:36 +01:00
Cam Saul
096198c027 Underlying-records drill should generate correct filters for binned columns (#35837) 2023-11-16 02:52:13 +00:00
Cam Saul
df321754c7 Move shared/src and shared/test code into regular src and test dirs (#35834) 2023-11-16 01:02:23 +00:00
Mark Bastian
4737d3653e Adding additional instrumentation to publish-event! (#35832)
* Adding additional instrumentation to `publish-event!`

The `publish-events!` defmethod has quite a few code branches and we're trying to figure out if one of these is causing the slowness described in #33499 as well as stats dashboard [2117](https://stats.metabase.com/dashboard/2117). This PR should provide additional information as to where the delays might be occurring.

It adds the following spans/changes:
- An `:events/initialized` attribute at the top level of `publish-event!`
- `record-view!` span
- `record-event!` span
- `update-users-recent-views!` span

If we merge this PR we can decide if these changes are worthwhile and revert if we don't like the additional layer of wrapping.

* Reinstating record-event! span to resolve rebase conflict.

* Fixing bad merge
2023-11-16 00:15:55 +00:00
Mark Bastian
baf0ee5f04 Fixing aggregate dropdowns in dashboard filters (#35754)
The `values-from-card-query` constructs a new query to determine
enumerable values for filter drop-downs in dashboards. It does this
by generating a simple query from the passed in query with the
filtered value as a query filter. This query didn't know about
expressions which the filter might use. The fix was to just add
in the expressions from the base query.

Fixes #12985
2023-11-15 22:58:56 +00:00
bryan
36f09dea0a seperate data from side effects in record-event! (#35715)
also adds quickcheck tests for user-id and model-id precedence
2023-11-15 16:11:41 -06:00
Jeff Bruemmer
f783c00775 docs - csv entity key (#35505) 2023-11-15 16:00:39 -05:00
metamben
579981e7e7 Add test for #31603 (#35688) 2023-11-15 23:58:41 +03:00
metamben
32376a99fe Add tests verifying that #18817 has been fixed (#35674) 2023-11-15 23:56:18 +03:00
Jeff Bruemmer
e1a94a1f12 docs - notes on personal collections (#35759) 2023-11-15 15:53:16 -05:00
Mark Bastian
40d7278631 Add otel instrumentation to diagnose 33499 (#35723)
* Adding clojure goes fast dependencies and configuration for debugging slow queries.

* Adding OTEL Span Instrumentation

This PR adds a Clojure library for adding opentelemetry spans for
code instrumetation along with a couple examples of instrumented
areas that could be hot spots.

* Adding span around run-query-async

* Adding `publish-event-async!`

The evidence for the slow loads of dashboards such as https://stats.metabase.com/dashboard/2117
as described in https://github.com/metabase/metabase/issues/33499
point to long synchronous calls in `metabase.events/publish-event!`.

This change does the following:

- Adds a span to `publish-event!` for instrumentation
- Adds an async version of the function
- Changes the GET api/dashboard/:id call to use the async function

Based on the discussion in [this slack thread](https://metaboat.slack.com/archives/CKZEMT1MJ/p1697604232592589)
we may not want to retain the async call ATM, but we could use it as
a stopgap for now.

As an aside, we might want to introduce a queue such as activemq if
we really need asynchronous behavior.

* Rebasing and reconciling with master

* Modifying ws to be like master in deps.edn

* sort nses

* Removed dead code

* Removed unneeded check-404

* Added TODO comment wrt goals for db performance

* Whitespace changes

* Removing async publication call
2023-11-15 20:48:06 +00:00
Cam Saul
a79f0e69fb Fix time bucketing for Postgres, MySQL, SQL Server, SQLite, and Vertica TIME columns (#35574) 2023-11-15 20:09:21 +00:00
Noah Moss
3e86d3172f Tweak audit view migration test to catch subsequent migrations that break the views (#35760) 2023-11-15 17:12:02 +00:00
Braden Shepherdson
ee02083913 Fix serdes of click_behavior on dashcards (#35717)
Several parts of this structure contain MBQL and dashboard/card
references that need exporting and importing, which was being missed.
2023-11-15 12:06:45 -05:00
Ryan Laurie
7213d15014 Add warning for h2 uploads db (#35664) 2023-11-15 16:35:15 +00:00
Alexander Solovyov
5369e1cfe4 better logging for escaped cards (#35741)
Resolves #33882
2023-11-15 14:24:01 +00:00
Cal Herries
e9b7a8cb04 Prevent updating a database from closing connections unnecessarily when updating database-enable-actions setting (#35713) 2023-11-15 13:46:30 +00:00
Cal Herries
ca8f2f7ae0 Track dashboard_saved snowplow event (#35703) 2023-11-15 13:41:18 +00:00
Nemanja Glumac
8ef7eb5914 Improve external filter checks (#35740)
* Improve and unify `external-filter` checks

* Refine E2E jobs conditionals
2023-11-15 13:59:23 +01:00
Nemanja Glumac
4657ee5a6f Improve uberjar.yml workflow (test multi-arch job) (#35737)
* Improve `uberjar.yml` workflow

It previously didn't even run multi-arch job if not on `master`.
There's no reason not to run this job. The trick is only to **not** push
the changes to DockerHub, unless we're on the `master` branch.
2023-11-15 12:56:02 +01:00
Mahatthana (Kelvin) Nomsawadi
e5a26b6de6 Reattempt: Add fonts in Dockerfile to fix pulses (#35736)
* Add fonts in Dockerfile to fix pulses (#31764)

Add Noto fonts in Alpine Dockerfile

* Fix Docker build command

---------

Co-authored-by: Luis Paolini <paoliniluis@gmail.com>
2023-11-15 07:45:35 +00:00
Ryan Laurie
6676158dfc Quarantine Flaky e2e Tests (#35676)
* add special flaky group

* tag tests with flakes over 10%

* mark more flaky jobs
2023-11-15 07:53:46 +01:00
Maxime Pauvert
2bc1e45585 Fix iframe-resizer readyCallback to onReady (#35541) 2023-11-15 07:51:01 +01:00
Nemanja Glumac
c6293fee64 Revert "Add fonts in Dockerfile to fix pulses (#31764)" (#35735)
This reverts commit 44de976d97.
2023-11-15 07:26:12 +01:00
Ngoc Khuat
a5b5bd2185 Split migration (#34400) 2023-11-15 12:35:40 +07:00
Aleksandr Lesnenko
d9a447792e Hide edit question menu item on dashboards when there is no collection write permission (#35686)
* Hide edit question menu item on dashboards when there is no collection write permission

* Add :can_write to dashboard->dashcards->cards

This hydrates each card in a dashboard's dashcards with :can_write.

* Check in a dashboard test that :can_write shows up on cards.

Just adding a key to one of these tests to let us know that it's being hydrated.

---------

Co-authored-by: Adam James <adam.vermeer2@gmail.com>
2023-11-14 19:59:24 -03:00
Ibe Dwi
ea3b02806a Fix negative value on loading dashboard title (#35633)
* fix: duplicated loadingIds on pending action

* chore: rename unit test name
2023-11-14 22:46:09 +01:00
Anthony Hivert
e48a7ce9e6 fix(presto): typo on kerberos title (#35456) 2023-11-14 16:44:57 -05:00
Case Nelson
085e8d99f7 [MLv2] Adds stage-count (#35722)
Fixes #35719
2023-11-14 16:41:39 -05:00
Mark Bastian
d4957af142 Adding linter and formatter pre-commit hooks for staged BE files
* Adding linter and formatter to staged BE files.

Note that `.cljfmt/indents.clj` tries to capture our indent rules
and, so far, seems to get things right. There are still some inconsistencies
in some of our nses in how we indent assoc(-in) and some t2 functions
when it comes to key-value pairs on following lines. Should the keys
align with the function call or be indented. Aesthetically, people
seem to like indents, but these are functions, so should align with the
first argument. IDK that it really matters as long as we have agreement.

We may, as we adopt this, have some files be reformatted in unexpected ways
for items that have been missed. If so, the developer can simply update
the .cljfmt/indents.clj file, rerun the hook, and commit that along with
their other changes.

* Added whitespace linter.

* Updating husky commit hook

* Updated hook scripts to be exclusively for staged files.

Updated cljfmt to use the latest and greatest along with the new format of config file.

* Commenting out the actual formatting hook in .husky/pre-commit until we come up with a globally happy solution to forms that don't have good formatting rules, like defprotocol+ in a reader conditional.

* Reverting formatting

* Moving pre-commit hooks from .husky/pre-commit to the package.json's lint-staged section.

Note that we're still not calling the cljfmt file (.bin/cljfmt_staged.sh)
until we get agreement on formatting.

One thing we might do since we're using lint-staged is we can probably
exclude the "bad" files that go sideways with linting and format everything
else automatically. This might be a good follow-on PR.
2023-11-14 21:12:26 +00:00
Steve Xu
f0f4e7fe87 fix: correct "SQL editor" link (#34644) 2023-11-14 16:05:16 -05:00
Jeff Bruemmer
54e494c220 docs - perms update (#35720) 2023-11-14 16:01:06 -05:00
Cam Saul
359996a7e2 Add test for #16672 (#35557) 2023-11-14 20:41:19 +00:00
Luis Paolini
44de976d97 Add fonts in Dockerfile to fix pulses (#31764)
Add Noto fonts in Alpine Dockerfile
2023-11-14 17:38:42 -03:00
Cam Saul
bda435946d [MLv2] suggested-join-condition => suggested-join-conditions and handle composite keys (#35565) 2023-11-14 20:17:36 +00:00
Ibe Dwi
ba02a664a9 Fix misplaced negative sign on a currency visualization in Dashboard (#35632)
* fix: misplaced negative sign

* update formatting unit test

* chore: update test name
2023-11-14 17:01:33 -03:00
Uladzimir Havenchyk
a7e16c49cd [Storybook]: Deduplicate babel types to fix build (#35659) 2023-11-14 21:45:24 +03:00
Oisin Coveney
7b80be7771 Remove redundant /user/recipient API calls (#35644) 2023-11-14 20:13:22 +02:00
Cam Saul
b13f672b0a Remove skipped tests for #13764 (#35571) 2023-11-14 09:05:30 -08:00
Nemanja Glumac
b547eb7eb4 Make E2E workflow 3rd party friendly (#35643) 2023-11-14 17:44:26 +01:00
bryan
a1aebe900b remove internal user on rollback + test (#35684)
* remove internal user on rollback + test

* fix naming + add newline

* fix typo

* rollback change to migration changeset ID

- since it would alter the checksum for it
2023-11-14 09:42:53 -06:00
Nemanja Glumac
931029e0bd Make Chromatic workflow 3rd party friendly (#35708) 2023-11-14 14:02:33 +01:00
Nemanja Glumac
0c65b64585 Fix be-checks-stub (#35702) 2023-11-14 12:42:50 +01:00
Cal Herries
4933d809e2 Fix flaky upload-csv-test (#35654) 2023-11-14 09:53:44 +00:00
Roman Abdulmanov
322570e2da renamed a team label (#35701) 2023-11-14 09:18:28 +00:00
Ryan Laurie
05782f8eb1 Fix Milestone Reminder (#35685) 2023-11-14 10:15:11 +01:00
Ngoc Khuat
cd4d3d89b9 Returns 404 when get a non-existing card (#35695) 2023-11-14 09:04:37 +00:00
Ryan Laurie
48348bfb5e Revert "Workaround for E2E search failures due to audit V2 (#35655)" (#35681)
This reverts commit adfda06499 now that #35621 has fixed the underlying issue.
2023-11-14 08:30:31 +01:00
Cal Herries
bf771f5fb4 Allow spaces in datetime strings for uploads (#35647) 2023-11-14 09:09:21 +02:00
bryan
dd418bf7f7 respect MB_PLUGINS_DIR on serialization load (#35622)
* respect MB_PLUGINS_DIR on serialization load

* respect MB_PLUGINS_DIR on serialization load
2023-11-13 16:55:27 -06:00
bryan
c3bca15a39 dont increment audit db id + remove 1-arity (#35169) 2023-11-13 16:54:27 -06:00
Jesse Devaney
70c8d96c7c Hide read-only items in the Archive (#33602)
* refactor use-list-select hook

- toggleAll(items) felt unintuitive as some items could be selected while simultaneously unselecting others
  - switched to selectOnlyTheseItems(items) to be more explicit on what the function is doing
- updated consumers of useListSelect to use the new API

* convert to functional component

* convert HoC ListSelect to hook useListSelect

* convert redux connects to useSelectors

* refactor ArchiveApp and improve types

* hide read only items in the archive

* verify desired behavior

* refactor beforeEach

* remove unused eslint disable line

* refactor item can_write accessor logic

* Add :can_write key into the search data response. uses `mi/can-write?`

* update archive app for archived search changes

* refactor filtering of list

* replace hard-coded collection ids in spec

* move specific helper outside of generic helpers file

* remove admin gets unfiltered data

* BE sends only can_write true results when search with archived?=true

This change modifies the `check-permissions-for-model` method to check for write access if the SearchContext has
archived true.

This means that the only results sent to the frontend are those results that the user can take actions on, namely,
unarchiving them.

* reomve unused require

* update FE to account for BE changes

---------

Co-authored-by: adam-james <21064735+adam-james-v@users.noreply.github.com>
2023-11-13 17:46:08 -05:00
bryan
a98530f11a remove plugins dir when copying (#35291) 2023-11-13 13:47:08 -06:00
bryan
d522b91471 Audit db sync cannot happen (#35621)
* Audit db sync cannot happen

- disable all job scheduling for audit db
- make syncing/scanning auditdb a noop in prod (throws otherwise)

* better name for job-data -> jobs-to-create

* test no scheduling and no running audit db sync

* sort ns

* fix trivial check in test

* use metabase.task/scheduler-info intead qrtz table

* sort ns
2023-11-13 13:39:40 -06:00
Nemanja Glumac
58e91cb6d3 Run stubbed backend jobs when main backend tests are skipped (#35656) 2023-11-13 17:34:54 +00:00
Noah Moss
2a0665a2ef Tweak description of env variable in MB config file docs (#35400)
* tweak wording in config file docs

* Update docs/configuring-metabase/config-file.md

Co-authored-by: Jeff Bruemmer <jeff.bruemmer@gmail.com>

* add period

---------

Co-authored-by: Jeff Bruemmer <jeff.bruemmer@gmail.com>
2023-11-13 17:59:33 +01:00
Nemanja Glumac
adfda06499 Workaround for E2E search failures due to audit V2 (#35655) 2023-11-13 17:57:41 +01:00
Jeff Bruemmer
baf43a132b docs - command page (#35566)
* command page

* formatting

* command updates
2023-11-13 11:41:47 -05:00
Jeff Bruemmer
924498cf44 note on data sandboxing and caching (#35663) 2023-11-13 11:19:44 -05:00
Noah Moss
1308cefc7b Fix startup logic to correctly detect new installs when a config file is used (#35626) 2023-11-13 09:52:57 -05:00
Braden Shepherdson
40a3c2dde6 [MLv2] Fix NULL FK values in the QP and drill-thru (#35567)
The QP returns "large int" IDs like FKs as string, since JS doubles only
guarantee 51 bits of mantissa and a 64-bit ID might get rounded.
However NULL IDs were getting returned as `""` empty strings.

This fixes the QP middleware to return `nil` (JS `null`).

In addition, the drill-thru logic in the FE and MLv2 was trying to
filter incorrectly with a NULL value. This PR prevents the FK filter
drill from returning anything in that case.

I filed #35561 to track the fact that would be useful to drill thru to
all rows with a NULL for some FK, but it's low priority.

Fixes #13957.
2023-11-13 09:46:35 -05:00
Ryan Laurie
26d608a435 Offline Releases (#35440) 2023-11-13 07:43:44 -07:00
Nemanja Glumac
cc50e7a942 Fix E2E file-path triggers (#35646)
Follow up after #34892 

* Include E2E workflow in file-path triggers
* Adjust the glob for "actions" directories
2023-11-13 10:43:33 +01:00
Nicolò Pretto
7f41a7d9e9 fix: avoid calling fetchCardData in undoRemoveCardFromDashboard for virtual cards (#35545)
* avoid calling fetchCardData in undoRemoveCardFromDashboard for virtual dashcards

* test: adds basic e2e test for text card
2023-11-13 09:50:13 +01:00
Nemanja Glumac
e48bb5de8f Fix public link E2E flakes (#35616)
* Fix flake for repro 20393

* Fix flake for repro 22524

[ci skip]
2023-11-13 08:01:02 +01:00
Nemanja Glumac
2900a03ffa Fix "create new pulse" E2E flake (#35589)
[ci skip]
2023-11-13 08:00:39 +01:00
Braden Shepherdson
d00c3f6ac3 Revert "Generate sane SQL for a DATE[TIME] expression = DATE literal filter (#35523)" (#35592)
This reverts commit d140d676bf.

Co-authored-by: Case Nelson <case@metabase.com>
2023-11-12 15:52:00 +00:00
Noah Moss
1c28052263 Remove auditv2-main branch filter from uberjar workflow (#35624) 2023-11-11 23:23:39 +01:00
Mark Bastian
efea8d01e3 Fixing flaky tests related to inner-query-name-collisions-test (#32355) (#35612)
It appears the code fails when run in parallel due to the `metabot-settings/enum-cardinality-threshold` value.

To demonstrate, I ran:

```clojure
(frequencies
  (pmap
  (fn [_]
    (clojure.test/run-test inner-query-name-collisions-test))
  (range 1000)))
```

and got:

```
{{:test 1, :pass 12, :fail 0, :error 0, :type :summary} 414, {:test 1, :pass 11, :fail 1, :error 0, :type :summary} 586}
```

Running with a simple sequential map produced no errors.

Wrapping the second test in `tu/with-temporary-setting-values [metabot-settings/enum-cardinality-threshold 10]`
reduced the error count dramatically (in the teens for 1000 samples), but still wasn't bulletproof.
I'm guessing the two `testing` directives in the test are run in parallel and the setting is not thread safe.

By adding the explicit threshold to the test and breaking it out into a standalone test the
error count drops dramatically.

```
(frequencies
  (pmap
    (fn [_]
      (clojure.test/run-test inner-query-name-collisions-with-joins-test))
    (range 1000)))
;=> {{:test 1, :pass 6, :fail 0, :error 0, :type :summary} 998, {:test 1, :pass 5, :fail 1, :error 0, :type :summary} 2}
```

I'm still not sure why this fails (only twice in 1000 runs), but apparently something about
this operation is not thread safe. However, given the additional isolation added by this PR
we go from a 60ish percent failure rate down to a 0.2% failure rate locally.

Hopefully this is adequate enough to prevent any substantial level of future flakes.
2023-11-10 15:35:33 -07:00
Jerry Huang
f2823e4c4b Add subscription-send and alert-send events (#35559) 2023-11-10 14:35:08 -08:00
Ryan Laurie
f685f1c17d Update Babel and MySQL2 Dependencies (#35602) 2023-11-10 14:30:44 -07:00
Jeff Bruemmer
65dc7663a2 links (#35603) 2023-11-10 16:26:17 -05:00
John Swanson
e825ef2c9f Audit log CRUD permission failures (#35391)
* Audit log CRUD permission failures

When we run `metabase.api.common/*-check` functions like `update-check` or `create-check`, publish an event when the
check fails, along with enough context that, on the other side, the audit log handler can record the relevant event.

Note that we won't fire events for a `read-check` failure. Eventually we will and these events will be handled by the "read log" instead of the audit log.

If we throw an event that isn't derived from `:metabase/event` it will throw an exception. That `derive` no longer belongs in the
audit log code, and until we have the view log there's not really a logical place to put it. For now, I just commented
out the `publish-event!` call, with the assumption that the view log is coming very soon. Otherwise we can just delete
it and add it back in when it's needed.

Some tangentially related required changes here to make this work include:

* allow `audit-log/model-name` to work with RootCollections

`(t2/model root-collection)` returns a Class rather than a keyword - `name` doesn't work here, so we'll use
`getSimpleName` instead.

* add a default model-details clause for dashboards

If the event-type is not one that we've explicitly delineated, just return an empty map for the model details.

* Migration to fit longer model names in `activity.model`

The `NativeQuerySnippet` or `PermissionsGroupMembership` models, for example, were too long to fit in `VARCHAR(16)`.
I'm doubling the length of this column to fit the longest model I see, with a little extra room.
2023-11-10 21:14:49 +00:00
Uladzimir Havenchyk
cde7b48cf3 Add don't bin option for temporal bucketing (#35549) 2023-11-10 20:22:50 +00:00
Nemanja Glumac
aa2c4ec1fb Further optimize static-viz check for the backend workflow (#35580)
Follow up after #34209
2023-11-10 21:02:13 +01:00
Noah Moss
6845d6a9a5 Speed up audit DB tests (#35522)
Co-authored-by: bryan <bryan.maass@gmail.com>
2023-11-10 20:00:45 +00:00
Nemanja Glumac
77f0b76630 Refine default CI triggers (#35617) 2023-11-10 21:00:19 +01:00
Ryan Laurie
e66d80d978 Give cljs tests 15 min (#35608) 2023-11-10 18:04:38 +00:00
Jesse Devaney
8a21ceae12 fix custom label line height not matching radio height (#35568) 2023-11-10 12:31:50 -05:00
John Swanson
263800c10c Skip :event/{card,dashboard}-update on pin/unpin (#35066)
When a card or dashboard is pinned, the entity itself is not changing, so let's not send the `:event/card-update` or
`:event/dashboard-update` events in these cases.
2023-11-10 08:48:26 -08:00
Nicolò Pretto
584eddc0ac [Move card to tab] Milestone 4 - polishment (#35240)
* empty commit to allow draft pr

* dismiss undo notifications when saving a dashboard (#35243)

* dismiss undo notifications when saving a dashboard

* e2e test

* Update e2e/test/scenarios/dashboard/tabs.cy.spec.js

Co-authored-by: Oisin Coveney <oisin@metabase.com>

---------

Co-authored-by: Oisin Coveney <oisin@metabase.com>

* fix z-index issues

* Update frontend/src/metabase/dashboard/components/DashCard/DashCard.styled.tsx

Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>

* renames as per feedback on PR

* left align dashcard actions on small cards (#35327)

* update emotion to support container queries

* left align actions with container query

* use rems

* fix restore z index between resize handle and dashcard actions

* refactor: remove renderDashCardActions in favor of a component (#35366)

* move DashboardCardActionsPanel inside DashCardActionButtons

* move isDashCardTabMenuOpen state to DashCardACtionsButtons

* refactor: remove renderDashCardActions

* refactor: renamed to DashCardActionsPanel

* refactor import type MouseEvent

* refactor DashCardActionButtons folder -> DashCardActionsPanel

* refactor: move DashCardTabMenu to DashCardActionsPanel

* refactor: move buttons to their own subfolder so that it's clear they're sub-components of the actions panel

* feat: use name of card in undo toast message (#35378)

* feat: use name of card in undo toast message

* feat/refactor: truncate via css

* denis' patch to use Ellipsified

* make toast don't take up all space + add max width

* Update frontend/src/metabase/containers/UndoListing.styled.tsx

Co-authored-by: Mahatthana (Kelvin) Nomsawadi <me@bboykelvin.dev>

---------

Co-authored-by: Mahatthana (Kelvin) Nomsawadi <me@bboykelvin.dev>

---------

Co-authored-by: Oisin Coveney <oisin@metabase.com>
Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>
Co-authored-by: Mahatthana (Kelvin) Nomsawadi <me@bboykelvin.dev>
2023-11-10 16:15:57 +01:00
Cal Herries
6da08bfae3 Add migration to remove FK target fields for previously inactive fields (#35531) 2023-11-10 16:52:09 +02:00
Nemanja Glumac
704d45bf66 Fix newly created E2E CSV flakes (#35579)
* Fix newly created E2E CSV flakes

* Do not use `.within()` on multiple elements

* Always isolate the correct status element before assertions
2023-11-10 14:45:44 +00:00
Alexander Solovyov
35718bb71c Fix breaking change in master (#35593)
`load-metabase!` now has an exclamation mark in the name
Fixes a breaking change in master caused by merging #35539 before #35530.
2023-11-10 15:38:57 +01:00
Alexander Solovyov
3145c43420 remove dashcards and tabs not in serialization data when loading (#35530)
Cards are not touched, just DashboardCards and DashboardTabs are synchronized with loaded data
2023-11-10 17:09:03 +03:00
Cal Herries
ca92754816 Rename unparallelizable serdes functions to have exclamation marks (#35539) 2023-11-10 16:05:08 +02:00
Kamil Mielnik
109c53586b Partial e2e tests - Visual glitches when joining same table and field multiple times (#35411)
* Add a repro for the basic case

* Add more assertions

* Remove external tag

* Improve test name

* Add a test case for visited questions

* Fix initial state for lhc display name for visited questions

* Refactor duplication

* Update test names

* Skip test that still fails

* Revert "Fix initial state for lhc display name for visited questions"

This reverts commit 36aca5469d.

* Use getNotebookStep

* Skip test until issue is fixed
2023-11-10 12:21:36 +00:00
Mahatthana (Kelvin) Nomsawadi
304c42fdaf Hide personal collections and items when configuring click behavior (#35317)
* Refactor to prepare for new requirement

* Hide personal collections and items when configuring click behavior

* Remove default export

* Add tests

* Fix type error

* Review: Simplify test util

* Update frontend/src/metabase-lib/parameters/utils/click-behavior.ts

Co-authored-by: Denis Berezin <denis.berezin@metabase.com>

* Consolidate collection util functions

* Reuse an existing function

* Fix conflict from rebasing off master

---------

Co-authored-by: Denis Berezin <denis.berezin@metabase.com>
2023-11-10 11:18:29 +00:00
Ngoc Khuat
dfbda33a11 Includes dbms_version for database_connection_successful snoplow event (#35403) 2023-11-10 10:51:33 +00:00
Ngoc Khuat
cd97591335 Daily task to delete old inactive tables (#35443) 2023-11-10 10:02:59 +00:00
Kamil Mielnik
04fb9a207e Editing existing click behavior after target dashboard tab has been removed (#35526)
* Display error instead of auto-fixing non-exiting tab id

* Make deleted target dashboard tab an invalid click behavior state

* Fix saving click behavior

* Add a test for showing error when the tab has been removed

* Add auto-fix for deleted tab when we don't render tabs dropdown

* Update test names
2023-11-10 16:57:51 +07:00
Kamil Mielnik
185a9427e8 Respect "enable nested queries" setting and database's "nested queries" feature (#35490)
* Do not show new question link when database does not support nested queries

* Do not show new question link when nested queries are disabled

* Add a unit test for disabled nested queries

* Add a unit test for databases without nested queries support
2023-11-10 16:56:52 +07:00
Cal Herries
878290b490 Deprecate PUT /api/dashboard/:id/cards endpoint (#35499) 2023-11-10 08:30:35 +00:00
Nemanja Glumac
d756bd3647 Refine CI triggers for i18n workflow (#35533) 2023-11-10 09:17:37 +01:00
Alexander Solovyov
55ed5e0f4e Stable order of serialization keys (#35485)
keys in serialization are be sorted by historical order first and alphabetically if they are not mentioned
2023-11-10 09:55:28 +03:00
Nemanja Glumac
4d91483b9a Refine CI triggers for e2e workflow (#34892) 2023-11-10 06:47:19 +00:00
Cam Saul
b83e72bd0d No more schema= (#35442) 2023-11-10 02:19:05 +00:00
Cam Saul
d140d676bf Generate sane SQL for a DATE[TIME] expression = DATE literal filter (#35523) 2023-11-09 17:51:14 -08:00
Noah Moss
62c72137a3 Handle audit v2 downgrade case (#35386)
Co-authored-by: Bryan Maass <bryan.maass@gmail.com>
2023-11-09 17:51:44 -06:00
Cam Saul
aa8351f161 Update some pivot QP code to use MLv2 (bug fix) (#35441) 2023-11-09 14:42:20 -08:00
Ryan Laurie
d204abe5a4 Make Pre-Release checks trigger on workflow_dispatch (#35185) 2023-11-09 21:42:32 +00:00
Nemanja Glumac
44a7e597f5 Split E2E visualizations group (#35423)
* Split visualizations E2E group

* Rename visualizations to `visualizations-charts`

* Update E2E matrix
2023-11-09 20:52:19 +01:00
Mark Bastian
8e9f0289fc Fix slow back button x-ray flakes (#35387)
* Attempting to fix x-ray back timeout issues with smaller card count

It looks like the flakes on https://www.deploysentinel.com/ci/analysis?tab=flake for "dashboard back navigation should display a back to the dashboard button in table x-ray dashboards" and "dashboard back navigation should display a back to the dashboard button in model x-ray dashboards" frequently fail at the `cy.wait("@dataset")` stage. I'm guessing this is because the dashboard code is so slow. This PR limits the number of cards produce to `MAX_CARDS` (5) in order to speed up card generation and help with the flakes.

* Adding a timeout to slow x-rays for back button. Hopefully, the small number of max cards makes this unnecessary, though.

* Bumped timeout to 15s instead of 5s. Looks like it was already 5. Again, hopefully the change to minimized the number of generated cards will fix this flake and not take as long.

* Fixing the `show` query param for x-rays

`show` in `core` can be either `:all` or an integer. However, the API layer only exposes the `:all` or `nil` options. This PR exposes the integer path as well.

Note that this is incremental to get flakes working faster. I'll still need to add API tests for this.

* Adding API unit tests to `metabase.api.automagic-dashboards-test` for `show` cases.

* Fixed deftest name to be unique.

* Fixing reference to new card in flaky test
2023-11-09 19:50:02 +00:00
Noah Moss
869ec6951b Add new indexes for audit v2 (#35506)
Co-authored-by: Luiz Arakaki <luiz.arakaki@metabase.com>
2023-11-09 13:56:27 -05:00
Braden Shepherdson
1b4d908faf [MLv2] Test if a join is removed a custom column based on it is too (#35504)
Adding unit tests for bug bash. Closes #14775.
2023-11-09 13:38:38 -05:00
Cam Saul
1852be04bb Test for #11210 (#35520) 2023-11-09 18:23:53 +00:00
Luiz Arakaki
866c34e825 reassign dashboard filters (#35537) 2023-11-09 18:14:02 +00:00
Case Nelson
b774b1fdaf [MLv2] Test for 27323 (#35515)
* [MLv2] Test for 27323

Fixes #27323

* Address PR review
2023-11-09 18:02:21 +00:00
Case Nelson
9f8f08af9c [MLv2] Test for #28609 (#35517)
Fixes #28609
2023-11-09 18:00:46 +00:00
Jesse Devaney
715585d61f Separate SMTP Connection Setup from Other Email Settings (#35177)
* separate SMTP connection settings from other email settings

* update tests based on now setup flow

- some tests were removed as the behaviors of the app have changed
- some tests were updated to validate the new SMTP connection card and setup process

* improve tests

* replace styled component with mantine flex

* fix type errors

* refactor breadcrumbs to use native solution in SettingsBatchForm

* only show breadcrumbs if email is already configured

* catch and handle error if form submission fails

* fix tests

* remove dead code

* fix test failure and consolidate similar E2E tests

* update unit tests to account for new behavior

* fix type error - remove unused dispatch prop

* update unit tests to account for redirect behavior

* move dispatch to useEffect and convert file to typescript

* fix button state on save error

* add unit tests for hiding SMTP configuration when cloud-hosted
2023-11-09 12:36:45 -05:00
Cal Herries
657f43dc01 Fix possibility of e2e-update-cards-only-test failure (#35542) 2023-11-09 16:44:18 +00:00
Cam Saul
f4c6ea5afd Test for #18769 (#35521) 2023-11-09 10:40:39 -05:00
Ryan Laurie
28b4e27057 Optimistic Database Sync in e2e tests (#35498)
* enable actions on databases on a per-test basis

* debug logging

* try some stuff

* optimistic sync

* put some stuff back

* revert formatting changes

* revert debug changes [ci skip]
2023-11-09 16:09:42 +01:00
Nick Fitzpatrick
0865c2142b Adding Stacked Checkbox component (#35448)
* Adding Stacked Checkbox component

* Switching to checkbox variant

* PR Feedback

* Storybook cleanup

* including description
2023-11-09 09:38:59 -04:00
Cal Herries
7e2e24d30a Remove a retired field's FK target references during sync (#35496) 2023-11-09 13:56:51 +02:00
Nemanja Glumac
abaf5e2d04 Refine CI triggers for snowplow workflow (#35527)
[ci skip]
2023-11-09 12:02:53 +01:00
Ryan Laurie
e67f05b578 Milestone Reminder Github Action (#35322) 2023-11-08 23:22:59 +00:00
Braden Shepherdson
210d7dc166 [MLv2] Refactor display-info; add caching (#35418)
This greatly improves the performance of `ML.display_info`, which is
taking a lot of the cumulative time in the various MLv2 slowdown bugs
recently: #35205, #25296.
2023-11-08 23:15:24 +00:00
Case Nelson
2d3b86d36b [MLv2] Tests #12625 removing sorted aggregations (#35507)
Fixes #12625
2023-11-08 23:12:55 +00:00
Case Nelson
cf59ad4f49 [MLv2] Test for #31384 available aggregators updates from join (#35512)
Fixes #31384
2023-11-08 15:35:05 -07:00
Noah Moss
1b1b6194d9 Fix flake in JWT test (#35510) 2023-11-08 22:28:42 +00:00
Jesse Devaney
b32cf74690 Add opt-in CC option to Admin Email Setting (#35478)
* Add opt-in option to CC recipients in admin email settings

* fix type errors

* add E2E tests for CC/BCC email option
2023-11-08 16:57:40 -05:00
Jesse Devaney
6e530e281c Create Admin Setting for MB_SESSION_COOKIE_SAMESITE (#35392)
* initial frontend commit

* add authorized origins check with note

* update interactive embedding unit test

* add samesite cookie to embedding E2E

* add unit tests for conditional note display

* fix types

* fix translations

* use alert instead of custom component
2023-11-08 16:30:11 -05:00
Luis Paolini
63f43a6e20 Update running-the-metabase-jar-file.md (#34994) 2023-11-08 16:06:00 -05:00
Noah Moss
8013cc29ee Copy activity table data to audit_log (#35233) 2023-11-08 12:53:28 -05:00
Mark Bastian
8ba0ef1a0f Fixing dropdown filter value GET #32126 (#35439)
* Fixing dropdown filter value GET #32126

When GET "/:id/params/:param-key/values" is invoked, the endpoint looks
for valid values to populate for the filter dropdowns using the resolved
field-ids for the underlying item in the dashboard. In some cases, such
as nested queries, the field is not referenced by id, but using the field name.

This PR adds a branch that will look for fields by field ref
(e.g. `[:field "SOURCE" {:base-type :type/Text}]`) if the field cannot be
resolved by id.

Fixes #32126

* lint fix
2023-11-08 17:48:48 +00:00
Noah Moss
e729597478 [AuditV2] Feature Branch 2 (#35434)
Co-authored-by: Ryan Laurie <iethree@gmail.com>
Co-authored-by: Luiz Arakaki <luiz.arakaki@metabase.com>
Co-authored-by: bryan <bryan.maass@gmail.com>
Co-authored-by: Noah Moss <32746338+noahmoss@users.noreply.github.com>
Co-authored-by: Ryan Laurie <30528226+iethree@users.noreply.github.com>
Co-authored-by: Nick Fitzpatrick <nick@metabase.com>
Co-authored-by: Nick Fitzpatrick <nickfitz.582@gmail.com>
Co-authored-by: Noah Moss <noahbmoss@gmail.com>
Co-authored-by: Case Nelson <case@metabase.com>
Co-authored-by: Jerry Huang <jhuang37050@gmail.com>
Co-authored-by: Bryan Maass <bryan.maass@gmail.com>
Co-authored-by: Jerry Huang <34140255+qwef@users.noreply.github.com>
Co-authored-by: adam-james <21064735+adam-james-v@users.noreply.github.com>
Co-authored-by: Adam James <adam.vermeer2@gmail.com>
Co-authored-by: John Swanson <john.swanson@metabase.com>
2023-11-08 11:34:43 -05:00
Braden Shepherdson
0675594592 [serdes] Bring back the big comments on the serdes process (#35468) 2023-11-08 10:53:24 -05:00
Luis Paolini
cac52d8452 update samesite docs (#35473)
* update samesite docs

* Update docs/configuring-metabase/environment-variables.md

Co-authored-by: Jeff Bruemmer <jeff.bruemmer@gmail.com>

---------

Co-authored-by: Jeff Bruemmer <jeff.bruemmer@gmail.com>
2023-11-08 12:20:38 -03:00
Jeff Bruemmer
d0796f348d docs - embedding updates (#35389) 2023-11-08 09:54:19 -05:00
Luis Paolini
8faa724c03 Update google-and-ldap.md (#35390)
Remove the recommendation for keeping the user/pass enabled
2023-11-08 11:51:37 -03:00
Cal Herries
385fdfe208 Use PUT /api/dashboard/:id to update dashcards and tabs (#35406) 2023-11-08 14:45:11 +00:00
Nemanja Glumac
f1595030ad Unskip repro for #12625 (#35486)
* Update repro for #12625

* Unskip repro for #12625

[ci skip]
2023-11-08 13:57:09 +01:00
Nemanja Glumac
d32c9e97d7 Unskip repro for #14775 (#35484)
* Adjust the repro for #14775

* Unskip repro 14775

[ci skip]
2023-11-08 12:41:50 +01:00
Serge Klochkov
e0ebd085cc Add align-temporal-unit-with-param-type multimethod (#34873)
* Add ->temporal-unit multimethod

* Change the method name and add a test

* Fix substitution.clj indentation
2023-11-08 10:34:30 +01:00
Luis Paolini
45809fdc2d How to upgrade beanstalk (#34715)
* How to upgrade beanstalk

For people that want to stay in beanstalk, give them an option to upgrade

* Update docs/installation-and-operation/running-metabase-on-elastic-beanstalk.md

Co-authored-by: Jeff Bruemmer <jeff.bruemmer@gmail.com>

---------

Co-authored-by: Jeff Bruemmer <jeff.bruemmer@gmail.com>
2023-11-08 10:33:26 +01:00
Uladzimir Havenchyk
317cf33ac5 Add type safety to jest config (#35210) 2023-11-08 12:26:22 +03:00
Ryan Laurie
d35c779976 Downgrade Cypress to 12.0.2 🤞 (#35471) 2023-11-07 16:58:43 -07:00
Braden Shepherdson
df75a500a9 Add :marginalia/one alias to generate docs for a single file (#35458) 2023-11-07 21:28:12 +00:00
Cam Saul
7c854d29be [MLv2] Implement zoom-in.binning drill thru (#34935) 2023-11-07 20:41:52 +00:00
Jeff Bruemmer
4274bcc223 update key (#35462) 2023-11-07 15:21:25 -05:00
Ryan Kienstra
fcfa572f02 Run clj-kondo on bin/ files (#34268)
Co-authored-by: Cam Saul <github@camsaul.com>
2023-11-07 11:50:22 -08:00
Mahatthana (Kelvin) Nomsawadi
25728dcca6 Hide elements in create new dashboard modal (#35277)
* Hide public collections in create a new dashboard modal

* Hide "+ New collection option" in FormCollectionPicker

* Hide public collections in create a new collection modal

* Add unit tests

* Update frontend/src/metabase/containers/AddToDashSelectDashModal/AddToDashSelectDashModal.unit.spec.tsx

Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>

* Review: Make test name more explicit to avoid confusion

* Review: Removed unused `async`

* Review: Move more common task to `beforeEach`

---------

Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>
2023-11-07 17:20:09 +00:00
Nick Fitzpatrick
4906c90ac7 impoving spacing, centering checkbox labels (#35381)
* impoving spacing, centering checkbox labels

* Adjusting label and icon spacing

* removing columns label
2023-11-07 13:18:33 -04:00
Cal Herries
c348b397d1 Only create one revision per request to PUT /api/dashboard/:id (#35413) 2023-11-07 18:13:27 +02:00
Jeff Bruemmer
698ea5579a update images, add mention of columns editing (#35433) 2023-11-07 11:09:10 -05:00
Ngoc Khuat
f0c5dd2793 Update search api documentation to includes available filters (#35405) 2023-11-07 22:12:26 +07:00
Kamil Mielnik
e8222896e0 Allow users to link dashcard to dashboard tab in Click Behavior sidebar (#35311)
* Rename click-behavior.unit.spec.js to click-behavior.unit.spec.ts

* Rename click-behavior.js to click-behavior.ts

* Fix typo

* Type formatDateForParameterType

* Move unit tests close to the file they're testing

* Add type guards for ActionClickBehavior types

* Replace isValidImplicitActionClickBehavior with an actual type guard

* Type notRelativeDateOrRange

* Add missing argument to formatDateForParameterType call

* Type baseTypeFilterForParameterType

* Remove redundant attribute

* Remove unused isAction

* Mark arguments as optional

* Inline getTargetsWithSourceFilters, remove getTargetsForAction

* Type clickBehaviorIsValid

* Add type guards

* Revert "Add type guards"

This reverts commit 16492d1cbf.

* Type getDataFromClicked
- update unit tests for userAttributes

* Make formatValueForLinkTemplate type-safe

* Properly define SourceFilters, move types to top of the file

* Remove redundant condition

* Type getTargetsForDashboard

* Introduce ClickBehaviorParameterSource & ClickBehaviorParameterTarget

* Fix Parameter['type']

* Refactor getTargetForQueryParams & getParameter to TS

* Improve typing

* Type formatSourceForTarget

* Migrate metabase-lib/types/constants to TS

* Improve getTargetsForQuestion typing

* Introduce ClickBehaviorVariableTarget

* Migrate getTargetsForQuestion to TS

* Fix typing errors

* Fix typing in tests

* Fix typing in tests

* Trick GH into giving a nice diff

* Revert "Trick GH into giving a nice diff"

This reverts commit 2adfc1d723.

* Add an explanatory comment

* Remove redundant checks

* Rename isRecord to isObject

* Remove redundant check

* Allow null value for TemplateTag['default']

* Fix tests

* Remove redundant if

* Fix user.login_attributes type

* Connect dashboard tabs in LinkedEntityPicker

* Split EntityCustomDestinationClickBehavior into DashboardCustomDestinationClickBehavior & QuestionCustomDestinationClickBehavior

* Add tabId prop to DashboardCustomDestinationClickBehavior

* Rename component to match the filename

* Connect a dropdown to change dashboard tab

* Remove controversial effect

* Make the click work with tabId

* Reuse ArbitraryCustomDestinationClickBehavior["linkType"]

* Reset tabId when changing dashboard targetId

* Avoid casting undefined to string

* Bring back the effect to set the tabIOd to match the comment in DashboardCustomDestinationClickBehavior['tabId']

* Rename isDash to isDashboard

* Add migration for deleted tab

* Add assertions for single-tab dashboards

* Add a test for setting dashboard tab

* Add assertions for click behavior after removing target tab

* Add a test for tables

* Use mantine instead of styled components

* Rename parametersQueryParams to baseQueryParams

* Remove commented-out code

* Format code

* Add assertion that tab is removed from dropdown

* Add a test case
2023-11-07 16:49:10 +02:00
Mahatthana (Kelvin) Nomsawadi
716dca1f5d Handle search in dashboard and question picker (#35215)
* Convert `QuestionList` to TypeScript

* Hide questions in personal collections from question picker

When adding questions to a dashboard in a public collection.

* Organize tests into distinct describe blocks

* Add unit tests

* Hide dashboards in public collections from dashboard picker

* Add unit tests

* Remove commented out code

* Correct test names

* Fix failed E2E

* Review: Use auto-generated ID to avoid manual ID incrementation

* Review: Use explicit assertions

* Review: Correct result type from entity loader
2023-11-07 14:40:11 +00:00
Kamil Mielnik
26c7c21e22 Fix - Text weirdly wrapped in column dropdown in Polish language (#35349)
* Introduce Content styled component and refactor its classnames to css

* Fix label text wrapping

* Use Ellipsified on TriggerButton's content

* Fix extra content taking too much space

* Fix typing

* Allow word wrapping in Content

* Fix overflow

* Revert redundant change

* Use Ellipsified directly
2023-11-07 21:25:28 +07:00
Oisin Coveney
2f716b0f14 Add Data Test ID for sidebar (#35445) 2023-11-07 16:14:39 +02:00
Nemanja Glumac
9ca96812f5 Fix E2E "move dashcards to tabs" flake (#35427)
* Fix E2E "move dashbards to tabs" flake

[ci skip]

* Use hover to trigger the menu

[ci skip]

Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>

* Force-click is not needed anymore

[ci skip]

---------

Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>
2023-11-07 11:32:59 +01:00
Oisin Coveney
d9f1cd16b5 Use recipients API instead of useUserListQuery (#35058) 2023-11-07 11:58:41 +02:00
Case Nelson
f381285426 [MLv2] Format brush filter display names (#35253)
* [MLv2] Format brush filter display names

Also better localize and handle any passed in offset date times.

* Update shared/src/metabase/shared/util/internal/time.clj

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>

* Update shared/src/metabase/shared/util/internal/time.clj

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>

* Address PR feedback, shared.util.time requires public-settings so have to require common directly

---------

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>
2023-11-07 09:24:45 +00:00
Cam Saul
e8dc6bff40 QP enterprise middleware should use defenterprise (#35130) 2023-11-06 14:18:21 -08:00
Jeff Bruemmer
90564ad004 docs - x-ray and action notes (#35334) 2023-11-06 12:36:21 -05:00
Case Nelson
1ce521fe89 [MLv2] Add card-or-table-id (#35265)
* [MLv2] Add card-or-table-id

Fixes #35257

* Address pr comments, rename to legacy-card-or-table-id
2023-11-06 10:15:52 -07:00
Braden Shepherdson
6d187112f8 [MLv2] Make find-matching-column correctly match implicit joins (#35168)
Fixes #35152
2023-11-06 16:04:29 +00:00
Nemanja Glumac
370c36dbc6 Improve stress-test workflow by adding grep functionality (#35415)
* Improve stress-test workflow by adding grep functionality

This change allows one to filter a specific test, or a set of tests to run
withing a single spec, by using a Cypress `grep` functionality.

The documentation and examples are here:
https://github.com/cypress-io/cypress/tree/develop/npm/grep

* Include documentation link in a comment

[ci skip]

* Update dev documentation

[ci skip]
2023-11-06 16:05:18 +01:00
Uladzimir Havenchyk
9256650d92 Drop useless tests and update comment 2023-11-06 16:32:34 +03:00
Uladzimir Havenchyk
9a52f4883c [Dashboard] Simplify filters stikiness calculation 2023-11-06 16:32:34 +03:00
Nemanja Glumac
97b05d36e2 Fix E2E failure due to the DST (#35412) 2023-11-06 12:55:00 +01:00
Ngoc Khuat
70fd1fb6f2 fix flaky relative time test filter-datetime-by-date-in-timezone-relative-to-days-since-test (#35407) 2023-11-06 17:21:25 +07:00
Lena
41bda6c99e Update teams in team.json (Nov 2023 reorg) (#35397)
[ci skip]
2023-11-06 09:36:27 +01:00
Cal Herries
031eeee682 BE prep for using PUT /api/dashboard/:id to update dashcards and tabs (#35223) 2023-11-06 09:05:27 +02:00
Mahatthana (Kelvin) Nomsawadi
f339a246af Correct collection item key (#35372) 2023-11-06 05:37:59 +00:00
metamben
e6b66c5655 Disable auto-commit (enable transactions) for read-only connections (#35268) 2023-11-04 21:21:37 +03:00
Mark Bastian
d71805e46b Moving x-ray checks to backend for 15655 to reduce flakes (#35380)
* Moving x-ray checks to backend for 15655 to reduce flakes

The following x-ray e2e tests are top contributors to x-ray flakes at 6.94% and 6.62%, respectively:
- "X-RAY" should work on a nested question made from base native question (metabase#15655)
- "COMPARE TO THE REST" should work on a nested question made from base native question (metabase#15655)

This change moves the x-ray dashboard generation aspects test load to a unit test and just checks that the insight buttons are present and clickable.

Note that there is still some scenario creation type code in the fixture that could potentially be simplified with some FE help.

* Inlining question creation to fix flakes for the 15655 fix

Previously, a multistage process was used to create the question on top of the native question being tested here.

Now, we just use `cy.createQuestion` directly.
2023-11-03 14:36:19 -06:00
Noah Moss
54071249ce Bump SAML to 2.2.4 (#35376) 2023-11-03 20:08:59 +00:00
Mark Bastian
5f02f32332 Fixing x-rays with custom columns (#16680) (#35336)
* Fixing x-rays with custom columns (#16680)

Queries with custom columns were broken for two reasons:
- When names were computed for display, the humanization code expected fields
- The generated dashcard queries did not preserve the base query's custom expression definitions

For the first point, the code in `metabase.automagic-dashboards.names` was generalized for both fields and expressions.

For the second, the logic that was formerly `preserve-joins` in `metabase.automagic-dashboards.core` has been generalized to `preserve-entity-element` and applied to both joins and expressions.

* Renamed innner `splice-joins` to `splice-elements`

* Updating `preserve-entity-element` to retain any existing element that is already present in the old query.

* Reinstated inline tru strings such as "is less than" so they can be internationalized.

* Added e2e test

* Adding .click() to e2e test.
2023-11-03 17:54:13 +00:00
Oisin Coveney
d2ecd17b97 Snowplow: Add new event for search results filtered (#35146) 2023-11-03 17:59:00 +02:00
Nick Fitzpatrick
e5bc88b80f Increasing scroll count for flakey table columns test (#35329)
* increasing scroll count

* another test
2023-11-03 10:25:13 -03:00
Mahatthana (Kelvin) Nomsawadi
18fb5a060f Fix calling API more than necessary (#35346)
* Fix calling API more than necessary

* Correctly fix the problem

* Add a test to confirm that it only query card once

* Added an issue in the test
2023-11-03 13:15:27 +00:00
Oisin Coveney
fb08407595 Replace getByLabelText with getIcon (#35350) 2023-11-03 12:56:24 +02:00
Ibe Dwi
6d2947e65f Fix - Custom expression that has a name consisting only of whitespace breaks the question (#33855)
* fix: prevent space in the expression name

* feat: add test with typing or pasting any characters with spaces

* chore: simplify onChange function and space character check

* test: check onChangeExpression call

* fix: check expression name is consist of string only

* fix: simplify function and add test cases

* add tests and update comments
2023-11-03 17:05:34 +07:00
Oisin Coveney
d571c9603f Fix missing indexed entity x-ray button (#35283) 2023-11-03 11:33:52 +02:00
Alexander Polyankin
c606541d27 Mantine number input fix (#35318) 2023-11-02 16:54:43 +00:00
Kamil Mielnik
9839606a1b Convert click-behavior utils to TypeScript (#35211)
* Rename click-behavior.unit.spec.js to click-behavior.unit.spec.ts

* Rename click-behavior.js to click-behavior.ts

* Fix typo

* Type formatDateForParameterType

* Move unit tests close to the file they're testing

* Add type guards for ActionClickBehavior types

* Replace isValidImplicitActionClickBehavior with an actual type guard

* Type notRelativeDateOrRange

* Add missing argument to formatDateForParameterType call

* Type baseTypeFilterForParameterType

* Remove redundant attribute

* Remove unused isAction

* Mark arguments as optional

* Inline getTargetsWithSourceFilters, remove getTargetsForAction

* Type clickBehaviorIsValid

* Add type guards

* Revert "Add type guards"

This reverts commit 16492d1cbf.

* Type getDataFromClicked
- update unit tests for userAttributes

* Make formatValueForLinkTemplate type-safe

* Properly define SourceFilters, move types to top of the file

* Remove redundant condition

* Type getTargetsForDashboard

* Introduce ClickBehaviorParameterSource & ClickBehaviorParameterTarget

* Fix Parameter['type']

* Refactor getTargetForQueryParams & getParameter to TS

* Improve typing

* Type formatSourceForTarget

* Migrate metabase-lib/types/constants to TS

* Improve getTargetsForQuestion typing

* Introduce ClickBehaviorVariableTarget

* Migrate getTargetsForQuestion to TS

* Fix typing errors

* Fix typing in tests

* Fix typing in tests

* Trick GH into giving a nice diff

* Revert "Trick GH into giving a nice diff"

This reverts commit 2adfc1d723.

* Add an explanatory comment

* Remove redundant checks

* Rename isRecord to isObject

* Remove redundant check

* Allow null value for TemplateTag['default']

* Fix tests

* Remove redundant if

* Fix user.login_attributes type
2023-11-02 23:18:33 +07:00
Nicolò Pretto
51054af194 refactor: remove wild cy.in in test file (#35308) 2023-11-02 16:15:04 +00:00
Ngoc Khuat
7ebfef0d74 Skip archived or deleted cards on revert dashboard (#35236) 2023-11-02 14:53:14 +00:00
Nick Fitzpatrick
c593fecdef Add remove columns panel (#34087)
* temp

* Mostly functional. Still needs cleanup

* cleanup

* hide from table header

* resolving type disputes. adding icon prop to column item

* e2e tests passing

* temp

* branch cleanup

* Fe linter and unit tests

* e2e adjustments

* PR Feedback

* fix unit test

* Hide Viz Settings Buttons in Column Headers in Raw Table Mode (#35114)

* e2e adjustments

* don't show viz settings actions on raw table view

* better prop handling

* Adding e2e test

* updating selector

* more e2e adjustments

---------

Co-authored-by: Nick Fitzpatrick <nickfitz.582@gmail.com>

* e2e updates

* removing comment

---------

Co-authored-by: Ryan Laurie <30528226+iethree@users.noreply.github.com>
2023-11-02 14:00:37 +00:00
Mark Bastian
a5a98a59a6 Preserve join aliases in dashcard queries (fixes 25278 & 32557) (#35267)
* Preserve join aliases in dashcard queries (fixes 25278 & 32557)

In `query-based-analysis` the final stage was to `maybe-enrich-joins`
to add in joins defined in the query being x-rayed into the dashcard
query. In some cases (e.g. cell queries), the trigger to detect this
addition isn't known as the filters are added downstream.

This PR always adds in the join aliases if they are present since
they should be harmless if not needed and you can't know if they are
needed downstream as the code is currently designed.

The tests assert not only that the cards are created, but that the
filter is present and executable (these previously errored out).

* lint fix

* Squashing `splice-in` into `preserve-joins` and adding some better test criteria for `generate-dashboard-pipeline-test`.
2023-11-02 07:40:59 -06:00
Alexander Polyankin
cb2a656f6d Fix click actions perf issue with charts (#35208) 2023-11-02 14:44:54 +02:00
Mahatthana (Kelvin) Nomsawadi
7085ab6307 [milestone 1] Prevent users from adding questions in personal collections to dashboards in public collections (#35135)
* Prepare to consolidate variables

* Hide personal collections in question picker (#35136)

* Only shows public collections when adding questions to a dashboard in
public collection

* Fix dashboard crashing when updating

* Address review

* Fix type error

* Fix conflicts between FE's generated `is_personal` and BE's

* Hide public collections in dashboard picker (#35137)

* Fix typo

* Hides public collections in DashboardPicker

When selecting a dashboard for a question in personal collection

* Fix not calling `useCollectionQuery` unnecessarily

Eventhough in this case it won't make any difference, because
`useCollectionQuery` is cached, we still shouldn't do that.

* Handle recently viewed dashboard

* Refactor default import and fix respective tests

* Refactor moving files closer to their usage

* Hide create a new dashboard option

When the question is in a personal collection and is opening public
collection in the dashboard picker. This only happens when users are
opening the root collection as other public collections won't be
visible.

* Hide items in ItemPicker

When the question is in personal collection and users are opening a
public collection. This only happens when users are opening the root
collection because other public collections are not visible.

* Make the boolean more readable

* Remove unused export

* Fix failed unit tests

* Avoid circular dependency

* Simplify dashboard collection type

* Simplify selectors

* Address review: improves hook name

* Review: Avoid using `ComponentProps`

* Review: Avoid using `useEffect` to call callback

* Fix dashboard picker for private questions not searching

* Review: convert a hook without hook usage to function

* Negate the boolean to positive name to make it easier to read

* Remove unrelated import and matches card to dashboard API types

* Handle moving dashboards to a different collection type (#35138)

* Fix typo

* Hides public collections in DashboardPicker

When selecting a dashboard for a question in personal collection

* Fix not calling `useCollectionQuery` unnecessarily

Eventhough in this case it won't make any difference, because
`useCollectionQuery` is cached, we still shouldn't do that.

* Handle recently viewed dashboard

* Refactor default import and fix respective tests

* Refactor moving files closer to their usage

* Hide create a new dashboard option

When the question is in a personal collection and is opening public
collection in the dashboard picker. This only happens when users are
opening the root collection as other public collections won't be
visible.

* Hide items in ItemPicker

When the question is in personal collection and users are opening a
public collection. This only happens when users are opening the root
collection because other public collections are not visible.

* Make the boolean more readable

* Remove unused export

* Fix failed unit tests

* Avoid circular dependency

* Simplify dashboard collection type

* Simplify selectors

* Address review: improves hook name

* Review: Avoid using `ComponentProps`

* Review: Avoid using `useEffect` to call callback

* Fix dashboard picker for private questions not searching

* Review: convert a hook without hook usage to function

* Negate the boolean to positive name to make it easier to read

* Remove unrelated import and matches card to dashboard API types

* Handle moving dashboards to a different collection type

Move between personal/public collections

* Add dashboard picker tests (#35141)

* Fix removing FE key since BE key is hydrated

* Add some basic tests

* Add more test cases

* Add test #1, and #2

* Modify setup argument to prepare for new tests

* Completed the unit tests

* Removed comments used during development

* Revert test util changes because I don't need it

* Make asserting breadcrumbs easier to read

* remove outdated comment

* Make test code cleaner

* add missing unit tests

* Prepare to add unit tests

* Fix conflict from master

* Add question picker tests (#35142)

* Fix removing FE key since BE key is hydrated

* Add some basic tests

* Add more test cases

* Add test #1, and #2

* Modify setup argument to prepare for new tests

* Completed the unit tests

* Removed comments used during development

* Revert test util changes because I don't need it

* Make asserting breadcrumbs easier to read

* remove outdated comment

* Make test code cleaner

* add missing unit tests

* Prepare to add unit tests

* Fix conflict from master

* Add a unit test file

* Removes PropType error

* Added the rest of the test

* Fix type error from upstream change

* Add E2E tests (#35171)

* Fix removing FE key since BE key is hydrated

* Add some basic tests

* Add more test cases

* Add test #1, and #2

* Modify setup argument to prepare for new tests

* Completed the unit tests

* Removed comments used during development

* Revert test util changes because I don't need it

* Make asserting breadcrumbs easier to read

* remove outdated comment

* Make test code cleaner

* add missing unit tests

* Prepare to add unit tests

* Fix conflict from master

* Add a unit test file

* Removes PropType error

* Added the rest of the test

* Fix type error from upstream change

* Add E2E test for question picker

* Add E2E test for dashboard picker for new questions

* Add E2E test for dashboard picker for existing questions

* Revert util to fix failed tests

* Remove commented code during development

* Fix E2E without modifying a shared util

* Make E2E tests less prone to flakiness
2023-11-02 10:13:55 +00:00
Ngoc Khuat
bd24329bad Optimize revision recording, speed up update dashboard API by 25% 🚀 (#34947) 2023-11-02 02:33:11 +00:00
lbrdnk
b8fa096d56 Correct added version for prettify-native-form (#35270) 2023-11-02 00:44:39 +01:00
Jeff Bruemmer
831776bfc8 docs - model index (#35289) 2023-11-01 15:54:17 -04:00
Nick Fitzpatrick
8e81f12e5d Merging table.columns for dashcards (#35259)
* temp

* Adding unit test
2023-11-01 13:28:09 -03:00
Jeff Bruemmer
b2b9e16849 anchor links (#35264) 2023-11-01 11:41:45 -04:00
Mahatthana (Kelvin) Nomsawadi
968afd218f Fix flaky test because of the current date (#35276) 2023-11-01 13:00:08 +00:00
Ngoc Khuat
901f705546 Fix migration added in #35134 (#35239) 2023-11-01 03:43:35 +00:00
Ngoc Khuat
13e6090682 Search option to return only or exclude items in personal collections (#34887) 2023-11-01 01:59:15 +00:00
Aleksandr Lesnenko
64e894e560 fix x-ray flake: bump timeout, look for a specific card (#35011) 2023-10-31 22:54:52 +00:00
Cam Saul
ad99d370e1 Remove :rff from the Query Processor context map (#35255) 2023-10-31 14:29:31 -07:00
Cam Saul
0e09ac7aaa Implement geo zoom drill (#34822) 2023-10-31 20:15:02 +00:00
Jeff Bruemmer
4500655544 update release list (#35258) 2023-10-31 20:02:53 +00:00
Nick Fitzpatrick
4b828b16dc ensure that column is removed from table.columns when updating question (#34976)
* ensure that column is removed from table.columns when updating question

* PR feedback

* better asserts
2023-10-31 17:02:33 -03:00
John Swanson
baa5d2d4bb Make SESSION_COOKIE_SAMESITE a setting (#35021)
* Make `SESSION_COOKIE_SAMESITE` a setting

Considerations here:

- I didn't want to break the existing behavior, which allows the env var to be case insensitive. This required a bit
of weirdness in the getter/setter - we get the *raw* value, then normalize it to a keyword, then make sure it's one of
the valid options.

- I'm not sure what the best practice is regarding i18n - I just went off the existing code, but I'm not entirely sure
whether I need to also add translations to the `locales/*.po` files, and how I get those translations if
so (err... chatGPT?).

- permissions: I'm not exactly sure how we decide between the `:settings-manager` and `:admin` settings. I went with
`:settings-manager` here.

- I'm not sure whether the frontend has its own definitions of possible values for set-based settings, or if I need to
expose that somehow?

The existing tests were good, easily adapted to the new behavior, and caught the above-mentioned backwards
incompatibility issue with case insensitivity.
2023-10-31 19:01:10 +00:00
Nicolò Pretto
c10a995fde Move card to tab - analytics event (#35151)
* move cards analytics event, closes #35123

* change test to check specific analytics event

* fix version in schema

* update src/metabase/analytics/snowplow.clj with 1-1-2 schema version

* update all dashboard schema events to use version 1-1-2

* refactor: exctracted "DASHBOARD_SCHEMA_VERSION" variable

* refactor: use camelCase for local constant
2023-10-31 18:37:03 +01:00
Emmad Usmani
ad7f3f8040 fix arabic number inconsistency (#34633)
Closes https://github.com/metabase/metabase/issues/34271

### Description

In Arabic locales (`ar` and `ar-sa`), we were displaying Arabic numerals for translated dates, but in the rest of the app we used Western numerals. This PR makes it so that for  dates we also use Western numerals.

Ideally we would have an option for which kind of numeral to use, but it's a sufficient solution to always use Western numerals. Even in Arabic-speaking countries where Arabic numerals are widely used, Western numerals are commonly seen on digital interfaces, so users should not be bothered by it.

### How to verify

1. Go to the Products model.
2. See "Created At" field in English.
3. Go to account settings, change language to "Arabic", then go back to Products model.
4. "Created At" field should now be translated, but using Western numerals.
5. Repeat the same for "Arabic (Saudi Arabia)" locale, and using admin site locale setting.
6. Go back to English, in Products model should see English dates again.

### Demo

https://github.com/metabase/metabase/assets/37751258/826375a2-1f85-4a3d-9abf-fab2e26dd0c0

### Checklist

- [x] Tests have been added/updated to cover changes in this PR
2023-10-31 10:24:10 -07:00
Braden Shepherdson
d0c8536b70 Add dev.fe-helpers to expose the current query to CLJS REPLs (#34997)
Use `(dev.fe-helpers/current-query)` from a CLJS REPL to get the query currently open in the UI.
2023-10-31 16:03:55 +00:00
Cal Herries
bbf3c53677 Refactor: Only use type predicates for type guards (#35207) 2023-10-31 15:53:48 +00:00
Cal Herries
1c69bc2466 Remove GET /api/dashboard endpoint (#35235) 2023-10-31 15:51:23 +00:00
Alexander Solovyov
7c47e04bc7 Return correct values for linked filters using non-equality filters (#34837)
`api.dashboard/chain-filter-constraints` now generates a list of constraints using a filter type defined (like
`:string/!=` or `:number/between`). `chain-filter/filter-clause` down the call chain has no access
to _dashboard_ data, but accepts operators like `:!=` and `:between` readily.
2023-10-31 14:57:02 +03:00
Kamil Mielnik
f550f95a99 Add test coverage for Dashboard Click Behavior - Table & Full app embedding (#35051)
* Reuse addOrUpdateDashboardCard

* Extract 15993 repro

* Extract 16334 repro

* Extract 23137 repro

* Extract 18067 repro

* Remove unused alias

* Add empty test suite for click-behavior

* Add a test for text cards

* Add createHeadingCard helper

* Add a test for heading cards

* Add createActionCard helper
- make text/label params optional in helpers
- remove unused dashboardId param in helpers

* Add a test for an action card

* Format code

* Reuse createActionCard in #32974 repro

* Simplify text code

* Reuse createActionCard, createTextCard & getNextUnsavedDashboardCardId in dashboard back navigation e2e

* Remove unused alias

* Inline 1-line createLinkCard helper

* Add createLinkCard helper

* Add a test for link cards

* Simplify interfaces of helper functions

* Update test title

* Add a test for object detail dashcard

* Remove redundant identifier

* Format code

* Add data-testid to ClickBehaviorSidebar

* Add setup for line chart test

* Test the actual click behavior

* Refactor expectDynamicAnchorClick to expectNextAnchorClick
- get rid of manual mock resetting

* Add test for editing URL filter

* Refactor expectNextAnchorClick to onNextAnchorClick

* Extract URL parameters test as a seprate one

* Fix assertions
- Add escapeCypressCurlyBraces

* Assert user can use dashboard filters and click event columns

* Use cy.get("aside") instead of sidebar functions
- Revert adding data-testid to sidebars

* Use all available parameters in the URL

* Add test for 0 filters

* Extract addFilter

* Add a test for single dashboard filter
- Add constants for magic numbers and values

* Extract OBJECT_DETAIL_CHART

* Use saveDashboard

* Add a test for multiple dashboard filters

* Improve URL assertion

* Improve assertions

* Format code

* Add a test for saved question destination

* Improve assertions

* Consolidate assertions

* Improve assertions

* Add a test for saved question with single parameter passed

* Update JSDoc

* Extract GAUGE_QUESTION_DETAILS & PROGRESS_QUESTION_DETAILS

* Reuse addOrUpdateDashboardCard

* Add a test for saved question with multiple parameters passed

* Extract FILTER_CREATED_AT & FILTER_COUNT

* Do not use elevated privileges

* Rename FILTER_COUNT to FILTER_QUANTITY

* Reuse ORDERS_ID

* Add a test for no saved question permissions

* Create dashboard filters via API

* Add a test

* Add a test for dashboard target

* Add test for 1 and multiple dashboard parameters

* Extract addTextParameter & addTimeParameter

* Improve assertions

* Use different question as target

* Use TARGET_QUESTION instead of SECRET_QUESTION

* Add a test for no dashboard permissions

* Add a test for drill-through menu behavior

* Fix typo

* Destructure location

* Format code, remove console.log

* Use slug instead of name where appropriate

* Add a test case for editing the click behavior

* Update comment

* Commit a dumb change to trigger uberjar rebuild

* Commit a dumb change to trigger uberjar rebuild

* Optimize line chart question
- add limit: 5
- update constants & assertions
- rename LINE_CHART to QUESTION_LINE_CHART
- extract clickLastLineChartPoint as click({ force: true }) is now needed

* Fix click simulation

* Add first test for tables
- extract assertDrillThroughMenuOpen

* - extract clickLastTableCreatedAtCell
- extract clickLastTableCountCell

* Revert "Commit a dumb change to trigger uberjar rebuild"

This reverts commit 27ef0600ad.

* Revert "Commit a dumb change to trigger uberjar rebuild"

This reverts commit a5141eb020.

* Add logs for clarity

* Prepare single test case for all click behavior in table

* Update labels

* Remove year aggregation

* Extract addCustomDashboardDestination

* Extract addSavedQuestionDestination

* Extract addSavedQuestionCreatedAtParameter and addSavedQuestionQuantityParameter

* Fix assertions

* Fix typo

* Extract helpers

* Extract addUrlDestination

* Add more assertions

* Remove redundant indentation

* Reduce indentation, remove redundant assertions

* Chain assertions

* Chain assertions

* Add test for URL click

* Rename test case

* Use parseSpecialCharSequences and get rid of escapeCypressCurlyBraces

* Assert dashboard pathname

* Remove pointless assertions

* Sort tests

* Test reverting to default click behavior

* Handle month column first

* Format code

* Remove redundant assertions

* Move assertions closer to tests

* Add test for dashboard mapping

* Refactor clickTableCell into getTableCell

* Update post-merge conflicts

* Update post-merge conflicts

* Fix test crashing

* Add custom link text assertions

* Add full app embedding tests

* Add a test for URL

* Format code

* Add test for custom question destination

* Add a test for passing question parameters, skip other failing tests

* Add test for updating dashboard filters in embedding

* Add an edge case test

* Add missing attributes

* Add missing assertion

* Format code

* Fix failing test

* Fix failing test

* Update tests to account for disallowing targeting saved questions & dashboards in embedding context
- see https://metaboat.slack.com/archives/C01LQQ2UW03/p1698669573035739
2023-10-31 18:35:35 +07:00
Ngoc Khuat
e9c2d10856 Drop parameter_card.entity_id (#35134) 2023-10-31 08:50:58 +00:00
Ngoc Khuat
c115b411b8 Attempt to fix the flaky hydrate-is-personal-test test (#35203) 2023-10-31 15:25:56 +07:00
shaun
6e5fc510b4 Convert SmartScalar to function component (#35189) 2023-10-31 01:04:21 +00:00
lbrdnk
2a763bfad0 Add percentile capabilities to sqlserver -- do not merge plz (#34783)
* Add percentile capabilities to sqlserver

* Bind sqlserver percentile capabilities to version

* Modify version retrieval

Take advantage of `db` containing `:dbms_version`.

* Extend honeysql with `::approx-percentile-cont`

Use `fn-handler` to extend honeysql instead of a `raw`.
2023-10-30 23:44:07 +01:00
lbrdnk
e6fd2ed212 Add prettify-native-form driver multimethod and refactor mdb.query/format-sql (#34991)
* Add multimethod to pretty-format native form

`driver/prettify-native-form` is added. It is added to `driver`
namespace, even though at the time of writing there is no need
to pretty format nosql, eg. mongo, but this way branchings,
as present in `dataset/native`, or rather `mbql.query/format-sql`
can be avoided.

* Move and update `mdb.query/format-sql`

* Add `prettify-native-form` sql implementation

* Refactor endpoint `/dataset/native`

* Update docstring in `prettify-native-form`

`prettify-native-form`has now docstring explaining its relationship
to `sql.u/format-sql`.

* Update tests

* Refactor references in sql-jdbc code

* Implement `prettify-native-form`in drivers

- sqlserver
- oracle
- bigquery-cloud-sdk

* Update test format-sql references

* Refactor modules use of format-sql

* Correct whitespace

* Correct whitespace for bigquery

* Update test

Make `nonsql-dialects-return-original-query-test` run only for mongo
as it now requires initialized mongo driver - mongo paths on class path.

* Update docstring (review suggestions)

For `prettify-native-form`.

* Update docstring (review suggestion)

For `mdb.query/format-sql`.

* Whitespace (review suggestions)

* Update docs (review suggestions)
2023-10-30 23:43:41 +01:00
Uladzimir Havenchyk
ad9742cd41 Fix field values re-rendering for virtual tables (#35014) 2023-10-30 21:14:03 +00:00
Ryan Laurie
03b5b85858 Automate reordering release tags (#35105) 2023-10-30 13:14:06 -06:00
John Swanson
1a0f2d6587 Clarify stacktraces from malli validation errors (#34712)
* Improve stacktraces for validation errors in malli-instrumented fns

First, when we throw exceptions in `metabase.util.malli/validate`, manually edit the stacktrace to remove those
StackTraceElements that start with `metabase.util.malli.fn`.

Second, instead of rewriting `mu/fn` bodies like so:

```
(let [f& ...] (fn [args] (do-validation) (f& args)))
```

Rewrite them like this:

```
(fn [args] (do-validation) ((fn [args'] ...) args))
```

I wasn't entirely sure that this wouldn't have a negative performance impact, so I tested it with these toy examples:

```
(def option-1
  (let [f (fn [x] (+ x 10))]
    (fn [x]
      (f x))))

(def option-2
  (fn [x]
    ((fn [x'] (+ x 10)) x)))
```

Then evaluated them with Criterium to benchmark.

The first option (our current behavior) looked like this:

```
Evaluation count : 10184236800 in 60 samples of 169737280 calls.
      Execution time sample mean : 4.117003 ns
             Execution time mean : 4.117119 ns
Execution time sample std-deviation : 0.017140 ns
    Execution time std-deviation : 0.017686 ns
   Execution time lower quantile : 4.100963 ns ( 2.5%)
   Execution time upper quantile : 4.149603 ns (97.5%)
                   Overhead used : 1.783065 ns
```

The second option (the new behavior) looked like this:

```
Evaluation count : 13861192260 in 60 samples of 231019871 calls.
      Execution time sample mean : 2.553532 ns
             Execution time mean : 2.553510 ns
Execution time sample std-deviation : 0.019674 ns
    Execution time std-deviation : 0.019824 ns
   Execution time lower quantile : 2.524266 ns ( 2.5%)
   Execution time upper quantile : 2.599826 ns (97.5%)
                   Overhead used : 1.783065 ns
```

So overall the performance does not look to be worse and may actually be slightly better.

In the end, we end up with stacktraces like:

```
(mu/defn bad-input :- :string
  [x :- :int]
  (str x))

(mu/defn bad-output :- :string
  [x :- :int]
  x)

(defn call-bad-input []
  (bad-input "1"))

(call-bad-input)

;;   Invalid input: ["should be an integer"]
;;   {:type :metabase.util.malli.fn/invalid-input,
;;    :error {:schema :int, :value "1", :errors ({:path [], :in [], :schema :int, :value "1"})},
;;    :humanized ["should be an integer"],
;;    :schema :int,
;;    :value "1",
;;    :fn-name playground/bad-input}
;;                      REPL:   19  playground/bad-input
;;                      REPL:   19  playground/bad-input
;;                      REPL:   28  playground/call-bad-input
;;                      REPL:   27  playground/call-bad-input

(defn call-bad-output []
  (bad-output 1))

(call-bad-output)

;;   Invalid output: ["should be a string"]
;;   {:type :metabase.util.malli.fn/invalid-output,
;;    :error {:schema :string, :value 1, :errors ({:path [], :in [], :schema :string, :value 1})},
;;    :humanized ["should be a string"],
;;    :schema :string,
;;    :value 1,
;;    :fn-name playground/bad-output}
;;                      REPL:   23  playground/bad-output
;;                      REPL:   23  playground/bad-output
;;                      REPL:   31  playground/call-bad-output
;;                      REPL:   30  playground/call-bad-output
```
2023-10-30 17:57:46 +00:00
Luis Paolini
ee66016f69 Add a note around embedding approaches (#35197) 2023-10-30 12:50:19 -04:00
Tim Macdonald
502ad0cd26 Add ::offset-datetime support for CSV uploads (#34826)
* varchar_255 -> varchar-255

* Add ::offset-datetime support for CSV uploads

* Use appropriate TZ logic for MySQL

* Now with more whitespace tolerance

* Handle OffsetDateTimes properly in MySQL export

* Make MySQL handle 0-offset datetimes

* Fix OffsetDateTimes for MariaDB uploads
2023-10-30 16:36:55 +00:00
Nicolò Pretto
e416d464df [Move dashcard to another tab] milestone 2 - undo logic (#34961)
* undo logic

* test(e2e): e2e test for undo dashcard to tab movement

* Revert "test(e2e): e2e test for undo dashcard to tab movement"

This reverts commit 050817b895022336753128c27e00c91aa56adea7.

* better e2e test for undoing

* self review new lines

* Apply suggestions from code review

Co-authored-by: Mahatthana (Kelvin) Nomsawadi <me@bboykelvin.dev>

* destTabId -> destinationTabId

* undo moved into thunk

* use checkNotNull

* throw Error -> throw new Error for consistency

* Update e2e/test/scenarios/dashboard/tabs.cy.spec.js

Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>

* change toast to match figma

* ??= operator

* Revert "undo moved into thunk"

This reverts commit 753a7d9357af4bec12616a5e379388d06594a581.

* restored design from figma after revert

* address pr feedback

* fix import after rebase on master

* Revert "address pr feedback"

This reverts commit bea6a27511.

* re-implement part of the feedback

* wip refactor to use thunk and avoid global redux state

* refactor: removed unused code + used selector

---------

Co-authored-by: Mahatthana (Kelvin) Nomsawadi <me@bboykelvin.dev>
Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>
2023-10-30 15:59:38 +00:00
Mark Bastian
cd7f82d457 Fixing cell queries with a temporal unit of year (#35175)
Fixing situations where a cell queries with a temporal unit of year produced nulls in description strings like:

 "A closer look at number of Orders where null of Created At is 2025"

The simple fix was just to add `:year` to the `unit-name` function in
`metabase.automagic-dashboards.names`. In addition to adding a unit
test for this case, several other temporal units were added to the test.

This fixes https://github.com/metabase/metabase/issues/35170.
2023-10-30 15:35:35 +00:00
Braden Shepherdson
e185045943 [MLv2] Add underlying-records drill and top-level-query machinery (#34450)
This adds the `underlying-records` drill, the one that allows you to click an aggregation (possibly with a breakout)
and see the raw table rows with appropriate filtering.

Removes some hacks in how dimensions are handled by drill-thru, and
fixes up some tests accordingly. This changed the format of
`zoom-in.timeseries` drills somewhat.

Also adds `dev.fe-helpers` for inspecting the current query in the CLJS
REPL.

Resolves #34233
2023-10-30 14:28:34 +00:00
Mark Bastian
6ca62be425 Add humanize-filter-value implementations for inequality operators to fix 30350 (#35101)
* I was able to reproduce this in the UI as well as by adding the `">"`, `"<"`, `">="`, and `"<="` clauses to the `cell-title-test` in `metabase.automagic-dashboards.names-test`.

The fix is to add the following `humanize-filter-value` implementations:

```clojure
(defmethod humanize-filter-value :>=
  [root [_ field-reference value]]
  (let [field      (magic.util/field-reference->field root field-reference)
        field-name (field-name field)]
    (if (isa? ((some-fn :effective_type :base_type) field) :type/Temporal)
      (tru "{0} is at least {1}" field-name (humanize-datetime value (:unit field)))
      (tru "{0} is at least {1}" field-name value))))

(defmethod humanize-filter-value :>
  [root [_ field-reference value]]
  (let [field      (magic.util/field-reference->field root field-reference)
        field-name (field-name field)]
    (if (isa? ((some-fn :effective_type :base_type) field) :type/Temporal)
      (tru "{0} is greater than {1}" field-name (humanize-datetime value (:unit field)))
      (tru "{0} is greater than {1}" field-name value))))

(defmethod humanize-filter-value :<=
  [root [_ field-reference value]]
  (let [field      (magic.util/field-reference->field root field-reference)
        field-name (field-name field)]
    (if (isa? ((some-fn :effective_type :base_type) field) :type/Temporal)
      (tru "{0} is at most {1}" field-name (humanize-datetime value (:unit field)))
      (tru "{0} is at most {1}" field-name value))))

(defmethod humanize-filter-value :<
  [root [_ field-reference value]]
  (let [field      (magic.util/field-reference->field root field-reference)
        field-name (field-name field)]
    (if (isa? ((some-fn :effective_type :base_type) field) :type/Temporal)
      (tru "{0} is less than {1}" field-name (humanize-datetime value (:unit field)))
      (tru "{0} is less than {1}" field-name value))))
```

With these in place, both the unit tests pass and the UI reproduction now produces the right result.

* Incorporated suggestions for humanized >= and <= wording for numeric and date values.

Added unit tests for humanized data comparisons.

* Updated comment string

* Added a default case for `humanize-filter-value` of "{0} relates to {1}".

IDK if there's anything better, but for now it's something.
2023-10-30 08:01:26 -06:00
Cal Herries
28c6d70e89 Remove innappropriate type casts and type guards for FieldFilterUiParameter (#35204) 2023-10-30 14:00:27 +00:00
Cal Herries
3513287230 Move metabase/core/utils to metabase/lib (#35095) 2023-10-30 15:56:30 +02:00
Cal Herries
6d7d6c9d2a Migrate Timeline and TimelineEvent "balloons" icons to "star" (#35166) 2023-10-30 15:56:10 +02:00
dpsutton
90867d89d0 Bump ring-jetty9-adapter to 0.22.3 (#35181)
```diff
-  info.sunng/ring-jetty9-adapter            {:mvn/version "0.22.1"}             ; Drop-in replacement for official Ring Jetty adapter. Supports Jetty 11 webserver.
+  info.sunng/ring-jetty9-adapter            {:mvn/version "0.22.3"}             ; Drop-in replacement for official Ring Jetty adapter. Supports Jetty 11 webserver.
```

Simple change, and quite possibly a no-op.

We have previously been overriding the jetty dep to be

```clojure
org.eclipse.jetty/jetty-server            {:mvn/version "11.0.17"}
```

And the dep tree before this change was:

```
info.sunng/ring-jetty9-adapter 0.22.1
  X ring/ring-core 1.10.0 :use-top
  X org.eclipse.jetty/jetty-server 11.0.15 :use-top
```

This is saying it declared a dep on 11.0.15 but was ignoring that in
favor of "use-top", aka the top level dependency we declared (11.0.17).

But synk is a scanning tool that doesn't check the artifact but the
manifests involved and flags issues in 11.0.15 and therefore Metabase
despite us not having that version.

Now the deps tree:

```
clj -X:deps tree :aliases '[:ee :drivers]'
info.sunng/ring-jetty9-adapter 0.22.3
  X org.eclipse.jetty/jetty-server 11.0.17 :use-top
```

Doesn't specify an older version of jetty and we're using the same jetty
version as we have for the last bit.
2023-10-30 07:48:12 -05:00
Kamil Mielnik
13424d36f2 Add test coverage for Dashboard Click Behavior - Line Chart (#34899)
* Reuse addOrUpdateDashboardCard

* Extract 15993 repro

* Extract 16334 repro

* Extract 23137 repro

* Extract 18067 repro

* Remove unused alias

* Add empty test suite for click-behavior

* Add a test for text cards

* Add createHeadingCard helper

* Add a test for heading cards

* Add createActionCard helper
- make text/label params optional in helpers
- remove unused dashboardId param in helpers

* Add a test for an action card

* Format code

* Reuse createActionCard in #32974 repro

* Simplify text code

* Reuse createActionCard, createTextCard & getNextUnsavedDashboardCardId in dashboard back navigation e2e

* Remove unused alias

* Inline 1-line createLinkCard helper

* Add createLinkCard helper

* Add a test for link cards

* Simplify interfaces of helper functions

* Update test title

* Add a test for object detail dashcard

* Remove redundant identifier

* Format code

* Add data-testid to ClickBehaviorSidebar

* Add setup for line chart test

* Test the actual click behavior

* Refactor expectDynamicAnchorClick to expectNextAnchorClick
- get rid of manual mock resetting

* Add test for editing URL filter

* Refactor expectNextAnchorClick to onNextAnchorClick

* Extract URL parameters test as a seprate one

* Fix assertions
- Add escapeCypressCurlyBraces

* Assert user can use dashboard filters and click event columns

* Use cy.get("aside") instead of sidebar functions
- Revert adding data-testid to sidebars

* Use all available parameters in the URL

* Add test for 0 filters

* Extract addFilter

* Add a test for single dashboard filter
- Add constants for magic numbers and values

* Extract OBJECT_DETAIL_CHART

* Use saveDashboard

* Add a test for multiple dashboard filters

* Improve URL assertion

* Improve assertions

* Format code

* Add a test for saved question destination

* Improve assertions

* Consolidate assertions

* Improve assertions

* Add a test for saved question with single parameter passed

* Update JSDoc

* Extract GAUGE_QUESTION_DETAILS & PROGRESS_QUESTION_DETAILS

* Reuse addOrUpdateDashboardCard

* Add a test for saved question with multiple parameters passed

* Extract FILTER_CREATED_AT & FILTER_COUNT

* Do not use elevated privileges

* Rename FILTER_COUNT to FILTER_QUANTITY

* Reuse ORDERS_ID

* Add a test for no saved question permissions

* Create dashboard filters via API

* Add a test

* Add a test for dashboard target

* Add test for 1 and multiple dashboard parameters

* Extract addTextParameter & addTimeParameter

* Improve assertions

* Use different question as target

* Use TARGET_QUESTION instead of SECRET_QUESTION

* Add a test for no dashboard permissions

* Add a test for drill-through menu behavior

* Fix typo

* Destructure location

* Format code, remove console.log

* Use slug instead of name where appropriate

* Add a test case for editing the click behavior

* Update comment

* Commit a dumb change to trigger uberjar rebuild

* Commit a dumb change to trigger uberjar rebuild

* Optimize line chart question
- add limit: 5
- update constants & assertions
- rename LINE_CHART to QUESTION_LINE_CHART
- extract clickLastLineChartPoint as click({ force: true }) is now needed

* Fix click simulation

* Revert "Commit a dumb change to trigger uberjar rebuild"

This reverts commit 27ef0600ad.

* Revert "Commit a dumb change to trigger uberjar rebuild"

This reverts commit a5141eb020.

* Extract helpers

* Reduce indentation, remove redundant assertions

* Chain assertions

* Rename test case

* Use parseSpecialCharSequences and get rid of escapeCypressCurlyBraces

* Assert dashboard pathname

* Remove pointless assertions

* Sort tests

* Test reverting to default click behavior

* Update post-merge conflicts

* Update post-merge conflicts
2023-10-30 08:52:05 +00:00
Ngoc Khuat
40af29dc22 Global search: optimize -- ~20% improvement (#34353) 2023-10-30 03:07:23 +00:00
Uladzimir Havenchyk
596c46ef71 [Dashboard] Make apply button aligned with fields on small screens (#35062) 2023-10-29 20:16:20 +00:00
metamben
4ab88d6812 Mark :type/Boolean as orderable (#35024) 2023-10-28 13:24:19 +03:00
Nemanja Glumac
e26598bd5a Fix e2e_all file path (#35190)
It should include `e2e_specs`. This has been missing from #35079.
2023-10-28 09:11:19 +02:00
Nemanja Glumac
58e811924e Fix E2E models metadata flakes (#35188)
* Fix model metadata flakes

* Do not use hard-coded ID

* Tweak tests

* Make viewport wider in order to fit the table content
2023-10-28 01:22:05 +02:00
Nemanja Glumac
e43bf37380 Stop caching uberjar for E2E tests (#35079)
* Stop caching the uberjar for E2E tests

* Bring back SHA1 in an uberjar name

* Adjust the download uberjar action

* Fix uberjar name for percy
2023-10-27 23:30:02 +02:00
Mark Bastian
dc8c63fde5 Dynamic metric x-rays (#34258)
Co-authored-by: dan sutton <dan@dpsutton.com>
2023-10-27 14:17:15 -06:00
Case Nelson
87f6384d07 [MLv2] Use date range formatting to display current date equal truncated date filters (#35075) 2023-10-27 19:10:46 +00:00
Ryan Laurie
1d4472e4e9 Use Mantine Switch instead of Toggle in Dashboard Sidebar (#34817) 2023-10-27 12:37:00 -06:00
Alexander Polyankin
3e57230b1c Fix table cells (#35148) 2023-10-27 15:13:25 +00:00
Anton Kulyk
6d8c4a3ec1 Use dayjs in TimeInput (#35045) 2023-10-27 15:13:20 +01:00
Anton Kulyk
8f9c2403b9 Fix E2E flake in repro for 23293 (#35144) 2023-10-27 13:56:44 +02:00
Oisin Coveney
e553187563 Can't choose recently viewed link with the mouse when editing dashboard link card #35037 (#35042)
Closes https://github.com/metabase/metabase/issues/35037

### Description

Ensures that clicking on a search/recents entry only triggers the onClick action, rather than the href/redirect behavior that the issue brings up.

_What Changed:_
- Added a new prop `isEnabled` to the InfoTextTableLink component.
- Modified the href attribute of a ResultTitle component.


### How to verify
 
- Create a new dashboard A, save it and visit it
- Create a new dashboard B and edit it.
- Add a link card to it
- A dropdown with "Recently viewed" items will appear
- Click header of the first entry in it with a mouse


### Checklist

- [X] Tests have been added/updated to cover changes in this PR
2023-10-27 14:06:30 +03:00
Case Nelson
57cd068cf8 [MLv2] Handle removing multiple dependent joins (#35109) 2023-10-27 07:52:06 +00:00
dpsutton
19f6d31553 Suppress some route logs on startup (#35120)
Annoying warnings on startup

;#### Before

```shell
 Warning: missing route-param regex for schema: /:entity/:entity-id-or-query/rule/:prefix/:dashboard-template [prefix Prefix]
 Either add :fn to metabase.api.common.internal/->matching-regex or metabase.api.common.internal/no-regex-schemas.
 Warning: missing route-param regex for schema: /:entity/:entity-id-or-query/rule/:prefix/:dashboard-template [dashboard-template DashboardTemplate]
 Either add :fn to metabase.api.common.internal/->matching-regex or metabase.api.common.internal/no-regex-schemas.
 Warning: missing route-param regex for schema: /:entity/:entity-id-or-query/cell/:cell-query [cell-query Base64EncodedJSON]
 Either add :fn to metabase.api.common.internal/->matching-regex or metabase.api.common.internal/no-regex-schemas.
 Warning: missing route-param regex for schema: /:entity/:entity-id-or-query/cell/:cell-query/rule/:prefix/:dashboard-template [prefix Prefix]
 Either add :fn to metabase.api.common.internal/->matching-regex or metabase.api.common.internal/no-regex-schemas.
 Warning: missing route-param regex for schema: /:entity/:entity-id-or-query/cell/:cell-query/rule/:prefix/:dashboard-template [dashboard-template DashboardTemplate]
 Either add :fn to metabase.api.common.internal/->matching-regex or metabase.api.common.internal/no-regex-schemas.
 Warning: missing route-param regex for schema: /:entity/:entity-id-or-query/cell/:cell-query/rule/:prefix/:dashboard-template [cell-query Base64EncodedJSON]
 Either add :fn to metabase.api.common.internal/->matching-regex or metabase.api.common.internal/no-regex-schemas.
 Warning: missing route-param regex for schema: /:entity/:entity-id-or-query/rule/:prefix/:dashboard-template/compare/:comparison-entity/:comparison-entity-id-or-query [prefix Prefix]
 Either add :fn to metabase.api.common.internal/->matching-regex or metabase.api.common.internal/no-regex-schemas.
 Warning: missing route-param regex for schema: /:entity/:entity-id-or-query/rule/:prefix/:dashboard-template/compare/:comparison-entity/:comparison-entity-id-or-query [dashboard-template DashboardTemplate]
 Either add :fn to metabase.api.common.internal/->matching-regex or metabase.api.common.internal/no-regex-schemas.
 Warning: missing route-param regex for schema: /:entity/:entity-id-or-query/cell/:cell-query/compare/:comparison-entity/:comparison-entity-id-or-query [cell-query Base64EncodedJSON]
 Either add :fn to metabase.api.common.internal/->matching-regex or metabase.api.common.internal/no-regex-schemas.
 Warning: missing route-param regex for schema: /:entity/:entity-id-or-query/cell/:cell-query/rule/:prefix/:dashboard-template/compare/:comparison-entity/:comparison-entity-id-or-query [prefix Prefix]
 Either add :fn to metabase.api.common.internal/->matching-regex or metabase.api.common.internal/no-regex-schemas.
 Warning: missing route-param regex for schema: /:entity/:entity-id-or-query/cell/:cell-query/rule/:prefix/:dashboard-template/compare/:comparison-entity/:comparison-entity-id-or-query [dashboard-template DashboardTemplate]
 Either add :fn to metabase.api.common.internal/->matching-regex or metabase.api.common.internal/no-regex-schemas.
 Warning: missing route-param regex for schema: /:entity/:entity-id-or-query/cell/:cell-query/rule/:prefix/:dashboard-template/compare/:comparison-entity/:comparison-entity-id-or-query [cell-query Base64EncodedJSON]
 Either add :fn to metabase.api.common.internal/->matching-regex or metabase.api.common.internal/no-regex-schemas.
 Warning: missing route-param regex for schema: /:key [key kebab-cased-keyword]
 Either add :keyword to metabase.api.common.internal/->matching-regex or metabase.api.common.internal/no-regex-schemas.
 Warning: missing route-param regex for schema: /:key [key kebab-cased-keyword]
 Either add :keyword to metabase.api.common.internal/->matching-regex or metabase.api.common.internal/no-regex-schemas.
 Warning: missing route-param regex for schema: /:zoom/:x/:y/:lat-field/:lon-field [lat-field :string]
 Either add :string to metabase.api.common.internal/->matching-regex or metabase.api.common.internal/no-regex-schemas.
 Warning: missing route-param regex for schema: /:zoom/:x/:y/:lat-field/:lon-field [lon-field :string]
 Either add :string to metabase.api.common.internal/->matching-regex or metabase.api.common.internal/no-regex-schemas.
```

;#### After

;#### Fixes

;###### :fn

We logged lots of startups that we didn't have a regex for the `:fn` type validator in routes. And this is generally not possible. So we should generally just ignore function based validators, as we're not going to write a regex for what a function validates/accepts. All of these `:fn` matchers are in the x-ray namespace matching base64 encoded json, an existing dashboard template prefix (`(malli.core/validate Prefix "TransactionTable")`),

;###### `:keyword`: Add a regex `#"[\S]+"` that just looks for non space characters

;###### String matches `:string`

```clojure
(def ^:private kebab-cased-keyword
  "Keyword that can be transformed from \"a_b\" -> :a-b"
  [:keyword {:decode/json #(keyword (u/->kebab-case-en %))}])

...

(api/defendpoint GET "/:key"
  "Fetch a single `Setting`."
  [key]
  {key kebab-cased-keyword}
  (with-setting-access-control
    (setting/user-facing-value key)))
```

We don't want a regex for this. Whatever we are currently accepting in the route matching is our desired behavior. Arbitrary strings don't have a good regex and we don't want to restrict what the route currently does.

```clojure
(api/defendpoint GET "/:zoom/:x/:y/:lat-field/:lon-field"
  "This endpoints provides an image with the appropriate pins rendered given a MBQL `query` (passed as a GET query
  string param). We evaluate the query and find the set of lat/lon pairs which are relevant and then render the
  appropriate ones. It's expected that to render a full map view several calls will be made to this endpoint in
  parallel."
  [zoom x y lat-field lon-field query]
  {zoom        ms/Int
   x           ms/Int
   y           ms/Int
   lat-field   :string
   lon-field   :string
   query       ms/JSONString} ...)
```
2023-10-26 21:39:23 -05:00
Oisin Coveney
54485cc85d Reorder type filter elements for Search (#35055) 2023-10-26 23:41:30 +03:00
Denis Berezin
adb2df0c50 Fix entities fetch caching (#34661)
* Fix entities fetch caching

* Add proper unit test, fix loop issue

* Review fixes, unit test fix
2023-10-26 20:14:04 +00:00
lbrdnk
25d7129c5c Support interval subtraction in expressions (#34752)
* Update sql qp to handle interval subtraction

* Update tests checking interval subtraction

* Transform assertions to exceptions
2023-10-26 20:01:10 +02:00
Cam Saul
b28abafbfc Don't look into viz settings when doing validate-temporal-bucketing query validation (#35072) 2023-10-26 10:35:44 -07:00
Case Nelson
9d243fc1f6 [MLv2] Fill in expression ref types on converted queries (#35016) 2023-10-26 17:06:53 +00:00
Jeff Bruemmer
eee20fce1a docs - notes on private channels (#35073) 2023-10-26 12:31:43 -04:00
Maz Ameli
b6b396de2b Revise the copy and tests for for the "don't lose your changes" confirmation modal (#34995)
* update copy and tests for confirmation modal

* fix tests
2023-10-26 09:18:55 -07:00
Nicolò Pretto
28d8dc9afa [move cards between tabs] Milestone 1 (#34832)
Co-authored-by: Emmad Usmani <emmadusmani@berkeley.edu>
Co-authored-by: Uladzimir Havenchyk <125459446+uladzimirdev@users.noreply.github.com>
Co-authored-by: Nicolò Pretto <info@npretto.com>
Co-authored-by: Alexander Polyankin <alexander.polyankin@metabase.com>
2023-10-26 17:32:33 +02:00
Cal Herries
768ba0577f Move metabase/core/utils/types to metabase/lib/types (#35090) 2023-10-26 16:05:46 +03:00
Kamil Mielnik
38b472f6cc Extract click-behavior e2e reproductions (#34898)
* Reuse addOrUpdateDashboardCard

* Extract 15993 repro

* Extract 16334 repro

* Extract 23137 repro

* Extract 18067 repro

* Remove unused alias

* Extract GAUGE_QUESTION_DETAILS & PROGRESS_QUESTION_DETAILS

* Reuse addOrUpdateDashboardCard

* Commit a dumb change to trigger uberjar rebuild

* Revert "Commit a dumb change to trigger uberjar rebuild"

This reverts commit 27ef0600ad.
2023-10-26 15:01:48 +02:00
shaun
00079fa9de update Trend chart design (#34587) 2023-10-26 13:33:49 +02:00
Anton Kulyk
950bc988a8 Fix crash when opening filter popover's expression editor (#35022)
Co-authored-by: Uladzimir Havenchyk <125459446+uladzimirdev@users.noreply.github.com>
2023-10-26 11:56:30 +01:00
Cal Herries
4252af1c66 Show 'From connected filters' option if parameter has fields (#34958) 2023-10-26 10:00:28 +00:00
Nemanja Glumac
dfe0210929 Fix E2E flake content-verification (#35084) 2023-10-26 11:52:55 +02:00
Nemanja Glumac
dbfd6b811d Fix stress-test workflow (#35083)
[ci skip]
2023-10-26 11:44:03 +02:00
Braden Shepherdson
8962b63eb1 Add drop_entity_ids CLI command, to drop all entity_ids (#34996)
This is useful for migrating from serdes v1 to v2.

Fixes #34871.
2023-10-26 08:47:03 +00:00
Nemanja Glumac
25c4e6a74e Fix E2E flake 17514 (#35082) 2023-10-26 10:37:17 +02:00
Aleksandr Lesnenko
3398d6c4b8 do not auto pivot table on high cardinality columns (#34770) 2023-10-25 21:59:20 +00:00
Cam Saul
76fdfa84ee Test for #34957 (#34986) 2023-10-25 11:28:01 -07:00
shaun
70173c3e4f Hide header info icon when card is too small (#34929) 2023-10-25 18:25:07 +00:00
Cal Herries
54bc469f37 Explain why linked filters and "From connected fields" don't work for native variables on the dashcard (#34969) 2023-10-25 21:02:13 +03:00
Jeff Bruemmer
cace86a410 note on language direction (#34856) 2023-10-25 17:34:33 +00:00
Cal Herries
8f23be707c Refactor: separate param-values from API endpoint usage (#35001) 2023-10-25 19:24:45 +03:00
Anton Kulyk
015327d0a5 Follow up on deprecating moment (#35044) 2023-10-25 16:52:28 +01:00
Ngoc Khuat
bfe5b2747d fix enable-email-restrict-recipients? check for the wrong flag (#35031) 2023-10-25 22:50:54 +07:00
Anton Kulyk
1d569585bd Fix typo in TimeInput story file (#35053) 2023-10-25 14:55:44 +01:00
Nick Fitzpatrick
9830930e96 fix scrolling while dragging column items (#34844)
* fix scrolling while dragging column items

* Add issue number for scrolling

---------

Co-authored-by: Jesse Devaney <22608765+JesseSDevaney@users.noreply.github.com>
2023-10-25 13:18:41 +00:00
Ngoc Khuat
76fa899471 Hydrate collection.is_personal (#34827) 2023-10-25 12:40:00 +00:00
Cal Herries
205f2ac384 Add .portal to gitignore (#35036) 2023-10-25 09:38:19 +00:00
Nemanja Glumac
042a32c9b7 Separate Replay E2E tests from the main workflow (#34895)
* Separate Replay E2E tests from the main workflow

* Fix workflow conditionals
2023-10-25 11:13:38 +02:00
Nemanja Glumac
b7eff22f3e Refine CI triggers for backend tests (#34890) 2023-10-25 08:23:48 +02:00
Nemanja Glumac
df16fc89e9 PoC External workflow run trigger (#34951)
[ci skip]
2023-10-25 08:23:20 +02:00
Anton Kulyk
0624d8d093 Mark moment-timezone as deprecated (#35020)
* Mark `moment-timezone` as deprecated

* Fix other eslint configs

* Disable eslint for current occurrence of moment
2023-10-24 23:23:23 +00:00
Nick Fitzpatrick
75243d7ae6 Ensure that field picker icon does not get smushed (#34808)
* Ensure that field picker icon does not get smushed

* removing unhelpful test

* register visualizations in test
2023-10-24 15:48:42 -03:00
Nick Fitzpatrick
52b6a7038a use replace for programatic navigation in Table Metadata (#34756)
* use replace for programatic navigation

* adding comments
2023-10-24 14:57:43 -03:00
Tim Macdonald
8a4c335a66 Fix broken link in backend docs (#35010) 2023-10-24 14:00:50 +00:00
Ngoc Khuat
f89ac78210 Global search: adding more filters (#32624) 2023-10-24 16:41:49 +03:00
Ibe Dwi
00f1ca7cc8 Return "parameterId" as "id" in removeParameter action (#34680)
* red: reproduce the error in test case

* green: return id in removeParameter action

* refactor: create dashboard actions parameters unit test

* chore: rename unit test

* fix: update test's issue reference

* chore: add new line
2023-10-24 18:28:53 +07:00
Kamil Mielnik
cef520443a Fix - Unsaved changes warning shown when going back to notebook after visualizing the question (#35003)
* Fix running and then editing the question

* Fix running and then editing the structured model

* Add a test for #35000

* Add a test for models in #35000

* Consolidate waiting for save to be enabled/disabled
- Rename waitForSaveQuestionToBeEnabled to waitForSaveToBeEnabled
- Rename waitForSaveModelToBeEnabled to waitForSaveChangesToBeEnabled
- Rename waitForSaveModelToBeDisabled to waitForSaveChangesToBeDisabled
- Remove waitForSaveNewQuestionToBeEnabled in favor of waitForSaveToBeEnabled
2023-10-24 17:13:15 +07:00
Braden Shepherdson
0404a350d1 Update gitignore with some more local junk files (#34926) 2023-10-23 16:30:40 -07:00
Braden Shepherdson
bd28194b49 [MLv2] Full :columns for :dimensions in available-drill-thrus (#34810)
Previously only the `:column-name` was provided, and there is a
self-proclaimed "icky hack" to guess at the full columns. The FE
provides the (JSON) columns, so this PR converts and uses them.

The icky hack can be removed.

`:column-ref` is included because sometimes it's important that the refs
use the same UUID.
2023-10-23 22:34:20 +00:00
metamben
841ec9ef6f Use the display name of the card as join alias (#34921) 2023-10-23 18:24:31 -04:00
metamben
5f25388568 Ignore undefined tag parameters sent by the FE (#34933)
Fixes #34729.
2023-10-23 21:14:00 +03:00
Nemanja Glumac
90c529240e Run MySQL v8.0 for driver tests (#34943)
EOL v5.7 was October 21, 2203.

The image changed from the legacy `circleci/` image to `cimg/`
https://circleci.com/developer/images/image/cimg/mysql
2023-10-23 17:45:09 +02:00
Nemanja Glumac
4b792e8034 Fix e2e stub condition (#34964) 2023-10-23 16:56:22 +02:00
Kamil Mielnik
b08e03edea Do not use history.goBack() to trigger navigation (#34956)
- Some tests had a redundant initial route just so that there is
  an entry in history we can go back to. This caused NewItemMenu to
  be redundantly rendered, which caused race conditions in the entity
  framework. We do not need history.goBack(), we can use history.push()
  but we need an extra, safe route we can try to navigate to.
- @see https://metaboat.slack.com/archives/C057T1QTB3L/p1697183111294489
- @see https://metaboat.slack.com/archives/C5XHN8GLW/p1697811520881169
- @see https://github.com/metabase/metabase/pull/34661
2023-10-23 16:41:36 +02:00
Nemanja Glumac
b1b13346cb Define CI triggers for frontend tests (#34944) 2023-10-23 15:45:31 +02:00
Cal Herries
b04b4ed355 Refactor: Remove FieldValuesWidget forceTokenField prop (#34903) 2023-10-23 11:15:36 +03:00
Nemanja Glumac
0c4a6d863f Move E2E download uberjar logic into a composite action (#34647)
* Move E2E download uberjar logic into a composite action

* Check out only the last 20 commits

* Always use the correct, last commit in a branch

This helps us avoid the slippery slope in which GitHub creates a new
merge commit, that doesn't exist in the repo, under our feet.

* Adapt the stress-test workflow to use new download action

* Increase the number of commits to search through

* Update .github/actions/e2e-download-uberjar/action.yml

Co-authored-by: Ryan Laurie <30528226+iethree@users.noreply.github.com>

* Log full artifact name

* Correctly download artifact from the current build

---------

Co-authored-by: Ryan Laurie <30528226+iethree@users.noreply.github.com>
2023-10-22 19:31:50 +02:00
Nemanja Glumac
6694129965 Fix E2E 20517 flake (#34927)
[ci skip]
2023-10-20 22:24:13 +02:00
Nemanja Glumac
8808c728ca Revert "[CI] Make Chromatic workflow 3rd party friendly (#34725)" (#34902)
This reverts commit 45d7460617.
2023-10-20 22:19:20 +02:00
Kyle Doherty
b7c756f11b remove padding on HeaderBadges to align title and last edit info (#34913) 2023-10-20 18:33:28 +00:00
metamben
955aab1fb3 Add filter-positions to the result of available-segments (#34815) 2023-10-20 16:37:03 +03:00
metamben
f12601a5d0 Add aggregation-position to available-metrics (#34867) 2023-10-20 16:36:32 +03:00
Nemanja Glumac
19dd58f930 Start running the fuzzing workflow on related changes (#34900) 2023-10-20 15:22:50 +02:00
Alexander Polyankin
4b3901f51f Fix dayjs i18n init (#34897) 2023-10-20 12:43:41 +00:00
Nemanja Glumac
6d8cf60a0b Run fuzzing workflow on demand (#34891)
[ci skip]
2023-10-20 14:13:14 +02:00
Anton Kulyk
a413d6a81b Clean up QB filter panel components (#34852)
* Extract `FilterHeaderButton`

* Move `QuestionFilters` to its own directory

* Remove not used `QuestionFilters` component

* Extract styled components

* Convert `ViewPill` to TypeScript

* Convert `QuestionFilters` to TypeScript

* Clean up

* Fix label
2023-10-20 12:41:18 +01:00
Nemanja Glumac
cb2263f776 [E2E] Set the TERM env at the job level (#34879)
No need to repeat the same line for every single **step**
when all steps can read from the **job** context.
2023-10-20 08:49:16 +00:00
lbrdnk
08f72b76b3 Update sqlserver CI jobs (#34861)
Add new sqlserver 2022 jobs to the CI and update the existing one's name.
2023-10-20 09:48:42 +02:00
Cal Herries
3d39bb26ba Rename dashboard's ordered_tabs to tabs (#34840) 2023-10-20 07:30:53 +00:00
Alexander Solovyov
418ef5c7ac show banner and log error when token format is invalid (#34789)
Makes /api/properties and /api/premium-features/token/status return valid structures with information about invalid token, plus logs the error about token being invalid in logs. Also this information is used to show a PaymentBanner on top of the screen so that admins can understand what is going on.

Resolves #33858
2023-10-20 09:05:04 +03:00
bryan
1ec1b61a45 PoC for explicitization of dynamic vars (#34030)
* PoC for explicitization of dynamic vars

* deref the current-user delay

* missed one

* fix flaky log test

* create-card! takes a card as first arg
2023-10-19 15:48:31 -06:00
Noah Moss
d8a9a00eb0 Only quote roles for connection impersonation when they contain special characters (#34858) 2023-10-19 21:41:42 +00:00
shaun
16e5bb6ae7 Add yarn dev to dev environment doc (#34860) 2023-10-19 20:44:53 +00:00
Cam Saul
a0667fd3db Distribution drill should not apply binning to FK columns (#34814) 2023-10-19 18:50:36 +00:00
Ryan Laurie
6e669a90e0 Use env vars for user-controlled strings (#34838) 2023-10-19 12:24:46 -06:00
Jeff Bruemmer
b601f5f878 Update data.md (#34755) 2023-10-19 17:15:35 +00:00
Nemanja Glumac
30caaa2462 Colorize E2E Docker container logs (#34793) 2023-10-19 18:54:13 +02:00
Alexander Polyankin
23b4099305 Day.js initialization for mantine (#34802) 2023-10-19 20:10:09 +04:00
Alexander Polyankin
d3865eefd1 Mantine DatePicker and DateInput (#34651) 2023-10-19 16:06:01 +00:00
Cal Herries
7463953499 Execute PUT requests in parallel on dashboard save (#34796) 2023-10-19 15:57:15 +00:00
Aleksandr Lesnenko
93d51c2ab8 fix and reorganize static viz stories (#34843) 2023-10-19 15:25:12 +00:00
Denis Berezin
8f8ab29774 Add dashboard parameter mapping for date range (#34544)
* Add dashboard parameter mapping for date range

* Fix unit tests

* Add e2e tests

* Update logic to use date range only for specific units
2023-10-19 14:54:50 +02:00
Uladzimir Havenchyk
c0d59b82e1 Fix an error during updating cards which are dashcards (#34786) 2023-10-19 12:34:34 +00:00
Anton Kulyk
fea24aa35a Mantine Popover (#34803)
* Add Mantine `Popover`

* Fix spacing

* Deprecate previous popovers
2023-10-19 13:07:43 +01:00
Alexander Polyankin
98c3fb4929 Mantine Tooltip (#34797) 2023-10-19 10:00:08 +00:00
Kamil Mielnik
6cec760553 Add custom warning message when leaving editing a notebook question (chill mode only) (#34658)
* Update isNavigationAllowed logic to prevent new model creation

* Add simple model creation test

* Remove identifier

* Update comment

* Add a test case for saving a new model

* Avoid using fetchMock directly in QueryBuilder unit tests

* Remove setupCollectionsEndpointsByIds in favor of setupCollectionByIdEndpoint

* Add native question test base

* Update isNavigationAllowed tests

* Make isNavigationAllowed tests pass

* Update shouldShowUnsavedChangesWarningForSqlQuery logic to account for new questions

* Add a test case to run new native question

* Update mock to include individual collection GET endpoint

* Add DataSourceSelectors to MockNativeQueryEditor

* Update test beforeunload event to reflect new behavior

* Use setupCollectionByIdEndpoint instead of modifying setupCollectionsEndpoints

* Update failing test

* Use serializeCardForUrl

* Add a test for native query editing

* Do not trigger warning when leaving empty question

* Add beforeunload tests for creating new questions

* Remove redundant div

* Make assertions consistent

* Use single resetAllMocks()

* Fix post-rebase conflict

* Simplify getShouldShowUnsavedChangesWarning's logic

* Add isModifiedFromNotebook to store

* Show unsaved changes warning when structured question has been modified via notebook editor

* Use explicit return type, as it's not obvious that this function needs to be a Promise

* Remove unused selector dependency

* Update mocks with new attribute

* Add a test for editing notebook questions

* Extract waitForSaveNewQuestionToBeEnabled out of triggerNotebookQueryChange

* Introduce waitForSaveModelToBeEnabled & waitForSaveModelToBeDisabled

* Add a test case

* Remove redundant navigation

* Update isNavigationAllowed logic and tests

* Refactor tests and add more test cases

* Add more test cases

* Shorten code

* Add a test for saving the question

* Refactor isNavigationAllowed

* Add a test for not showing modal

* Add a test for non-notebook changes

* Organize code

* Use existing setUIControls

* Add extra assertions for post-save navigation to check if question is properly mark as non-dirty

* Add extra assertions for post-save navigation to check if question is properly mark as non-dirty

* Add a post-save nagivation test

* Add logic to reset UI controls isModifiedFromNotebook state after saving the question

* Rename to allowedPathnames

* Add explanatory comment

* Update failing e2e test

* Fix #32963 e2e repro failing

* Allow `/model/${slug}` to make models-query-editor e2e test pass

* Update isNavigationAllowed logic to make e2e tests pass

* Update isNavigationAllowed tests

* Add 1 more model location

* Revert identifier name change

* Use optional chaining operator for brevity

* Fix typo

* Rename notebook to structured

* Rename getQuestionLocations to getNativeQuestionLocations and don't use getNativeQuestionLocations in getStructuredQuestionLocations
2023-10-19 09:13:06 +00:00
Alexander Polyankin
8b48eb2d43 Mantine TimeInput (#34646) 2023-10-19 11:57:48 +04:00
Alexander Solovyov
3cf3cc3af7 Remove data migrations (#34598)
Moves `migrate-click-through` and `migrate-remove-admin-from-group-mapping-if-needed` to custom migrations, so that all migrations are handled by liquibase.

Resolves #32611, #32612

Co-authored-by: John Swanson <john.d.swanson@gmail.com>
2023-10-19 07:36:09 +00:00
Noah Moss
2dbbf12161 Fix pivot table e2e test on master (#34825)
* remove redundant cy.wait

* try again to fix test failure in CI that doesn't repro locally
2023-10-19 07:30:05 +02:00
Nemanja Glumac
0c9f77daeb Store E2E uberjar artifact with a SHA1 in its name (#34811) 2023-10-19 06:12:30 +02:00
Cam Saul
f3b31a9266 quick-filter drill on an aggregate column should introduce a new stage (#34812) 2023-10-19 02:56:25 +00:00
Noah Moss
42bd30c6a6 Determine pivot-cols and pivot-rows on the backend using viz settings (#34583) 2023-10-18 23:22:54 +00:00
metamben
aa5d804b98 Support duplicate columns hidden in cards (#34636) 2023-10-19 01:52:10 +03:00
metamben
031fc025f8 Add filter-positions to filterable-columns (#34769) 2023-10-18 19:19:53 +00:00
John Swanson
71641927af Add a couple tests for comma-separated numbers in a number field (#34627)
We want to add some tests to verify that this (slightly hidden) feature continues working.

Fixes: https://github.com/metabase/metabase/issues/21163
2023-10-18 12:02:45 -07:00
Cal Herries
8fb7a78425 Rename dashboard's ordered_cards to dashcards (#34792) 2023-10-18 19:00:22 +00:00
Cam Saul
fb4bfa2896 Drill thru fixes: #34439, #34440, #34441 (#34760) 2023-10-18 17:40:25 +00:00
lbrdnk
caaf963ff5 Add test checking driver defmultis are mentioned in changelog (#32262)
* Add `:added` metadata to driver multimethods

Commit which introduced defmulti was determined
with `git log -L<line>,+1:<file>. Then first version it appeared in
was extracted from `git tag --contains <sha>`.

* Add driver methods changelog test

* Add `:changelog-test/ignore` to various defmultis

Multiple defmultis added after 42 incl. are missing entries from
changelog. Marking them this way makes it possible to add those
entries retrospectively without having failing tests, one by one.
2023-10-18 16:41:48 +02:00
Nick Fitzpatrick
329cc52253 Adding check for column before getting friendly name (#34761) 2023-10-18 10:22:29 -03:00
Nick Fitzpatrick
988398ce16 34618 splitting breakouts (#34674)
* no splitting when there is only 1 metric

* checking for unique cards, not series

* beefy e2e test
2023-10-18 09:58:45 -03:00
Case Nelson
595d20785f Mlv2 describe relative date time range (#34765) 2023-10-18 16:54:41 +04:00
metamben
48903246c1 Remove invalid test cases (#34758) 2023-10-17 23:05:51 +03:00
Nemanja Glumac
faca09c6cc Conditionally start Docker containers for E2E tests (#34655)
* Conditionally start Docker containers for E2E tests

* Check out before initializing Docker containers

* Use official action to log in to DockerHub

* Evaluate conditional expressions

* Try shell conditionals

* Fix errors due to unset vars

* Run either Mongo or Pg+MySQL
2023-10-17 20:00:55 +02:00
Nemanja Glumac
cc24e188cc Remove branch information from version.properties (#34406)
* Remove `branch` from version.properties file

* Remove branch from logs

* Remove `branch` from `application-name`

The `application-name` string is needed for Google drivers.
See: https://github.com/metabase/metabase/issues/2627
2023-10-17 19:59:36 +02:00
Case Nelson
021cff2bdf [MLv2] Adjust filter clause display-names (#34415)
https://www.notion.so/metabase/Filter-clause-text-descriptions-556639c83bd24e3f9a306b68d36e8a1f

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>
Co-authored-by: Anton Kulyk <kuliks.anton@gmail.com>
2023-10-17 17:23:12 +00:00
lbrdnk
07b74ebdfc Add metabase_field semantic_type migration (#34664)
* Update migration and add test

Sets semantic_type to null for metabase_field if value was type/Number,
to avoid log warnings.

* Remove test for trivial migration as suggested

As migration tests are costly and change is trvial, it is better
to test small migration as one in question manually. Hence removing
the test.
2023-10-17 18:46:28 +02:00
metamben
269e19d65b Enable column-filter, disable distribution and summarize-column drills for aggregated columns (#34681) 2023-10-17 19:29:31 +03:00
metamben
1166d8f08d Test that metabase.util/assoc-default preserves metadata (#34716) 2023-10-17 19:28:21 +03:00
Cam Saul
9b3757d99b Fix quick-filter drill returning extra operators (#34445) (#34678) 2023-10-17 09:08:00 -07:00
Nicolò Pretto
d7c9354852 remove typo from docs (#34732) 2023-10-17 12:52:14 +00:00
Kamil Mielnik
f7cf34e29d Add custom warning message when leaving creating an SQL question (#34696)
* Update isNavigationAllowed logic to prevent new model creation

* Add simple model creation test

* Remove identifier

* Update comment

* Add a test case for saving a new model

* Avoid using fetchMock directly in QueryBuilder unit tests

* Remove setupCollectionsEndpointsByIds in favor of setupCollectionByIdEndpoint

* Add native question test base

* Update isNavigationAllowed tests

* Make isNavigationAllowed tests pass

* Update shouldShowUnsavedChangesWarningForSqlQuery logic to account for new questions

* Add a test case to run new native question

* Update mock to include individual collection GET endpoint

* Add DataSourceSelectors to MockNativeQueryEditor

* Update test beforeunload event to reflect new behavior

* Use setupCollectionByIdEndpoint instead of modifying setupCollectionsEndpoints

* Update failing test

* Use serializeCardForUrl

* Add a test for native query editing

* Do not trigger warning when leaving empty question

* Add beforeunload tests for creating new questions

* Remove redundant div

* Make assertions consistent

* Use single resetAllMocks()

* Fix post-rebase conflict

* Work around Cypress not handling beforeunload-related prompts

* Our app registers beforeunload event listener e.g. when editing a native SQL question.
* Cypress does not automatically close the browser prompt and does not allow manually
* interacting with it (unlike with window.confirm). The test will hang forever with
* the prompt displayed and will eventually time out. We need to work around this by
* monkey-patching window.addEventListener to ignore beforeunload event handlers.
*
* @see https://github.com/cypress-io/cypress/issues/2118
2023-10-17 16:15:04 +07:00
Nemanja Glumac
45d7460617 [CI] Make Chromatic workflow 3rd party friendly (#34725)
* Make `Chromatic` workflow 3rd-party friendly

* Remove unused output

* Unify the use of `GITHUB_TOKEN`

* Update label check

* Fix wrong token reference

[ci skip]
2023-10-17 10:55:46 +02:00
Nemanja Glumac
0d2265b391 [E2E] Fix broken Replay runs (#34722)
This was causing scheduled runs to fail due to a
missing closing quotes in a string.

[ci skip]
2023-10-17 07:43:45 +02:00
Jeff Bruemmer
87fd1e76d3 update releases (#34675) 2023-10-16 12:40:33 -04:00
Uladzimir Havenchyk
691281c275 Fix download full results link for embedded and public questions (#34659) 2023-10-16 18:58:58 +03:00
Alexander Solovyov
43d9be7d4e fix "between datetimes" filter (#34704)
fixes #34615
2023-10-16 15:58:24 +00:00
Cal Herries
d7156adbe0 FE: Disable invalid values source options if parameter has linked filters (#34531) 2023-10-16 15:54:00 +00:00
Ryan Laurie
e79c114cde Use correct build dependencies for build-for-release job (#34457) 2023-10-16 09:18:05 -06:00
Cal Herries
a96e777071 Revert "Remove eclipse.org/dev links from docs (#34684)" (#34700) 2023-10-16 17:11:39 +03:00
Kamil Mielnik
dc676e1e64 Add custom warning message when leaving creating a model (#34527)
* Update isNavigationAllowed logic to prevent new model creation

* Rename tests

* Add routes for model creation

* Allow null card in setup

* Add test case for creating models in isNavigationAllowed

* Add simple model creation test

* Add workaround for metabase#34523

* Remove "Discard changes?" confirmation modal when creating a model
- use a single "Cancel" button
- remove custom cancel edit warning

* Update e2e test

* Remove redundant function bodies

* Bring back unsaved changes warning on cancel click when editing a model

* Add beforeunload event test for creating models

* Fix unit test

* Fix unit test and isNavigationAllowed

* Use regexp

* Add notebook prefix

* Drop mock prefix

* Use it.each

* Use it.each

* Use it.each

* Use it.each

* Use it.each

* Use it.each

* Refactor isNavigationAllowed

* Remove identifier

* Update comment

* Add a test for the cancel button

* Rename /home route to / so that redirection after cancelling creating a model works

* Add a test case for saving a new model

* Avoid using fetchMock directly in QueryBuilder unit tests

* Remove setupCollectionsEndpointsByIds in favor of setupCollectionByIdEndpoint

* Remove default value for card parameter
2023-10-16 18:13:41 +07:00
lbrdnk
b48db6916a Update join condition transformation for mongo (#34619)
* Update join condition transformation for mongo

LHS of let in lookup must contain identifier with no dots. This commit
updates identifier generation to conform that.

* Add review suggestions
2023-10-16 12:31:31 +02:00
Cal Herries
887e3f219e BE: Remove filterParameters from parameter if values_query_type=none (#34660) 2023-10-16 13:27:15 +03:00
Nemanja Glumac
595ea881ab Move browser-related Cypress prep steps to a composite action (#34642)
* Move browser-related Cypress prep steps to a composite action

* Fix browser paths
2023-10-16 11:02:37 +02:00
Cal Herries
6772456051 Fix dashboard filter label carrying over from previously edited label (#34613) 2023-10-16 08:23:17 +00:00
Cal Herries
5e3cf65589 Remove eclipse.org/dev links from docs (#34684) 2023-10-16 11:01:52 +03:00
Lena
f76bdf9e59 update the team label names in .github/team.json (#34685)
Remove the emojis from the team labels. With the emojis, the "auto-add to project" github automated workflow doesn't work, and we rely on it for the #bug-triage channel on slack. After several attempts of escaping the emojis, they've been removed from the labels, and now have to be removed here as well for the auto-assignment of PRs to continue working.
2023-10-16 09:46:15 +02:00
Cal Herries
a5be63242c FE: Prevent setting linked filters if filter widget is input box (#34663) 2023-10-16 06:51:41 +00:00
Alexander Solovyov
8d1a2bbd01 store metabase version in cards and revisions (#28387, #29167) (#34520) 2023-10-16 09:48:17 +03:00
Nemanja Glumac
e7ec68f44d Bump Postgres version in drivers tests in CI to 12 (#34403)
* Bump Postgres in drivers tests to 12

* Update env vars

* Authenticate with password

* user name with prefix pg_ is not allowed

---------

Co-authored-by: Ngoc Khuat <qn.khuat@gmail.com>
2023-10-16 07:14:02 +02:00
Tim Macdonald
8f2a82ea96 Use Marginalia to centralize documentation (#34608) 2023-10-14 10:03:39 +00:00
Jerry Huang
bd8fe4a953 Add public setting to opt-in to CC recipients (#34621) 2023-10-13 12:36:13 -07:00
Denis Berezin
b55da4db39 Migrate Sort drill to use MLv2 implementation (#34460)
* Add Sort drill

* Fix unit tests

* Add more unit/integration tests

* Add more unit/integration tests

* Add more unit/integration tests
2023-10-13 19:32:11 +00:00
Anton Kulyk
1b03ca3e69 Collapse temporal units list (#32953)
* Collapse temporal units list

* Extract `MoreButton` component

* Simplify conditions

* Make `isInitiallyExpanded` a bit more clear

* Use `INITIALLY_VISIBLE_ITEMS_COUNT` in tests

* Fix typos

* Remove comment

* Update popover size and spacing

* Remove outdated test

* Update E2E tests

* Add hover state to the "More" button

* Disable hover transition
2023-10-13 19:15:14 +01:00
Anton Kulyk
164742caef Fix notebook cell cursor (#34648) 2023-10-13 19:05:49 +01:00
Cam Saul
84e8079f60 Applying sort-drill thru should REPLACE existing sort on same column (#34637) 2023-10-13 17:28:41 +00:00
John Swanson
ed00657b68 replace java-time namespace with java-time.api
This namespace is deprecated and replaced with `java-time.api`.

https://github.com/metabase/metabase/issues/34506
2023-10-13 07:31:41 -07:00
Ngoc Khuat
54460e7dc6 Fix unable to start dev mode with a fresh DB (#34640) 2023-10-13 12:57:16 +00:00
Cal Herries
8c82d6bf01 src-min-noconflict -> src-noconflict (#34602) 2023-10-13 11:39:39 +00:00
Anton Kulyk
c220919161 Remove model metadata editor sidebar animation (#34612) 2023-10-13 11:09:10 +01:00
Alexander Solovyov
87580d030d add big query log processor (#34609)
fixes #31153

Co-authored-by: Mayank Agarwal <mayankagarwal44442@gmail.com>
2023-10-13 11:58:50 +03:00
Cal Herries
7ce84d852d FE: Do not show linked filter options if the parameter has values_source_type of "static-list" or "card" (#34438) 2023-10-13 11:08:14 +03:00
Oisin Coveney
054a2d4be9 Add verified_filled icon (#34463) 2023-10-13 09:21:02 +03:00
Luis Paolini
066e41cf04 Upgrade Jetty (#34605) 2023-10-12 23:11:27 -03:00
Aleksandr Lesnenko
6937fcfba9 replace github_env with github_output because env is not available in other jobs (#34629) 2023-10-12 21:58:40 +00:00
Case Nelson
b48702db12 [MLv2] Support replacing segments (#34547) 2023-10-12 15:24:53 -06:00
Noah Moss
d721afee3a Truncate slack token and make it visible to settings managers (#34620) 2023-10-12 21:22:00 +00:00
Luis Paolini
ecdff94ff8 Add check for driver version (#33471)
* Add check for driver version

* Update docs/troubleshooting-guide/db-connection.md

Co-authored-by: Jeff Bruemmer <jeff.bruemmer@gmail.com>

---------

Co-authored-by: Jeff Bruemmer <jeff.bruemmer@gmail.com>
2023-10-12 20:44:49 +00:00
Tim Macdonald
58e805abc0 Support string PKs in CSV files (#34595)
[Fixes #34592]
2023-10-12 21:17:19 +01:00
Aleksandr Lesnenko
bd7132f337 fix backports by using gh cli (#34624)
* use gh cli in the backport script
2023-10-12 20:07:37 +00:00
Ryan Laurie
003ec3dedd Improve release commit check (#34550) 2023-10-12 19:57:07 +00:00
Noah Moss
e14c1ff855 Add mb-version query param to token check request (#34584) 2023-10-12 15:39:48 -04:00
Nick Fitzpatrick
717ce7ddc6 Adding dropped series to split suggestions (#34455)
* Adding dropped series to split suggestions

* adding unit test

* adding e2e test
2023-10-12 15:03:11 -03:00
Maz Ameli
4baff24beb let them eat cake (#34586) 2023-10-12 09:16:15 -07:00
Luis Paolini
73c7013d04 Remove db dependant extensions (#34534) 2023-10-12 15:03:05 +00:00
lbrdnk
77f68ea8ec Update test expression-with-only-field-in-source-query-test (#34599)
Make test parallel, now for real! And `checkins` -> nil has no effect
from functional point of view, but leaving checkins in could just
confuse the reader.
2023-10-12 14:28:03 +00:00
Ryan Laurie
ad84822372 Automatically manage milestones in releases (#34508) 2023-10-12 07:22:19 -06:00
John Swanson
a2d3b00520 Prune deleted in-memory databases on startup (in dev)
Thanks to @dpsutton for the help here! I investigated an alternative approach of reusing the machinery that we use in
tests to determine whether the database already exists, but that turned out to rely on a private atom that stored a
list of databases created by the tests. I didn't want to muck around with those internals, and it turned out to be
simpler than expected to make `can-connect?` work (although I did need to catch the exception thrown when we couldn't
connect, which seems a little odd - I would have expected `can-connect?` to catch that and return `false`).

Fixes https://github.com/metabase/metabase/issues/9962
2023-10-12 05:09:26 -07:00
Tim Macdonald
2a05f18dfd Add int PKs to CSVs (#34173)
[Fixes #33714]
2023-10-12 12:38:11 +01:00
Anton Kulyk
20d392be02 MLv2 — Migrate notebook's join step to MLv2 (#33078)
* MLv2 Joins 1 — Basic features (#32903)

* Fix `FilterClause` return type

* Export `Joinable` type

* Add `Join` type to `replaceClause`

* Add `CardDisplayInfo` type

* Add `FilterOperatorDisplayInfo` type

* Add `JoinExternalOp` type

* Export `QueryColumnPickerProps`

* Implement basic MLv2 `JoinStep`

* Remove `null` condition hack

* Sync join strategy on external query update

* Clean `JoinStep.styled.tsx`

* Add `JoinConditionClause` type

* Fix join external op type-casting

* Use HTML button in `JoinTablePicker`

* Simplify `JoinStep` logic

* Add `Join` type to `removeClause`

* Extract `useJoin` hook

* Extract `useJoinCondition` hook

* Group `JoinStep` components into directories

* Fix new condition rendering hack

* Use `cursor: pointer` for join column picker

* Fix condition duplication

* Fix missing LHS/RHS column method arguments

* Simplify join condition assertions

* Fetch metadata for selected table

* Fix `joinConditionLHSColumns` usage

* Highlight selected condition columns

* Preselect right table database, filter databases

* Fix table filter

* Open LHS column picker when table is selected

* Use `joinLHSDisplayName`

* Patch test

* Fix text

* Open RHS column picker once the LHS one is selected

* Preselect models picker for model based questions

* Fix test

* Remove TODOs

* Fix popover ref

* Disallow removing condition columns

* Use "Previous results" if table name is unavailable

* Fix previous results shown too early

* Update `joinLHSDisplayName` usage

* MLv2 Joins 2 — Suggested condition (#32904)

* Use suggested join condition if available

* Remove `it.todo`

* MLv2 Joins 3 — Fields (#32905)

* Update `FieldsPicker` API

* Export `JoinFields` type

* Implement join fields selection

* Fix empty column list when need to fetch metadata

* Add missing tests

* Remove `it.todo`

* Extend tests

* Fix tests

* Fix race-condition when loading table metadata

* Make field picker's `isColumnSelected` required

* MLv2 Joins 4 — Multiple conditions (#32906)

* Implement multiple conditions

* Fix tests

* Remove irrelevant test

* Extract `JoinConditionRightPart`

* Fix temporal units sync for join columns

* MLv2 Joins 5 — Update condition UI (#32907)

* Add `removeCondition` to `useJoin`

* Sync `useJoinCondition` state

* Update join condition UI

* Improve a11y

* Tweak UI

* Fix color literal usage

* Update UI

* Fix read only mode (#32908)

* MLv2 Joins 7 — Fix notebook editor lifecycle issue (#32911)

* Allow keeping a step open on calling `updateQuery`

* Don't auto-close join notebook steps

* Make join steps open by default

* Remove join on table change

* Move open steps calc to `getInitialOpenSteps`

* Remove no longer relevant check

* Add a link to proper fix description

* Use MLv2 in `notebook/lib/steps`

* Update join's `isValid` check

* Remove redundant tests

* Remove more redundant tests

* Revert "Use MLv2 in `notebook/lib/steps`"

This reverts commit 24df2d7222.

* Revert "Revert "Use MLv2 in `notebook/lib/steps`""

This reverts commit 7b511fd053.

* Fix join revert

* Fix type imports linter errors

* MLv2 Joins 8 — Update tests (#32912)

* Use new test IDs

* Update test

Join suggested condition is smarter now and we don't need to manually construct a condition here

* Fix test

* Remove irrelevant test

The behavior used in the repro is removed

* Fix test

Section names used to be inconsistent — mixing singular and plural forms

* Fix test

* Fix fails because of FK name in column names

Normally it's expected to show FK reference names here

It seems like MLv1 just couldn't resolve it through metadata before

* Fix column name

* Fix `JoinStep` tests

* Fix missing FK reference name

* Fix columns highlighting for new condition

* Fix missing FK reference name

* Update E2E tests

MLv2 now figures out suggested conditions in a better way,
and we can skip the manual selection steps now

* MLv2 Joins 9 — Remove `externalOp` usage (#33526)

* Replace `JoinConditionExternalOp` type

* Add `joinConditionParts` helper

* Revert `externalOp` method type definitions

* Don't use `externalOp` for joins

* Fix deselecting all join fields

* Fix test

* Fix tests

* Remove most of MLv1 joins code (#33334)

* Remove join's `clean` method

* Remove join's `hasGaps` method

* Remove join's strategy methods

* Remove join fields method

* Remove join's `addEmptyDimensionsPair` method

* Remove join's `joinDimensionOptions` method

* Remove join's `setJoinSourceTableId` method

* Remove join's alias methods

* Remove join's `setOperator` method

* Remove join's `removeCondition` method

* Remove join's `setDefaultCondition` method

* Remove join's `parentDimensions` method

* Remove join's dimension setter methods

* Remove join's `parentDimensionOptions` method

* Remove join's `isMultipleConditionsJoin` method

* Remove join's `joinDimensions` method

* Clean up the `Join` class

* Remove query's `clearJoins` method

* Add `getQueryStageIndex` method

* Remove query's `hasJoins` method

* Remove query's `addJoin` method

* Mark query's `joinedDimensions` as deprecated

* Mark query's `joins` as deprecated

* Mark query's `join` as deprecated

* Remove join update methods

* Remove join removal methods

* Make `cleanJoins` private

* Remove `Join.unit.spec`

* Return `clearFields` join method

* Fix wrong references

* Revert "Remove join removal methods"

This reverts commit 9ae1e8c503d9b097d073836e7c6530282c6a64fa.

* Revert "Remove join update methods"

This reverts commit de232238bd266ed72a498d0afea3675e609cfae3.

* Mark join methods as deprecated

* Remove tests

* Fix bad reference

* Fix linter error

* Revert #32911 (#34407)

* MLv2 Joins — Disable RHS table changes (#34501)

* Disable RHS table change

* Don't highlight inactive join step cells

* Use `disabled` prop instead of custom styles

* Fix test

* Fix RHS column table names

* Fix column name label

* Don't suggest joining something by its implicitly joinable columns (#34538)

Fixes #34526.

---------

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>
2023-10-12 10:59:16 +01:00
Ngoc Khuat
315c90739a run with-temp in a transaction (#33738) 2023-10-12 09:42:44 +00:00
Kamil Mielnik
6e1cddd349 Sort scripts in package.json alphabetically (#34567)
* Sort scripts in package.json

* Sort scripts in release/package.json

* Fix a flaking test
2023-10-12 07:33:48 +00:00
lbrdnk
753c49ab57 Make implicit fields coming from source query expressions use string id (#34568)
* Update way source metadata are transformed to fields

`add-implicit-fields` now transforms expressions containing only field,
coming from source-query, to field with string id (aka name).
With use of numerical id, implicit field could have been added twice,
and because of that later discarded.

* Add test checking implicit expr field from source query
2023-10-12 09:20:16 +02:00
Nemanja Glumac
66e2bf630f Revert "Clean up yarn scripts" (#34588)
This commit reverts b19add2.
2023-10-12 08:40:06 +02:00
metamben
ef5d2ca452 Exclude summarize-column-by-time drill-thru for aggregate columns (#34456) 2023-10-12 01:29:25 +03:00
Nick Fitzpatrick
045107e76a re-initialize qb when navigating back (#34285)
* re-initialize qb when navigating back

* a gentler approach

* Moving describe block
2023-10-11 13:35:17 -03:00
lbrdnk
b17619123b Add lbrdnk into qpd team (#34504) 2023-10-11 13:52:25 +02:00
Alexander Solovyov
caded0ff26 report correct undefined parameters in dev log messages (#34516)
allowed-params should be keywords, because they are compared with keys in
a body map, which are keywords
2023-10-11 10:31:07 +00:00
Luis Paolini
d0cb6d6671 Update Apache POI (#34539)
* Update Apache POI

Let's see if this fixes https://github.com/metabase/metabase/issues/29839 without busting everything else

* Rework XLSX auto-sizing test to be more resilient

---------

Co-authored-by: Noah Moss <noahbmoss@gmail.com>
2023-10-11 07:28:54 -03:00
Luis Paolini
696115ecd7 Update webpack.config.js (#34543) 2023-10-11 07:27:52 -03:00
Nemanja Glumac
fb1c9d1eae Install dependencies before dev and dev-ee (#34560)
* Install dependencies before `dev` and `dev-ee`

Follow up after #34553.
[ci skip]

Co-authored-by: Uladzimir Havenchyk <125459446+uladzimirdev@users.noreply.github.com>
2023-10-11 11:55:40 +02:00
Nemanja Glumac
b19add2580 Clean up yarn scripts (#34553)
Remove `yarn &&` in front of every single script invocation.
Libraries should already be installed by the time one runs any of these scripts.

`yarn` is the equivalent of `yarn install`.
2023-10-11 10:08:33 +02:00
Nemanja Glumac
9727ad28fc Increase E2E tests running on Replayio frequency (#34555)
* Run E2E using ReplayIO daily

Increase the frequency from weekly to daily.
[ci skip]

* Use the latest replayio/action-upload version

[ci skip]
2023-10-11 09:36:07 +02:00
Nemanja Glumac
5cd80a0057 Use private ReplayIO API key (#34552) 2023-10-11 06:19:19 +00:00
Luis Paolini
c02773aad0 Run be tests on Java 21, and skip 19 altogether (#34470)
* Test Java 21

* Bring back Java 17

* Run Java 21 only on `master`

---------

Co-authored-by: Nemanja <31325167+nemanjaglumac@users.noreply.github.com>
2023-10-11 06:37:30 +02:00
shaun
d82ef1040e Add field selection to SmartScalar (#34420) 2023-10-10 19:59:29 -05:00
Cam Saul
6091adcab6 Fix #34505 (#34536) 2023-10-10 18:08:56 +00:00
Ryan Laurie
e2595bca0b Move some pre-release checks to build job from test job (#34454) 2023-10-10 10:44:15 -06:00
Cal Herries
be4e6cd046 Prevent dashboard parameter labels with identical slugs (#34369) 2023-10-10 19:38:18 +03:00
Nicolò Pretto
9a20401e6e add repro test for #26467 which has been already fixed with #28945 (#34502)
Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>
2023-10-10 17:58:18 +02:00
Nemanja Glumac
899ad8ab62 E2E isolate mongo (#34423)
* Tag Mongo-dependent E2E tests

* Run mongo tests only if `CYPRESS_QA_DB_MONGO` is `true`

* Adjust E2E workflow to run mongo tests separately

* Guard against missing mongo env var

* Fix workflow

* Fix qa snapshots

* Tag additional Mongo E2E tests

* Omit tests tagged with `@mongo` in regular runs
2023-10-10 09:51:11 -06:00
Kamil Mielnik
b984a4fb6f Refactor - reduce duplication in QueryBuilder unit tests (#34494)
* Extract changeNotebookQuery & revertNotebookQueryChange

* Extract changeNativeQuery

* Reuse changeNotebookQuery & revertNotebookQueryChange

* Move assertion to a util function

* Add missing spinner awaits

* Extract changeMetadata

* Rename changeX to triggerXChange
2023-10-10 14:02:29 +00:00
Jacob Joseph
cd20152b3f Update users-roles-privileges.md (#34509)
fixed syntax error re: predefined Postgres role pg_read_all_data that is only available in Postgres 14+
added reference link to Postgres docs re: predefined roles
added DATABASE grant option example
2023-10-10 14:00:03 +00:00
Kamil Mielnik
4fab29109a Show custom warning message when leaving editing model via Cancel button (#34487)
* Show a warning modal when clicking "Cancel" while editing a model with unsaved changes

* Add tests for cancel button when editing metadata

* Add tests for cancel button when editing query definition

* Update e2e test

* Update e2e tests

* Update code after merge

* Remove todo

* Inverse hasFieldWithoutDisplayName logic to everyFieldHasDisplayName
2023-10-10 13:39:35 +00:00
John Swanson
3a4e6b2b1c Excited to work with you all! :) 2023-10-10 06:35:40 -07:00
Cal Herries
72643952eb BE: Remove linked filters from dashboard if values source type is not "From connected fields" (#34424) 2023-10-10 13:57:42 +03:00
Oisin Coveney
423e00ce4d Split SearchResult components into separate files (#34466) 2023-10-10 13:25:12 +03:00
Ngoc Khuat
ba3b6ffaed Updates hawk to include supports #hawk/malli reader within =? (#34512) 2023-10-10 09:52:25 +00:00
Uladzimir Havenchyk
d52476e8c8 Combine linting fe jobs into one (#34359) 2023-10-10 12:25:09 +03:00
Ngoc Khuat
7c1d9647f0 defendpoint without redefine routes (#34513) 2023-10-10 09:07:41 +00:00
Cal Herries
c4812b4a3e Prevent empty dashboard parameter labels (#34358) 2023-10-09 13:55:01 +00:00
Kamil Mielnik
7f4d07a1d2 Introduce waitForLoaderToBeRemoved util (#34432)
* Introduce waitForLoadingSpinnerToDisappear

* Use waitForLoadingSpinnerToDisappear in QueryBuilder tests

* Use waitForLoadingSpinnerToDisappear in ObjectDetailWrapper tests

* Use waitForLoadingSpinnerToDisappear in DashboardApp tests

* Use waitForLoadingSpinnerToDisappear in ActionCreatorModal tests

* Use waitForLoadingSpinnerToDisappear in DatabaseEditApp tests

* Use waitForLoadingSpinnerToDisappear in MetricApp tests

* Use waitForLoadingSpinnerToDisappear in SegmentApp tests

* Use waitForLoadingSpinnerToDisappear in DatabasesPermissionsPage tests

* Use waitForLoadingSpinnerToDisappear in GroupsPermissionsPage tests

* Use waitForLoadingSpinnerToDisappear in PremiumEmbeddingLicensePage tests

* Use waitForLoadingSpinnerToDisappear in TableBrowser tests

* Use waitForLoadingSpinnerToDisappear in FieldValuesWidget tests

* Use waitForLoadingSpinnerToDisappear in DataPicker-Models tests

* Use waitForLoadingSpinnerToDisappear in DataPicker-Questions tests

* Use waitForLoadingSpinnerToDisappear in DataPicker-RawData tests

* Use waitForLoadingSpinnerToDisappear in ActionSidebar tests

* Use waitForLoadingSpinnerToDisappear in DashboardHeader tests

* Use waitForLoadingSpinnerToDisappear in SearchBar tests

* Use waitForLoadingSpinnerToDisappear in SearchResults tests

* Use waitForLoadingSpinnerToDisappear in SearchResultsDropdown tests

* Use waitForLoadingSpinnerToDisappear in MainNavbar tests

* Use waitForLoadingSpinnerToDisappear in Navbar tests

* Use waitForLoadingSpinnerToDisappear in PublicAction tests

* Use waitForLoadingSpinnerToDisappear in DefaultPicker tests

* Use waitForLoadingSpinnerToDisappear in TypeFilterContent tests

* Use waitForLoadingSpinnerToDisappear in SearchApp tests

* Replace waitForElementToBeRemoved(() => screen.queryByText("Loading...")) with waitForLoadingSpinnerToDisappear();

* Replace waitForElementToBeRemoved(() => screen.queryByText(/loading/)) with waitForLoadingSpinnerToDisappear();

* Remove all remaining waitForElementToBeRemoved usages

* Replace all spinner queries by text with queries by test-id

* Make spinner existence assertions consistent

* Consolidate imports

* Connect comment to code

* Add explanatory comment

* Rename waitForLoadingSpinnerToDisappear to waitForLoaderToBeRemoved
2023-10-09 13:42:19 +00:00
Tim Macdonald
680741aa70 Bump clj-kondo to 2023.09.07 (#34489) 2023-10-09 13:35:39 +00:00
Ryan Laurie
baf0bb65a9 Make broken branch notification less obnoxious (#34452) 2023-10-09 07:32:45 -06:00
Ryan Laurie
8a30a8bff0 Fix docs update trigger (#34459) 2023-10-09 07:32:13 -06:00
Oisin Coveney
79ebd09007 Convert ModeratedStatusIcon to typescript (#34464)
Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>
2023-10-09 15:37:16 +03:00
Luis Paolini
a5a3998d0c Fix 25638 spinners change color (#34473)
* Reverting 18238

* Additional tweaks

---------

Co-authored-by: Luis <luis@pop-os.localdomain>
2023-10-09 13:18:06 +02:00
Uladzimir Havenchyk
914bce8935 [Dashboard] Do not lose filters state on navigating back from Question (#34399) 2023-10-09 11:08:18 +00:00
Nemanja Glumac
540e9f8b87 Exclude team.json from CI triggers in file paths (#34488)
Check results in [this test tool](https://www.digitalocean.com/community/tools/glob?comments=true&glob=.github%2F%2A%2A%2F%21%28%2A.md%7Cteam.json%29&matches=false&tests=.github%2Fteam.json&tests=.github%2Ffoo%2Fteam.json&tests=.github%2Ffoo%2Fpotato.json&tests=.github%2Ffoo%2Fbar.md&tests=.github%2Ffoo.md&tests=.github%2Fworkflow.yml&tests=.github%2Ffoo%2Fworkflow.yml) that confirm the glob used here is correct.

[ci skip]
2023-10-09 12:49:03 +02:00
Kamil Mielnik
a24acdd2ee Refactor confirmation modal assertions (#34484)
* Add data-testid to LeaveConfirmationModal

* Update LeaveConfirmationModal assertions in QueryBuilder unit tests to use data-testid

* Update LeaveConfirmationModal assertions in DashboardApp unit tests to use data-testid

* Update LeaveConfirmationModal assertions in SegmentApp unit tests to use data-testid

* Update LeaveConfirmationModal assertions in MetricApp unit tests to use data-testid

* Update LeaveConfirmationModal assertions in DashboardEditApp unit tests to use data-testid

* Update LeaveConfirmationModal assertions in ActionCreatorModal unit tests to use data-testid

* Extract LeaveConfirmation component

* Add data-testid prop to ConfirmContent

* Replace cancel-leave-confirmation-modal with leave-confirmation

* Rename LeaveConfirmation to LeaveConfirmationModalContent and move it to LeaveConfirmationModal directory

* Replace leave-confirmation-modal with leave-confirmation
2023-10-09 17:34:45 +07:00
Alexander Solovyov
3016bb0f96 Add Alexander Solovyov to the team.json (#34485)
[ci skip]
2023-10-09 12:27:48 +02:00
Ryan Kienstra
06f4647aad Add tests for api endpoints: timeline-event, search (#34072)
* Add a unit test for /api/pulse/preview_card_info/:id

For the GET endpoint
/api/pulse/preview_card_info/:id

* Add a unit test for the GET endpoint /search/models

* Add a unit test for DELETE /api/timeline-event/:id

* Add a unit test for DELETE /api/timeline-event/:id

* Commit Ngoc's suggestion: Update test/metabase/api/timeline_event_test.clj

Co-authored-by: Ngoc Khuat <qn.khuat@gmail.com>

* Apply Ngoc's suggestion to destructure :timeline_id

* Remove test for event that I created in with-temp

* Fix failed test I introduced, change collection to collection-id

* Test deleting a non-existent timeline event by id

* Move my search-models-test lower

* Copy-paste Ngoc's query-model-set-test and macro

https://github.com/metabase/metabase/pull/32624/files#diff-734923de9c62f49d6b708d64a214ee38d7d0fb1b2c20343bff7b947a6021b021R297-R332

https://github.com/metabase/metabase/pull/32624/files#diff-54344d8b75319d40a4cb2a2afe935500c23d34f0f3c63c51f005493d4dc4f8f1R690-R732

* Remove "database" and "table" from test expectation

Those failed in this PR,
though they passed in 32624

* Revert test for pulse/preview_card_info/, as it'll be removed

* Remove with-verified-cards, which I needlessly copied into this PR

That's needed in 32624,
but not this PR.

* Add a test for the archived-string param

---------

Co-authored-by: Ngoc Khuat <qn.khuat@gmail.com>
2023-10-09 11:37:44 +02:00
Nemanja Glumac
bc7bd10269 Bump Mongo used in driver tests to v4.4 (#34434) 2023-10-08 22:08:59 +02:00
Cam Saul
d9301a1767 Add missing models to copy command (#34412) 2023-10-06 18:26:56 -07:00
Alexander Polyankin
e1ebf6003f Mantine Divider (#34392) 2023-10-06 21:08:27 +00:00
Ryan Laurie
a5a8df92d2 improve table-column-settings test performance (#34442) 2023-10-06 12:41:15 -06:00
Nemanja Glumac
296f5ffcee Improve E2E matrix generation and simplify job conditionals (#34444) 2023-10-06 20:24:56 +02:00
Denis Berezin
8f87659cb0 [33482] Add more unit tests for all implemented drills (#33974)
* Add more drills tests, unify tests structure, add issues refs

* Add tests for fk-details drill apply

* Tests fixes after merge with master

* Code review fixes

* Comment failing tests after merging with master

* Restore sort drill tests
2023-10-06 18:14:18 +00:00
Emmad Usmani
d9aa16e2c6 Mantine Switch (#34005)
* wip

* Add comma and fix spelling error

* Added some padding and things

* switch control styles

* text styles

* add storybook examples

* Add guidance text

* Add top padding for small switches

* change default size from `sm` to `md`

* fix missing default `size` prop

* fix paddings

* remove label padding if empty

* use `getStylesRef`

---------

Co-authored-by: Oisin Coveney <oisin@metabase.com>
Co-authored-by: Maz Ameli <maz@metabase.com>
2023-10-06 17:50:51 +00:00
Cam Saul
bfd51fd328 Sort drill thrus should come back for aggregate columns (#34389) 2023-10-06 18:49:11 +03:00
Braden Shepherdson
682215fd3f Hack to fix webpack serving stale CLJS on browser refresh (#34381)
### Background

CLJS output is not watched by webpack. (Watching it causes full page reloads I can't find a way to stop.)
CLJS changes are hot reloaded by shadow-cljs separate from webpack.

Changing CLJS code works great: shadow-cljs hot reloads it and it works nicely.

Changing JS code also works: webpack recompiles (including the latest CLJS output), the browser refreshes, and all is
well.

### The Problem

If you refresh the browser after you've changed only CLJS code, webpack does not know it must recompile the bundles.
Therefore it serves up the old bundles, which have now-stale CLJS output in them.

### The "Solution"

The first time shadow-cljs hot reloads after a CLJS change, a hook in `metabase.util.devtools` registers a
`beforeunload` handler. This handler sends a request to `http://localhost:8080/webpack-dev-server/invalidate`, forcing
webpack to recompile the bundles.

That isn't such a terrible hack by itself. The ugly part is that there's a race
condition between webpack invalidating the bundles and the browser trying to
load the bundles after the refresh, and sometimes the browser wins (loading the
stale CLJS). I added a spin-lock, repeatedly checking `performance.now()` until
500ms have passed, then the handler returns. This small delay gives webpack
time to mark the bundles invalid and allow the refresh.

I haven't experimented with how long that delay needs to be for this to be
reliable. Since this handler is only attached after CLJS code has been hot
reloaded, it will never run for most FE devs.

### Alternative: Smarter webpack

The best solution would be to make webpack
- recompile the bundles when the CLJS output changes; but
- not try to HMR them (which triggers a browser refresh and ruins CLJS hot reloading)
but I have not found any way to configure this out of the box. I think it would require patching `ReactRefreshPlugin`,
a nontrivial job. It might also be possible for shadow-cljs to poke webpack after it finishes building, but there's the
same problem that webpack will want to HMR.

Webpack doesn't support any "lazy" invalidation; as far as I know there's no
way to say "this bundle is now invalid but don't recompile it until someone
tries to GET it" or anything like that.

### Alternative: Block refresh then continue

The `beforeunload` handler could instead work like this:
- `preventDefault()` on the event, stopping the refresh.
- `fetch()` the `invalidate` route as above.
- asynchronously, when that `fetch()` is done and we know webpack has invalidated the bundles, trigger a refresh.

I haven't tried this, since it seems more complicated than the spin-lock. We just need to give the `invalidate` request
a head start.
2023-10-06 11:12:10 -04:00
Case Nelson
86394513c3 [MLv2] Fix boolean operators for Category typed fields (#34331) 2023-10-06 08:45:14 -06:00
Case Nelson
c279053a82 [MLv2] Support invisible columns with expression-parts (#34371) 2023-10-06 08:45:03 -06:00
Nemanja Glumac
ea17aa7852 Parameterize E2E matrix (#34431) 2023-10-06 16:41:52 +02:00
Tim Macdonald
009000e5dc Minor updates to the developer's guide (#34436)
* Minor updates to the developer's guide

* extra context

---------

Co-authored-by: dan sutton <dan@dpsutton.com>
2023-10-06 09:40:20 -05:00
Nemanja Glumac
0f54f772ed Remove and disallow H2 from E2E tests (#34364)
* Make it easy to add SQLite database

* Replace H2 with SQLite in E2E tests

* Remove long unused E2E reproduction

It's been sufficiently covered with backend tests.

* Remove H2 database helper from E2E tests
2023-10-06 15:40:04 +03:00
Kamil Mielnik
23453f57e2 Show custom warning message when leaving editing dashboard via Cancel button (#34405)
* Show a warning modal when clicking "Cancel" in dashboard

* Update dashboard test

* Update question settings test

* Add missing "Edit dashboard" click

* Add tests for leaving dashboard editing via Cancel button
2023-10-06 19:37:59 +07:00
Kamil Mielnik
d7576fc89e Add custom warning message when leaving editing a model (query definition or metadata) (#34316)
* Add model-editing logic to isLocationAllowed in QueryBuilder

* Fix IS_LOCATION_ALLOWED implementation

* Fix typos

* Remove redundant checks and invert logic for better readability

* Add editing queries tests

* Improve test to include reverted form interaction

* Fix existing test case

* Add editing metadata test

* Add editing metadata test (unedited)

* Organize tests

* Add a test for not showing custom warning modal when saving edited query

* Extract slug to TEST_MODEL_CARD_SLUG

* Add a test for not showing custom warning modal when saving edited metadata

* Remove redundant routing

* Add a workaround for test setup

* Add a test for tabs navigation

* Fix failing test

* Extract isNavigationAllowed out of isLocationAllowed

* Extract createMockLocation

* Add isNavigationAllowed test setup and test for new questions

* Add a test case for beforeunload event

* Format code

* Add more tests and organize them

* Add notebook question tests

* Format code
2023-10-06 11:00:20 +00:00
Kamil Mielnik
d29867e084 Add custom warning message when leaving changing Data Model (segments and metrics) (#34398)
* Rename component to match the filename

* Fix typo

* Replace useBeforeUnload with LeaveConfirmationModal in SegmentForm

* Replace useBeforeUnload with LeaveConfirmationModal in MetricForm

* Update setup of MetricForm tests to allow testing navigation

* Update setup of SegmentForm tests to allow testing navigation

* Use proper history in MetricForm

* Refactor SegmentForm test setup to be consistent with the one of MetricForm

* Make MetricForm and SegmentForm tests consistent

* Add tests for not showing custom warning

* Add tests for showing custom warning when leaving with unsaved changes

* Extract FORM_URL

* Remove redundant asyncs and awaits

* Rename MetricForm.unit.spec.tsx & SegmentForm.unit.spec.tsx to MetricApp.unit.spec.tsx & SegmentApp.unit.spec.tsx and move them near the components they're testing

* Improve a11y

* Add missing endpoint mocks

* Improve selectors thanks to proper a11y

* Add tests for not showing warning modal when saving changes

* Convert CreateMetricForm to a functional component

* Convert CreateSegmentForm to a functional component

* Convert UpdateMetricFormInner to a functional component

* Convert UpdateSegmentFormInner to a functional component

* Disable LeaveConfirmationModal on scheduled navigation

* Setup metrics & segments POST endpoints

* Properly mock metric and segment creation

* Lift LeaveConfirmationModal from SegmentForm to SegmentApp

* Lift LeaveConfirmationModal from MetricForm to MetricApp

* Sort props

* Get rid of useCallbackEffect usage in MetricApp

* Get rid of useCallbackEffect usage in SegmentApp
2023-10-06 10:33:47 +00:00
Uladzimir Havenchyk
20c6fcccff [jest] Add global catch for unmocked http requests (#34277) 2023-10-06 09:41:06 +00:00
metamben
b0cd79dea8 Remove dependent joins from subsequent stages too (#34416) 2023-10-06 01:14:03 +03:00
metamben
c70fc0d42d Update Liquibase to 4.21.1 (#33891) 2023-10-05 21:42:19 +00:00
Ryan Laurie
ad5da72d75 Convert collection permissions to typescript and add unit tests (#34186) 2023-10-05 13:22:44 +00:00
Ngoc Khuat
b14e033cab Remove most of metabase.util.schema (#34208) 2023-10-05 10:34:02 +00:00
Cal Herries
976f96bbcb Fix corrupted dashboard parameters to have "unnamed" names and slugs (#34311) 2023-10-05 10:15:50 +03:00
metamben
745c0c9463 Read the latest version of the secret from the DB (#34335) 2023-10-05 02:19:52 +03:00
metamben
a597d5ef2f Enable expression dashboard filters (#34262) 2023-10-05 02:19:04 +03:00
Cam Saul
24b3553472 Implement #33646 (#33865)
* Implement #33646

* More dox

* Seconds, not milliseconds

* Respect env var values
2023-10-04 19:12:14 +00:00
Danilo Campana Fuchs
b526a2ac86 fix: Correct cache control for static js/css files (#34171) 2023-10-04 20:57:19 +02:00
Cam Saul
a511a62ea1 drill-thru-method for sort drill thrus should handle string directions (#34352) 2023-10-04 18:42:58 +00:00
Cam Saul
171d3d2d9e Consider drill thru :dimensions when calculating available-drill-thrus (#34347) 2023-10-04 18:33:36 +00:00
Alexander Polyankin
52d9eec9a0 Fix Select CSP errors (#34365) 2023-10-04 16:05:50 +00:00
Alexander Polyankin
6c99f746d5 Mantine Textarea (#34136) 2023-10-04 14:02:02 +00:00
Alexander Polyankin
d8d630f3b1 Mantine FileInput (#34117) 2023-10-04 10:10:03 +00:00
Nemanja Glumac
927c4894a0 Fix broken metrics test (#34357)
I broke tests on master with the following change:
0d77aba#diff-205d5528aa8f03902903027631d50ef76459835737fb06b16e55fdd1d7430c8eL331

Relevant failure: https://www.deploysentinel.com/ci/runs/651d290ef6799f2563b8b986

This PR brings it back.
2023-10-04 11:59:20 +02:00
Uladzimir Havenchyk
8f900e6107 Do not run frontend workflolw when label is added or removed (#34307) 2023-10-04 12:20:12 +03:00
Nemanja Glumac
80ee48bfe0 Remove delete-file! function (#34306)
It was deprecated and left in a codebase for backwards compatibility.
But it seems we've migrated all references to the new method `delete-file-if-exists`.

The last time this was touched was three years ago.
Should be safe to remove.
2023-10-04 10:28:37 +02:00
Nemanja Glumac
f25d5b1539 [E2E] Fix segment flake (#34329)
* Fix the flakes for metrics as well
2023-10-04 09:09:35 +02:00
Cam Saul
8224e5b615 Misc drill thru fixes 🔧 (#34231) 2023-10-03 14:38:16 -07:00
Jacob Joseph
09e3777a47 Update expressions-list.md (#34263)
added an example of rounding with a decimal place
2023-10-03 15:00:04 -04:00
Ryan Laurie
6215bb1ced Fix download bucket variable in release notes generation (#34328) 2023-10-03 19:23:09 +02:00
Braden Shepherdson
21a70290ae Fix yarn dev-ee with new CLJS setup (#34319)
`yarn dev` had been adjusted to use `build-hot:js-wait` (which waits for the first CLJS compilation to be done), but `yarn dev-ee` had not been changed, so its JS compilation ran too early, failed, and never re-ran.

We actually had this broken behavior (JS build runs too early, CLJS build completes, JS build fails, JS build notices new inputs and re-runs) for a long time. But since it fixed itself when the JS build re-ran, it didn't cause any issues. Now that the JS build no longer watches the CLJS output for changes, the CLJS output needs to be there for the first JS build.
2023-10-03 19:02:40 +02:00
Tim Macdonald
81a0efd58d Use HTTPS when getting version-info (#34310) 2023-10-03 13:10:12 +00:00
Ibe Dwi
bdbbb61d57 Add color to ExpandButton when moving collection (#33846)
* fix: add ExpandButton color on parent's hover

* fix: icon's color by canSelect, remove !important

* feat: update expand button style on canSelect props

* fix: icon button color when hovered
2023-10-03 19:12:07 +07:00
Anton Kulyk
3715839c15 Add more E2E tests around joins (#34252)
* Test using columns from joined tables or cards

* Test multi stage joins

* Test removal on source table change

* Test RHS table column selection

* Reduce flakiness?

* Fix test

* Reduce flakiness?
2023-10-03 11:33:12 +01:00
Kamil Mielnik
124a6a3d72 Add custom warning message when leaving creating/editing a DB connection (#34272)
* Use LeaveConfirmationModal in QueryBuilder

* Add isLocationAllowed prop to LeaveConfirmationModal

* Do not route-block running modified native question

* Fix typo

* Introduce explanatory variables

* Move updating URL during question creation to QueryBuilder

* Schedule navigation to after re-render so that LeaveConfirmationModal prop has a chance to update

* Add a test for unsaved changes warning

* Introduce useCallbackEffect

* Refactor QueryBuilder to use useCallbackEffect

* Refactor ActionCreator to use useCallbackEffect

* Fix useCallbackEffect typing

* Move onSubmit out of the scheduled callback to reduce probability of race conditions

* Add comments explaining useCallbackEffect usage

* Improve JSDocs

* Add a test for running modified question

* Update button query to more accessible one

* Add a test for saving a modified question

* Update test names

* Add a test for leaving with no changes

* Remove isDirty-related no-change assertions, as isDirty flag does not work reliably
- Question.prototype.isDirtyComparedTo would return true because edited "question"
  would have extra "description: null" attribute and no "name" compared to
  "originalQuestion" (see "getIsDirty")

* Move useCallbackEffect to its own directory

* Add test setup for useCallbackEffect

* Add a test case for scheduling

* Add a test for scheduling callback effect

* Do not disable navigation in models
- this is a temporary condition until #33793 is implemented

* Remove redundant _.noop

* Rename isScheduled to isCallbackScheduled

* Replace useBeforeUnload with LeaveConfirmationModal in DatabaseEditApp

* Refactor DatabaseEditApp.unit.spec.js to TypeScript

* Add initialRoute param, return history & add /home route

* Add a test case for showing the unsaved changes modal

* Add a test case for not showing the unsaved changes modal

* Format code

* Extend a test case to assert isDirty being properly computed

* Remove redundant route

* Remove redundant code

* Add a test for custom warning modal when saving edited question as a new one

* Redirect to databases page on database creation in component so that isDirty flag can re-compute on re-render

* Fix mocks setup

* Remove redundant withRouter usage

* Use waitFor + expect + not.toBeInDocument instead waitForElementToBeRemoved

* Add a test case for creating new database connection

* Remove redundant promise
2023-10-03 10:28:24 +00:00
Cal Herries
69ca1a0a9c Fix action parameter types not saving correctly (#undefined) 2023-10-03 06:37:58 +00:00
Nemanja Glumac
92312aba69 Remove unused collection color column (#34239) 2023-10-03 06:53:47 +02:00
Aleksandr Lesnenko
65373df63b fix Arabic translations (#34295) 2023-10-03 04:46:01 +00:00
Ryan Laurie
15f82914fc Automated Releases from CI 🚀 (#33938) 2023-10-02 17:16:28 -06:00
Braden Shepherdson
8e298158a4 Enable ClojureScript REPL and hot reloading of CLJS code (#34007)
This also moves the CLJS output out of `frontend/src/cljs{,_release}` to
`target/cljs_{dev,release}`. If that causes problems for FE tooling I
don't know about, it could be moved back.

Hot reloading:
CLJS changes are hot-reloaded into the running app by Shadow CLJS - no
action is needed. Note that the UI will not refresh; you usually have to
click around so the updated MLv2 code gets executed.

Usage of the CLJS REPL:
- Open the browser (you should see `shadow-cljs: #N ready!` in console)
- Connect to nrepl on 50655
- "Select" the `:app` build;
    - https://shadow-cljs.github.io/docs/UsersGuide.html#_editor_integration
    - Conjure: `:ConjureShadowSelect app`
    - Plain REPL: Eval in CLJ mode `(shadow/repl :app)`
- Consider running `yarn build-hot:cljs` and `yarn build-hot:js` in
  separate terminals; then when `yarn build-hot:js` crashes you don't
  have to reconnect your REPL.
- The REPL works beautifully, even loading files outside the :entries
  of the shadow-cljs build like tests!

"Stale" error in browser:
- This can happen if the webpack bundle is created before the CLJS is
  done building.
- If you ran `yarn build-hot:cljs` and `:js` separately, let `:cljs`
  finish compiling first.
- If you see this otherwise: (a) contact Braden so it can be fixed; and
  (b) either restart `build-hot:js` or force webpack to rebuild by
  hitting http://localhost:8080/webpack-dev-server/invalidate

Yarn commands:
`dev`, `dev-ee`, `build-hot`, and `build-static-viz:watch` all now wait
for the CLJS build to be complete by watching for files to be generated.
They should work the same from a user's POV.

(Since the webpack build no longer watches the CLJS output,
it won't notice the changes and immediately rebuild after the first
build. This avoids errors on the clean build, or "stale build" messages
in the app from Shadow CLJS.)

Fixes #32674.
2023-10-02 21:52:15 +00:00
Uladzimir Havenchyk
89729a8d40 Drop unused typings (#33851) 2023-10-02 17:30:18 +00:00
Cal Herries
2e9a28ede8 Remove extra driver/execute-write-query! sql-jdbc implementation (#34216) 2023-10-02 20:09:30 +03:00
Uladzimir Havenchyk
6ba4d78b61 [jest] Move builtin plugins to specific specs (#34167) 2023-10-02 15:49:33 +00:00
Jeff Bruemmer
97b9af4dd1 docs - note experimental feature (#34181) 2023-10-02 15:12:45 +00:00
Alexander Polyankin
77620a0e23 Handle mismatching date parameters in dashboard -> native question drills (#34270) 2023-10-02 18:01:48 +03:00
Anton Kulyk
c0d707e34a Clean up join E2E tests (#34253)
* Add `dashboardGrid` E2E helper

* Add test ID for x-ray dashboard header

* Extract 14793 repro to its own file

* Extract 15578 repro to its own file

* Remove duplicate 17968 repro

* Clean up 17968 repro

* Clean up test

* Clean up test

* Clean up test

* Clean up test

* Clean up test

* Clean up test

* Sort imports

* Use shared helpers for join tests

* Extract 12928 repro to its own file

* Minor renames

* Fix `join` e2e helper

* Fix `assertQueryBuilderRowCount` for count > 1000

* Make table check optional in `assertJoinValid`

* Clean up test

* Fix `join` helper

* Fix 17968 test

* Fix 30058 and 32075 tests

* Reduce flakiness?
2023-10-02 15:44:41 +01:00
Uladzimir Havenchyk
d654c0cf90 Fix tests wtih unmocked http requests (#34217) 2023-10-02 17:20:20 +03:00
Kamil Mielnik
f7bf023460 Add custom warning message when leaving editing an existing SQL question (#34084)
* Use LeaveConfirmationModal in QueryBuilder

* Add isLocationAllowed prop to LeaveConfirmationModal

* Do not route-block running modified native question

* Fix typo

* Introduce explanatory variables

* Move updating URL during question creation to QueryBuilder

* Schedule navigation to after re-render so that LeaveConfirmationModal prop has a chance to update

* Add a test for unsaved changes warning

* Introduce useCallbackEffect

* Refactor QueryBuilder to use useCallbackEffect

* Refactor ActionCreator to use useCallbackEffect

* Fix useCallbackEffect typing

* Move onSubmit out of the scheduled callback to reduce probability of race conditions

* Add comments explaining useCallbackEffect usage

* Improve JSDocs

* Add a test for running modified question

* Update button query to more accessible one

* Add a test for saving a modified question

* Update test names

* Add a test for leaving with no changes

* Remove isDirty-related no-change assertions, as isDirty flag does not work reliably
- Question.prototype.isDirtyComparedTo would return true because edited "question"
  would have extra "description: null" attribute and no "name" compared to
  "originalQuestion" (see "getIsDirty")

* Move useCallbackEffect to its own directory

* Add test setup for useCallbackEffect

* Add a test case for scheduling

* Add a test for scheduling callback effect

* Do not disable navigation in models
- this is a temporary condition until #33793 is implemented

* Remove redundant _.noop

* Rename isScheduled to isCallbackScheduled

* Remove redundant route

* Remove redundant code

* Add a test for custom warning modal when saving edited question as a new one
2023-10-02 14:13:50 +00:00
Braden Shepherdson
86f405a060 [MLv2] Allow any type of arguments to :concat expressions (#34157)
The QP supports this - it appears that every type can be `concat`-ed and
it will coerce the values to some kind of string - numbers, dates,
booleans, etc.
2023-10-02 09:51:45 -04:00
Anton Kulyk
bca9d35fac Migrate notebook's data step to MLv2 (#34256)
* Add `displayInfo` types for cards and tables

* Add TypeScript wrapper for `withDifferentTable`

* Move fields tests under their own `describe`

* Clean up the fields picker

* Add extra test coverage

* Fix missing import

* Fix type

* Migrate `DataStep` to MLv2 (mostly)

* Fix creating a new query
2023-10-02 14:27:20 +01:00
Case Nelson
354f152e11 [MLv2] Add short-name to temporal-bucket display-info (#34225) 2023-09-29 23:38:41 +02:00
Nemanja Glumac
c13328df2f Optimize changed files check for the backend.yml workflow (#34209)
Before
1. prepare-frontend
2. prepare-backend
3. build-static-viz
4. files-changed-check
5. static-viz-files-changed-check

So, we're doing all these expensive operations before the step 4, even though they might not even be necessary.
If files changed already outputs backend_all, this means we have to run these tests whether or not there were static-viz changes.

After
1. test which files changed
    - if backend_all output -> skip static-viz-bundle and start running tests straight away
    - else if there are no direct backend changes, have an additional check for static-viz
2. static-viz-files-changed
    - if true -> run tests
    - else -> skip tests
2023-09-29 23:30:31 +02:00
Mark Bastian
92faa8e206 This is a small set of changes pulled from another PR whose contents (#34228)
probably won't be merged. The intent of these changes is to be
explicit in what is passed into each of the card creation functions,
ensure consistency of types, and eliminate redundant or non-required
arguments.

`build-dashcard` was the target of this simplification. The
`available-values` argument is no longer necessary as that data is
sourced from other arguments. the `satisfied-*` arguments are no
longer seqs of satisfied filter, metric, and dimension definitions,
but maps of names of those items to the definitions. This is only
needed because satisfied metrics needs metrics names when adding
metadata. However, all values were modified into a consistent shape.

In other areas, if an aggregate object with several keys is passed
to a function that uses only one element of the object, only the
inner element is passed.

In card-candidates, `:matches` is dissoced from `satisfied-dimensions`
to remove the extra payload that isn't needed in that argument.
This makes it clear that satisfied field values are passed into card
creation functions via the `satisfied-bindings` and not cruft from
earlier stage.

As an aside, one potential fix that would substantially improve the
readibility of this entire codebase would be to move the element
names in the one key to value maps as is done for dimensions,
metrics, filters, and cards into the elements as a named key.
Carrying that shape forward from the yaml files requires a ton of
first this or zipmap that to recover the names into whatever the
current context is.
2023-09-29 23:02:51 +02:00
Denis Berezin
6e5b6a7b72 Fix flaky ActionViz unit tests (#34250) 2023-09-29 16:44:06 +03:00
Mahatthana (Kelvin) Nomsawadi
7035559764 Fix overlapping x-tick labels on static viz timeseries charts (#33707)
* Fix overlapping x-tick labels on static viz timeseries charts

* Address review: make the condition easier to understand + fix failed cases

* Update frontend/src/metabase/static-viz/components/XYChart/utils/ticks.ts

Co-authored-by: Jesse Devaney <22608765+JesseSDevaney@users.noreply.github.com>

* Add a comment to explain why we have to fix timeseries ticks

---------

Co-authored-by: Jesse Devaney <22608765+JesseSDevaney@users.noreply.github.com>
2023-09-29 14:03:15 +01:00
Roman Abdulmanov
4224bbeac8 fixed & symbol escaping (#34243) 2023-09-29 13:46:54 +01:00
Kamil Mielnik
5c2279d4d7 Add custom warning message when leaving creating/editing a query action in model details page (#34192)
* Replace useBeforeUnload with LeaveConfirmationModal in ActionCreator

* Take action name and action settings changes into account when computing isDirty

* Improve action name change detection

* Rename handleFormSettingsChange to patchFormSettings

* Rename handleActionChange to patchAction

* Introduce a way to sync initial action state after creation/update

* Sync initial action state after creation/update

* Add a hack for re-rendering

* Revert "fixing" isDirty flag

* Replace delay hack with an effect

* Improve ActionCreatorModal setup
- use actual component, not the mock
- move waiting for spinner outside of setup, as it is initialRoute-dependent
- ensure history object is always present
- add missing setupDatabaseEndpoints call

* Add a test for showing custom unsaved changes warning modal

* Update default mock query action's visualization_settings

* Add a test for not showing custom unsaved changes warning modal

* Fix isDirty flag evaluation

* Group similar tests

* Add tests for creating new action

* Remove redundant spread

* Use local action

* Fix typo

* Add a test for updating an action

* Add a test for creating an action

* Fix a flake

* Add missing router in tests setup

* Enable LeaveConfirmationModal only in ActionCreatorModal with a dedicated route
- see action-related edge cases in https://github.com/metabase/metabase/issues/34114

* Fix flaking test by waiting for modal to close

* Make assertion consistent

* Fix flaky unit tests

* Refactor isDirty computation

* Add a way to skip unsaved changes warning when submitting the modal

* Remove setAction

* Bring back old logic

* Undo rename

* Update comment

* Update comment

* Add areActionsEqual to deal with redundant "value" attribute of action parameter

* Omit "hasVariableTemplateTagTarget", compute visualization settings diff based on form state

* Revert unnecessary change

* Revert unnecessary change

* Rename getActionCrudParameters to getCleanParameters

* Revert unnecessary change

* Revert unnecessary change

* Simplify isDirty computation with Question.prototype.isDirtyComparedTo

* Revert leftover code

* Remove duplicated assertion

* Update test to detect correctness of isDirty flag when user reverts changes
2023-09-29 09:48:24 +00:00
Nemanja Glumac
85dbd9aced Add :dataset to the POST /api/card endpoint (#34218)
Depending on this key's value, we might either create a model when saving a card, or not.

It already exists in some tests and in the `create-card!` function but it was never explicitly defined in this endpoint.
That is a shame because we generate API documentation based on these keys.
2023-09-29 10:22:31 +02:00
Cam Saul
d239ca8256 Hardcode Vertica DB default timezone to UTC, don't use session timezone (#34234) 2023-09-29 10:21:07 +02:00
Nemanja Glumac
6927d396b6 Add initial unit test coverage for ColorRangeToggle (#34124)
* Add unit tests for `ColorRangeSelector` toggle button

* Refactor tests

* Test click handlers

* Test label utility
2023-09-29 00:25:14 +02:00
Nemanja Glumac
4302573698 Fix typo in malli schema dosctring (#34215)
[ci skip]
2023-09-28 17:08:40 +02:00
Ryan Laurie
eaa7620bf8 Stop publishing elastic beanstalk artifacts (#34065) 2023-09-28 08:58:36 -06:00
Nemanja Glumac
3138343a5a Fix codeql conditional run check (#34212)
This workflow was always running, even though we had a files-check step all along.

[ci skip]
2023-09-28 15:29:44 +02:00
Jacob Joseph
400a820b03 Update introduction.md (#34189)
Changed "Signed" to "Static" re: embedding renaming
2023-09-28 10:28:43 +00:00
Uladzimir Havenchyk
78aedc0a57 Move register-visualization from global setup (#34133) 2023-09-28 12:57:55 +03:00
Nemanja Glumac
6dbeae9091 Automatically re-run failed backports (#34193) 2023-09-28 10:00:41 +02:00
Mahatthana (Kelvin) Nomsawadi
c42bdf89c8 Remove time-series grouping widget for custom date breakout (#33810)
* Remove unsupported timeseries grouping on expression dimension

* Add unit tests

* Update frontend/src/metabase/query_builder/containers/QueryBuilder.unit.spec.tsx

Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>

* Update frontend/src/metabase/query_builder/containers/QueryBuilder.unit.spec.tsx

Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>

* Rename a test ID to make it more consistent with the component name

* Fix the code that broke other E2E tests

* Fix failed test from merging master

* Another attempt to fix this

* Fix type error

* Make the code easier to read by eliminating double negation

---------

Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>
2023-09-28 07:43:45 +01:00
Case Nelson
892368e550 [MLv2] Unblock filter work (#34153)
Co-authored-by: Alexander Polyankin <alexander.polyankin@metabase.com>
2023-09-27 23:07:30 +00:00
Nemanja Glumac
53f7cb43e9 Upgrade Percy CLI to the latest v1.27.2 (#34176) 2023-09-27 21:57:05 +00:00
Nemanja Glumac
148cf80164 [E2E] Fix #22859 reproduction flake (#34178) 2023-09-27 23:55:36 +02:00
Nemanja Glumac
b5071fa079 Fix Chrome version in stress-test-flake workflow (#34180) 2023-09-27 21:33:00 +00:00
Jeff Bruemmer
8a368c2200 update further reading (#34104) 2023-09-27 16:35:33 -04:00
Jeff Bruemmer
8470248f2c docs - x-ray updates (#34170)
* x-ray updates

* remove image link
2023-09-27 16:35:16 -04:00
Ryan Laurie
0e310101a6 [Auditv2] e2e test fixes (for master) (#34066) 2023-09-27 13:34:32 -06:00
Uladzimir Havenchyk
3a0346c39c Move getIsNavbarOpen to selectors file to get rid of circular deps (#34163) 2023-09-27 21:28:17 +03:00
Case Nelson
7b945e4001 Sync should handle multiple columns with same name (#34098)
Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>
2023-09-27 11:01:17 -06:00
Denis Berezin
3d45def8ca Fix duplicated entities api calls with better cache check (#33898)
* Fix duplicated api call with better cache check

* Fix issues with e2e

* Fix e2e tests

* Simplify solution

* Add entities loader fetch requests queue

* Refactor waiting for loaded state to await for promise

* Fix e2e test

* Fix unit tests
2023-09-27 16:20:00 +03:00
Ngoc Khuat
a7c9441899 Remove toucan1 (#31388) 2023-09-27 18:14:07 +07:00
Uladzimir Havenchyk
55dbe7b2b1 Fix memoization on the table cell (#34093) 2023-09-27 10:55:17 +00:00
Alexander Polyankin
bfe1714ba8 Mantine Card (#34113) 2023-09-27 11:28:09 +03:00
Cal Herries
22eb69802f Add test for "MySQL databases with short system_time_zone IDs cannot sync" (#34055) 2023-09-27 07:27:43 +00:00
Cal Herries
5be6213248 Add table-privileges driver feature and sync table-privileges on sync (#34128) 2023-09-27 10:08:41 +03:00
adam-james
0920254f90 Alert API sends all alert information to any user. Change this to onl… (#34067)
* Alert API sends all alert information to any user. Change this to only show those pulses the user has created or is
recipient of

* Adjust tests to show that only admins see all alerts. Regular users only see their alerts.

* Change docstring to describe behaviour of the endpoint.
2023-09-26 12:52:49 -07:00
Tim Macdonald
9daad146dd Add Github Action to set version-info's announcement_url (#33642)
Co-authored-by: Ryan Laurie <iethree@gmail.com>
2023-09-26 19:33:26 +00:00
Cam Saul
47a52b574f Remove deprecated current-db-time method (#32686)
* Remove deprecated current-db-time method

* Address PR feedback

* sync-timezone! should handle java.time.ZoneId and java.time.ZoneOffset

* Allow time zone offsets as zone IDs

* Fix tests and suppress clj-kondo on a few forms

* Suppress warning on one more occurrence of db-default-timezone

* Map offset Z to time zone UTC when syncing

* Accept zone offsets, zone ids and strings for h2 and oracle

* Mark snowflake as not supporting report timezone

* Revert "Mark snowflake as not supporting report timezone"

This reverts commit 70b15a6033.

* Fix report-timezone handling

* Numeric timezone

---------

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>
Co-authored-by: Tamás Benkő <tamas@metabase.com>
2023-09-26 10:11:28 -07:00
lbrdnk
a428ad8390 Use get-or-create-full-field-values! to fetch field values (#32299)
Co-authored-by: Cal Herries <39073188+calherries@users.noreply.github.com>
2023-09-26 11:35:47 -04:00
Nick Fitzpatrick
39acfd4a8f Only run BE tests on static viz FE changes (#33760)
* output static viz sources, update be workflow and file paths

* build static viz before file check

* extending file check timeout

* fixing mistake

* disable optimization when generating file paths

* prefer offline

* moving workflows to save 89505

* Maybe caching the build?

* removing minification

* upload artifact instead of use cache

* Add workflows back

* reduce files changed timeout

* removing unneeded yarn install
2023-09-26 11:43:45 -03:00
dpsutton
400850b98a X ray stage 1 (#34026)
* reintroduce the functions

* using affinities

had to update the affinities map to handle multiple definitions of the
same affinity name.

```clojure
core=> (let [affinities (-> ["table" "GenericTable"]
                            dashboard-templates/get-dashboard-template
                            dash-template->affinities-map)]
         (affinities "HourOfDayCreateDate"))
[["HourOfDayCreateDate"
  {:dimensions ["CreateTimestamp"], :metrics ["Count"], :score 50}]
 ["HourOfDayCreateDate"
  {:dimensions ["CreateTime"], :metrics ["Count"], :score 50}]]
```

Here there were two cards defined as "HourOfDateCreateDate". One looked
for a createtimestamp, the other for a createtime. When treating the
affinities as unique names, the one with createtime clobbered the
createtimestamp and then it went unsatisfied.

Now we keep both definitions around. The group by is stable so the
timestamp comes first and in match that one will be matched.

* i don't like reduced for some reason

* fixup affinities

1. Affinities were in wrong shape:

before:

```clojure
{"card-name" [["card-name" definition]
              ["card-name" definition]]
 ,,,
```

new shape:

```clojure
{"card-name" [definition
              definition]
 ,,,
```

ex:

```clojure
core=> (let [affinities (-> ["table" "GenericTable"]
                            dashboard-templates/get-dashboard-template
                            dash-template->affinities-map)]
         (affinities "HourOfDayCreateDate"))
({:dimensions ["CreateTimestamp"], :metrics ["Count"], :score 50}
 {:dimensions ["CreateTime"], :metrics ["Count"], :score 50})
```

2. Erroring on unfindable filters/metrics
using `{:filter [:dimension ::unsatisfiable]}` didn't work correctly
because of this:

```clojure
;; it doesn't look for dimensions by keyword
core=> (dashboard-templates/collect-dimensions [:dimension ::nope])
()
core=> (dashboard-templates/collect-dimensions [:dimension (str ::nope)])
(":metabase.automagic-dashboards.core/nope")
```

* Updating dash-template->affinities-map to dash-template->affinities.

Two key changes were made:
- The card name is now a part of the 'affinity' object (under the `:affinity-name` key).
  This flattening should also make affinities easier to deal with and more flexible
  (e.g. arbitrary groupings).
- All base dimensions are exploded out into these affinity objects under the `:base-dims` key.
  Note that this may result in growth of the number of affinities when named items are
  repeated with different definitions. For example, card names are not unique, resulting in
  N affinities per card. Also, metrics and filters need not be unique. GenericTable, for
  example, has 6 definitions of the Last30Days filter. This will result in 6X the number of
  affinities created for each card using that filter.

This change encapsulates affinities, as before you'd need to know what dimensions underlied
any given metric or filter. ATM, we do not package each filter or metric definition in each
affinity object, but perhaps that would be worth doing in the future for complete encapsulation.

This change also allows for very simple matching logic. To match card affinities, for example,
you just filter all affinities for which the affinity dimensions are a subset of the provided
dimensions.

* Updated tests for new affinity code. Removed accidental cruft.

* Change shape of affinities

The "satisfied-affins" are of this shape:
```clojure
{"AverageIncomeByMonth" #{"Income" "Timestamp"},
 "AverageDiscountByMonth" #{"Income" "Discount" "Timestamp"}}
```

And they are ordered so it can drive the `make-cards` function in the
future. The idea is for right now we'll look up the card based on
affinity name, and when multiple cards found, the set of dimensions they
depend on. And that will drive the layout.

But in the future, just the affinity itself will drive how we make a
card layout. This is the firs step towards that.

* Satisfied-affinities shape is ordered map to vector of sets of dims

```clojure
{"RowcountLast30Days" [#{"CreateTimestamp"}],
 "Rowcount" [#{}]}
```

Since each could be met in a few definitions in multiple ways

* Update comment

```clojure
core=> (let [affinities (-> ["table" "GenericTable"]
                            dashboard-templates/get-dashboard-template
                            dash-template->affinities)]
         (match-affinities affinities {:available-dimensions {"JoinDate" :whatever}}))
{"Rowcount" [#{}],
 "RowcountLast30Days" [#{"JoinDate"}],
 "CountByJoinDate" [#{"JoinDate"}],
 "DayOfWeekJoinDate" [#{"JoinDate"}],
 "DayOfMonthJoinDate" [#{"JoinDate"}],
 "MonthOfYearJoinDate" [#{"JoinDate"}],
 "QuerterOfYearJoinDate" [#{"JoinDate"}]}
```

* comment block is helpful 🐙

* Drive `make-cards` from affinities

old style was make-cards looped over all cards to see which ones were
satisfied. Now we've taken a notion of "interestingness" which we call
affinities: which dimensions are interesting in combination with each
other. Right now these are derived from card combinations but that will
change going forward.

So now going into the make-cards loop are interesting combinations and
we then grab a card-template from the combination. Again, it's a double
lookup back to cards but this lets us break that cycle and come up with
interesting card templates just based on the groupings themselves.

in the future, we're going to want an affinity to produce multiple
card-templates so this will become a mapcat of some sorts rather than a
map.

* Removing pre-check from card-candidates and corresponding unit test as this is not an invariant -- card-candidates should always be satisfied with our affinity mapping.

* comment and docstring

* Changed names for clarity (affinity -> affinity-sets) and modified
the return value of match-affinities to have values of sets of sets
rather than vectors of sets. This makes matching simpler and easier.

Added a docstring to CardTemplateProvider and started adding some tests.

* Revert "Changed names for clarity (affinity -> affinity-sets) and modified"

This reverts commit dd2aef1fea.

* Something about either the cherry-pick or stale state made the previous
change of affinities (as a vector of set) to affinity-sets (a set of sets)
cause failures. It may just be that the implementation was broken and
the tests passed due to a stale state ¯\_(ツ)_/¯.

This picks out the clarity and doc changes and reverts the set of sets.

* Adding schemas for the affinity functions in metabase.automagic-dashboards.core

* Created the AffinitySetProvider protocol, which, given an item, will
provide the set of affinities (a set of set of dimensions) required to
bind to that item. The initial implementation reifies the protocol
over a dashboard template and provides affinity sets for cards, but
this protocol could be extended to provide affinities for whatever
object we desire.

The initial implementation looks like so:

```clojure
(p/defprotocol+ AffinitySetProvider
  "For some item, determine the affinity sets of that item. This is a set of sets, each underlying set being a set of
  dimensions that, if satisfied, specify affinity to the item."
  (create-affinity-sets [this item]))

(mu/defn base-dimension-provider :- [:fn #(satisfies? AffinitySetProvider %)]
  "Takes a dashboard template and produces a function that takes a dashcard template and returns a seq of potential
  dimension sets that can satisfy the card."
  [{card-metrics :metrics card-filters :filters} :- ads/dashboard-template]
  (let [dim-groups (fn [items]
                     (-> (->> items
                              (map
                                (fn [item]
                                  [(ffirst item)
                                   (set (dashboard-templates/collect-dimensions item))]))
                              (group-by first))
                         (update-vals (fn [v] (mapv second v)))
                         (update "this" conj #{})))
        m->dims    (dim-groups card-metrics)
        f->dims    (dim-groups card-filters)]
    (reify AffinitySetProvider
      (create-affinity-sets [_ {:keys [dimensions metrics filters]}]
        (let [dimset                (set (map ffirst dimensions))
              underlying-dim-groups (concat (map m->dims metrics) (map f->dims filters))]
          (set
            (map
              (fn [lower-dims] (reduce into dimset lower-dims))
              (apply math.combo/cartesian-product underlying-dim-groups))))))))
```

* Adding specs for dashcard, dashcards, context (minimal) and instrumenting
make-cards. I'm wondering if we should move card-candidates into the
layout-producer protocol since we're using known affinities to make a thing,
not to make a baby step to make a thing. The one gotcha in this is that
there's a positional index inserted in there which IDK how we use other
than maybe layout ATM.

* Added more schemas and externalized the matching of affinities to
potential dimensions (or any map conforming to the a map of dimension
names to matches of items). This generalizes our ability to match
of affinity groups with "things" that we want to generate.

* Renaming output of all-satisfied-bindings to satisfied-bindings to prevent variable shadowing error.

---------

Co-authored-by: Mark Bastian <markbastian@gmail.com>
2023-09-26 07:56:56 -06:00
Cal Herries
481604aef6 Update table_privileges on sync for MySQL (#33598) 2023-09-26 12:52:48 +00:00
Tim Macdonald
ecf9d54955 Use Bigints for CSV uploads (#34118)
[Fixes #34080]
2023-09-26 11:44:35 +00:00
Nicolò Pretto
7e0eb68fd7 Revert "show columns added after the dashcard has been created in the viz settings (#33886)" (#34116) 2023-09-26 13:38:47 +03:00
Ngoc Khuat
3a1b10c643 Fix the flaky test 'downgrade-dashboard-tabs-test' (#34115)
* Fix the flaky test 'downgrade-dashboard-tabs-test' by bumping the
migration version we upgrade to during the test. I'm not fully sure why
it was flaky in the first place. For some reasons the rollback step
doesn't get triggered on MySQL even though liqubiase does acknowledge
that the migration got ran?? eitherway bumping the version seems to take
the flaky a way.
2023-09-26 10:36:42 +00:00
Cal Herries
263698247f Assure that common_name is assoc'd on a User correctly (#34056) 2023-09-26 08:16:42 +00:00
Mahatthana (Kelvin) Nomsawadi
c47e63c34d Add a repro for #17213 (#33833) 2023-09-26 07:07:19 +01:00
Uladzimir Havenchyk
6bcdd301bc Cleanup unused action names to prevent circular deps problem (#33983) 2023-09-25 20:50:33 +00:00
Braden Shepherdson
87cddad248 [MLv2] Rebuild lib.equality for faster, more precise matching and simpler code (#33977)
Fixes #32373.
2023-09-25 19:40:48 +00:00
Cam Saul
04f2471926 Support nested transactions for app DB (#33816)
Support nested transactions for app DB
---------

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>
Co-authored-by: Ngoc Khuat <qn.khuat@gmail.com>
2023-09-25 18:08:54 +00:00
shaun
0d18a32fd3 Fix typo in audit.md (#34092) 2023-09-25 17:21:12 +00:00
Uladzimir Havenchyk
70772211ce Lazy load EntityForm (#33978)
* Lazy load EntityForm

* Replace lazy loading with require

* add a comment
2023-09-25 14:16:13 +00:00
Cal Herries
109a5a870b Remove hardcoded collection in test (#34083) 2023-09-25 14:08:08 +00:00
Oisin Coveney
a52081f0ba Search Milestone 1.5 - Integration Branch (#33533) 2023-09-25 17:03:54 +03:00
Cal Herries
d7ed835aab Add missing @external tag to test introduced by #33990 (#34073) 2023-09-25 13:47:34 +02:00
Tim Macdonald
72f7eea10d Run the backport CI job when pushing new commits (#34079)
* Fix typo in comment

* Kick CI

* Run backport reminder on every push to an open PR

* Kick CI again with Nemanja's magic

---------

Co-authored-by: Nemanja <31325167+nemanjaglumac@users.noreply.github.com>
2023-09-25 13:32:52 +02:00
Tim Macdonald
9a613a8201 Set last_acknowledged_version automatically for new users (#33807)
Set `last_acknowledged_version` automatically for new users

This prevents new users from being told about what's new in Metabase
when…everything is new in Metabase for them
2023-09-25 10:37:40 +00:00
Alexander Polyankin
8e4fd016ce Mantine forms and password update form (#33726) 2023-09-25 13:21:26 +03:00
Nicolò Pretto
8d5f5db02c show columns added after the dashcard has been created in the viz settings (#33886)
* new implementation after rebase, also works for table details

* fix: makes #28304 pass again

* fix settings undefined crash

* use already defined variable

* get columns from settings param

* fix test data

* add unit test for metabase#28304
2023-09-25 10:08:16 +02:00
Oisin Coveney
6f23e1deb5 Add explicit font size for Search Bar (#33980) 2023-09-25 08:05:12 +00:00
Nemanja Glumac
14d4665c59 Do not offer to delete archived collections (#33991)
* Reproduce #33996
2023-09-23 00:44:56 +02:00
Case Nelson
20988e9513 [MLv2] Add query can-run function (#34040)
* [MLv2] Add query can-run function

* Update src/metabase/lib/native.cljc

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>

* Add test for non-native query

* Fix tests - snippet-id can be optional

---------

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>
2023-09-22 20:45:57 +00:00
dpsutton
fa764262f2 ~~Bump h2~~ inline parameter to fix flaky test (#34062)
* Bump h2 to fix flaky test

Symptom:
--------

error in linter job:
```
With premium token features = #{"audit-app"}
:metabase-enterprise.audit-app.pages.dashboards/most-popular-with-avg-speed

expected: (schema= {:status (s/eq :completed), s/Keyword s/Any} (qp/process-query query))
  actual: clojure.lang.ExceptionInfo: Error reducing result rows: Error running audit query: Invalid value "NULL" for parameter "result FETCH"; SQL statement:
WITH "MOST_POPULAR" AS (SELECT "D"."ID" AS "DASHBOARD_ID", "D"."NAME" AS "DASHBOARD_NAME", COUNT(*) AS "VIEWS" FROM "VIEW_LOG" AS "VL" LEFT JOIN "REPORT_DASHBOARD" AS "D" ON "VL"."MODEL_ID" = "D"."ID" WHERE "VL"."MODEL" = 'dashboard' GROUP BY "D"."ID" ORDER BY COUNT(*) DESC LIMIT ?), "CARD_RUNNING_TIME" AS (SELECT "QE"."CARD_ID", AVG("QE"."RUNNING_TIME") AS "AVG_RUNNING_TIME" FROM "QUERY_EXECUTION" AS "QE" WHERE "QE"."CARD_ID" IS NOT NULL GROUP BY "QE"."CARD_ID"), "DASH_AVG_RUNNING_TIME" AS (SELECT "D"."ID" AS "DASHBOARD_ID", AVG("RT"."AVG_RUNNING_TIME") AS "AVG_RUNNING_TIME" FROM "REPORT_DASHBOARDCARD" AS "DC" LEFT JOIN "CARD_RUNNING_TIME" AS "RT" ON "DC"."CARD_ID" = "RT"."CARD_ID" LEFT JOIN "REPORT_DASHBOARD" AS "D" ON "DC"."DASHBOARD_ID" = "D"."ID" WHERE "D"."ID" IN (SELECT "DASHBOARD_ID" FROM "MOST_POPULAR") GROUP BY "D"."ID") SELECT "MP"."DASHBOARD_ID", "MP"."DASHBOARD_NAME", "MP"."VIEWS", "RT"."AVG_RUNNING_TIME" FROM "MOST_POPULAR" AS "MP" LEFT JOIN "DASH_AVG_RUNNING_TIME" AS "RT" ON "MP"."DASHBOARD_ID" = "RT"."DASHBOARD_ID" ORDER BY "MP"."VIEWS" DESC LIMIT ? [90008-214]

<stack traces of us catching and rethrowing>
Caused by: org.h2.jdbc.JdbcSQLDataException: Invalid value "NULL" for parameter "result FETCH"; SQL statement:
WITH "MOST_POPULAR" AS (SELECT "D"."ID" AS "DASHBOARD_ID", "D"."NAME" AS "DASHBOARD_NAME", COUNT(*) AS "VIEWS" FROM "VIEW_LOG" AS "VL" LEFT JOIN "REPORT_DASHBOARD" AS "D" ON "VL"."MODEL_ID" = "D"."ID" WHERE "VL"."MODEL" = 'dashboard' GROUP BY "D"."ID" ORDER BY COUNT(*) DESC LIMIT ?), "CARD_RUNNING_TIME" AS (SELECT "QE"."CARD_ID", AVG("QE"."RUNNING_TIME") AS "AVG_RUNNING_TIME" FROM "QUERY_EXECUTION" AS "QE" WHERE "QE"."CARD_ID" IS NOT NULL GROUP BY "QE"."CARD_ID"), "DASH_AVG_RUNNING_TIME" AS (SELECT "D"."ID" AS "DASHBOARD_ID", AVG("RT"."AVG_RUNNING_TIME") AS "AVG_RUNNING_TIME" FROM "REPORT_DASHBOARDCARD" AS "DC" LEFT JOIN "CARD_RUNNING_TIME" AS "RT" ON "DC"."CARD_ID" = "RT"."CARD_ID" LEFT JOIN "REPORT_DASHBOARD" AS "D" ON "DC"."DASHBOARD_ID" = "D"."ID" WHERE "D"."ID" IN (SELECT "DASHBOARD_ID" FROM "MOST_POPULAR") GROUP BY "D"."ID") SELECT "MP"."DASHBOARD_ID", "MP"."DASHBOARD_NAME", "MP"."VIEWS", "RT"."AVG_RUNNING_TIME" FROM "MOST_POPULAR" AS "MP" LEFT JOIN "DASH_AVG_RUNNING_TIME" AS "RT" ON "MP"."DASHBOARD_ID" = "RT"."DASHBOARD_ID" ORDER BY "MP"."VIEWS" DESC LIMIT ? [90008-214]
 at org.h2.message.DbException.getJdbcSQLException (DbException.java:646)
    org.h2.message.DbException.getJdbcSQLException (DbException.java:477)
    org.h2.message.DbException.get (DbException.java:223)
    org.h2.message.DbException.getInvalidValueException (DbException.java:298)
    org.h2.command.query.Query.getOffsetFetch (Query.java:912)
    org.h2.command.query.Select.queryWithoutCache (Select.java:768)
    org.h2.command.query.Query.queryWithoutCacheLazyCheck (Query.java:197)
    org.h2.command.query.Query.query (Query.java:512)
    ...
```

BUT this only causes an issue for tests run under the cloverage
linter. It's not an issue under any other test scenarios.

Reproduction:
-------------

I can get the same stack traces with the following:

```clojure
dashboards=> (clojure.java.jdbc/query {:datasource
                                       (:data-source metabase.db.connection/*application-db*)}
                                      ["select 1 limit null"])
Execution error (JdbcSQLDataException) at org.h2.message.DbException/getJdbcSQLException (DbException.java:646).
Invalid value "NULL" for parameter "result FETCH"; SQL statement:
select 1 limit null [90008-214]

dashboards=> (clojure.java.jdbc/query {:datasource
                                       (:data-source metabase.db.connection/*application-db*)}
                                      ["select 1 limit ?" nil])
Execution error (JdbcSQLDataException) at org.h2.message.DbException/getJdbcSQLException (DbException.java:646).
Invalid value "NULL" for parameter "result FETCH"; SQL statement:
select 1 limit ? [90008-214]
```

But with a normal repl, running the test does not error:

```clojure
(deftest all-queries-test
  (mt/with-test-user :crowberto
    (with-temp-objects [objects]
      (premium-features-test/with-premium-features #{:audit-app}
                             ;; limit to just the version
        (doseq [query-type #_(all-query-methods) [:metabase-enterprise.audit-app.pages.dashboards/most-popular-with-avg-speed]]
          (testing query-type
            (do-tests-for-query-type query-type objects)))))))

pages-test=> (clojure.test/run-test all-queries-test)

Testing metabase-enterprise.audit-app.pages-test

Ran 1 tests containing 1 assertions.
0 failures, 0 errors.
{:test 1, :pass 1, :fail 0, :error 0, :type :summary}
```

And even more frustrating, just grabbing the sql and params and calling
the same code:

```clojure
common=> (let [driver (mdb/db-type)
               sql check/sql
               params check/params]
           (with-open [conn (.getConnection mdb.connection/*application-db*)
                       stmt (doto (sql-jdbc.execute/prepared-statement driver conn sql params)
                              foo
                              )
                       rs   (sql-jdbc.execute/execute-prepared-statement! driver stmt)]
             (into [] (clojure.java.jdbc/result-set-seq rs))))
[]
```

I can get the test to fail by running the cloverage runner with a socket
repl started and then running the test during that instrumented run:

```
clojure -J"$(socket-repl 6000)" -X:dev:ee:ee-dev:test:cloverage
```

But I'm not able to find anything interesting. It's a bug in CTEs with
parameters in h2, and it seems that only this query is sensitive.

If I inline the value it works under 2.1.214. And if I bump the version
to 2.2.224 it works. So I'm bumping the version.

* inline the offending value

* Revert "Bump h2 to fix flaky test"

This reverts commit 9cd6aed19c.
2023-09-22 14:08:27 -05:00
Case Nelson
bf45689cd6 [MLv2] Handle coalesce type after conversion (#33814)
* [MLv2] Handle coalesce type after conversion

* Update test/metabase/lib/aggregation_test.cljc

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>

* Only update fields on converted queries

* Don't convert if base-type exists

* Guard against non-numeric field ids

* Fix test with hardcoded ids

* Allow metadata/field to return nil on not found

* Add ipaddress and mongobsonid types to equality-comparable-types

* Support is-empty not-empty for mongobsonid

* Add base-type to FE tests

* Fix e2e tests - column metadata is valid with field types filled in

---------

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>
2023-09-22 18:54:22 +00:00
Case Nelson
1815233a97 [MLv2] Add function for database engine (#33942)
* [MLv2] Add function for database engine

* Update src/metabase/lib/js.cljs

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>

* Use native query

---------

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>
2023-09-22 10:34:11 -06:00
Case Nelson
d7de93801d [MLv2] Fix template-tags snippet-id (#33902)
* [MLv2] Fix template-tags snippet-id

Looking at this bug I found there were a couple problems that the
converters were not properly handling. First, the conversion to js was
copying snake case to kebab case instead of renaming. Second the conversion to
clojure was not picking up kebab case keys but using the snake case keys.

So I dropped the TemplateTag encoder and decoder and went forward with
js->clj and clj->js since the only tricky part was keeping the tag names
as strings and keeping the :type as keyword.

* Address review comments
2023-09-22 16:01:40 +00:00
Uladzimir Havenchyk
1ed5c083e5 Fix links in admin settings to work on subpath (#33985) 2023-09-22 14:49:36 +00:00
Uladzimir Havenchyk
3ea1d6c571 [InteractiveTable] Improve peformance during scrolling (#34037) 2023-09-22 17:36:28 +03:00
Nemanja Glumac
ff0ab8bb14 Fix archived items tooltip that's missing the item type (#33970)
* Make archived item rely on the `model` for its type

The `type` prop doesn't exist in the list of items.
`models` on the other hand exists and it shows the underlying item model,
which almost 1:1 matches the desired type.

Almost, because we can questions "card" in the code.
That will be accounted for in the next commit.

* Handle `card` and `dataset` models

Show "question` and "model" in the UI instead.

* Move `getTranslatedEntityName` to the common utils

* Use translated entities for the archived item tooltip

* Switch back to the implicit return

* Lowercase the translated model name

* Add missing string translation

* Add unit test for `getTranslatedEntityName`
2023-09-22 15:52:25 +02:00
Oisin Coveney
75482b1f99 Remove extra search API call (#34014)
Co-authored-by: Nemanja <31325167+nemanjaglumac@users.noreply.github.com>
2023-09-22 15:35:06 +03:00
Cal Herries
6102fad048 Fix 33971: CSV uploads aren't possible when native query editing is disabled (#33990) 2023-09-22 12:09:01 +00:00
Nemanja Glumac
1865b0681a Nit: Fix typo in conditional table formatting (#34048)
'vice a versa' -> 'vice versa'
2023-09-22 12:56:50 +02:00
Ryan Laurie
de98b25937 Update release-glob in re-run workflow (#34046) 2023-09-22 09:23:54 +02:00
Cal Herries
76b54609e5 Update changelog to include report-timezone-id-if-supported change (#34028) 2023-09-22 09:41:41 +03:00
Emmad Usmani
7b9b2f3086 fix multi-color selection in ColorRangeSelector (#33989)
* fix multi-color selection in `ColorRangeSelector`

* unit test
2023-09-21 10:25:58 -07:00
Nemanja Glumac
e833b59ab5 Use the same Chrome version (111) for visual tests as well (#34025) 2023-09-21 17:54:12 +02:00
Tim Macdonald
8cd527a148 Random BE cleanup (#34024) 2023-09-21 15:50:52 +00:00
Cal Herries
3b8492ad4a Fix 33917: Increase max length of collection slugs (#33931) 2023-09-21 15:27:47 +00:00
Nemanja Glumac
0550ee44c0 [E2E] Fix "back to x-ray model dashboard" navigation flake (#34020)
* Fix back to x-ray dashboard flake

No need to load thousands of row and to rely on overly complicated automagic calculations.
The only thing this test wants to know whether or not we display "back to dashboard" button.

By greatly simplifying the underlying model, automagic dashboard becomes MUCH simpler.
The test will also be significantly faster as a result of this change.

* Make test title more accurate

* Remove the `@slow` test tag
2023-09-21 16:45:37 +02:00
Aleksandr Lesnenko
3faa180ddf fix stacked tooltip shows only first data point value instead of a sum (#34008) 2023-09-21 13:16:53 +00:00
Nicolò Pretto
718596f5ee Convert lib/utils.js to ts (#33966)
* converts lib/utils to ts

* removed "MetabaseUtils" namespace in favor of exporting single functions

* fix tests

* fix bug

* removed unused isBase64 function
2023-09-21 08:21:43 +00:00
Kamil Mielnik
65cfb44821 Add custom warning message when leaving editing dashboard with unsaved changes (#33827)
* Add custom warning message when leaving editing dashboard with unsaved changes

* Add a test for warning about unsaved changes (it does not work yet)

* Add a unit test for warning about unsaved changes

* Revert "Add a test for warning about unsaved changes (it does not work yet)"

This reverts commit 7210873994.

* Add a test case for no changes

* Reduce number of checkNotNull calls

* Reduce number of checkNotNull calls
2023-09-21 13:19:13 +07:00
Nemanja Glumac
395eb81184 Fix E2E model actions CRUD flake (#33994)
* Navigate to `/archive` directly

* Fix the flake by asserting on UI changes

* Clean test up

* Delete the superfluous assertion
2023-09-20 21:29:34 +02:00
Mark Bastian
764fcd0687 X-ray improvements for clarity and literacy (#33815)
* Fix clj-kondo

was getting an error:

```clojure
user=> (require ’[clj-kondo.hooks-api :as hooks])
Syntax error compiling at (clj_kondo/impl/analysis/java.clj:61:6).
Unable to find static field: ASM9 in interface org.objectweb.asm.Opcodes
```

checking where the bad version comes from:

```clojure
user=> (io/resource "org/objectweb/asm/Opcodes.class")
        "0x37e9d2e2"
        "jar:file:/Users/dan/.m2/repository/org/ow2/asm/asm-all/5.2/asm-all-5.2.jar!/org/objectweb/asm/Opcodes.class"]
```

and running

```
> clj -X:deps tree :aliases '[:dev :ee :ee-dev :drivers :drivers-dev :alpha :socket :morse :reveal]' > deps

❯ grep asm deps
  X org.ow2.asm/asm 9.4 :superseded
  . org.ow2.asm/asm-all 5.2
      . org.ow2.asm/asm 9.5 :newer-version
      . org.ow2.asm/asm-commons 9.5
        . org.ow2.asm/asm 9.5
        . org.ow2.asm/asm-tree 9.5
          . org.ow2.asm/asm 9.5
    X org.ow2.asm/asm 9.2 :older-version
```

The 9.4 and 9.5s are all close to each other. But the asm-all 5.2 is far
too old. That's brought in by eastwood. So i'll exclude it and see if it
works

* Can't throw error in api endpoint for linked entities x-ray

`create-linked-dashboard` creates a dashboard if there are no linked
entities, so this is unreachable code

* unify card and query code pathways.

now it's quite clear how card and query diverge:

```clojure
(defmethod automagic-analysis Card
  [card {:keys [cell-query] :as opts}]
  (let [root     (->root card)
        cell-url (format "%squestion/%s/cell/%s" public-endpoint
                         (u/the-id card)
                         (encode-base64-json cell-query))]
    (query-based-analysis root opts
                          (when cell-query
                            {:cell-query cell-query
                             :cell-url   cell-url}))))

(defmethod automagic-analysis Query
  [query {:keys [cell-query] :as opts}]
  (let [root       (->root query)
        cell-query (when cell-query (mbql.normalize/normalize-fragment [:query :filter] cell-query))
        opts       (cond-> opts
                     cell-query (assoc :cell-query cell-query))
        cell-url   (format "%sadhoc/%s/cell/%s" public-endpoint
                           (encode-base64-json (:dataset_query query))
                           (encode-base64-json cell-query))]
    (query-based-analysis root opts
                          (when cell-query
                            {:cell-query cell-query
                             :cell-url   cell-url}))))
```

* Adding frequencies to a test to prevent non-deterministic behavior

* Fixing linter check and ordering issue in test.

* Adding TODO future task to replace /rule/ with /dashboard-template/ in paths.

* Added large ns block to metabase.automagic-dashboards.core

* Fixing spelling mistakes

* Some docstrings and renaming for clarity.

* Added ->field and ->root (covering source) tests

* TODO - Fix minumum spelling error on standalone PR.

* Breaking up tests to understand what is on with bulk failures

* Broke make-cards into several logical steps so that the code is more readable. Added tests for each stage.

* Updating references to rules.clj for i18n generation.

* Inlined make-context into apply-dashboard-template. This makes the steps of creating dimensions, metrics, and filters more explicit. ATM we still need to resolve the logic around inject-root as this has dependence on the context and not the individual dimensions.

* put build stuff on classpath for lsp

* calculate base-context once before template loop

* Removed the inject-root multimethod in favor of simple functions. Introducing the idea of removing metric and filter candidates that claim dimensions that don't exist.

* Adding logic to pre-emptively remove unsatisfied metrics, filters, and dimensions.

In `card-candidates` the check:

```
(and
  (every? context-dimensions (map ffirst card-dimensions))
  (every? context-metrics card-metrics)
  (every? context-filters card-filters))
```

is now performed to ensure that the card is satisfied before moving forward.

* Renamed common-dimensions, common-metrics, and common-filters to satisfied-* for clarity. In card-candidates also changed context-* and card-* bindings to available-* and required-* for clarity.

* Teasing out the generated dimensions, metrics, and filters from the big-ball-of-mud context. `make-cards` now takes the base context as well as the available computed dimensions, metrics, and filters as a separate argument. Additionally, tests were added for the `(comp #(filter-tables % tables) dashboard-templates/->entity)` branch of `some-fn` in `potential-card-dimension-bindings`. However, I am not confident that this is ever called outside of the tests. In order to be called, the entity type for the table has to be a named dimension in a card, which I can't find any examples of in the templates.

* Pushing mega-context down to return value of apply-dashboard-template. Just need to take it apart where it is used downstream.

* apply-dashboard-template now just returns generated values and does not build up the base context.

* Adding tests for cases in which dimensions are defined in a native query on the dashcard template.

The only case where this happens is in the resources/automagic_dashboards/table/example.yaml and,
prior to this PR, had no test coverage.

It does add some weird complexities to the system (including bringing in dimensions from a different
approach vector) so perhaps we want to re-evaluate if we want this as a feature or not.

---------

Co-authored-by: dan sutton <dan@dpsutton.com>
2023-09-20 16:01:31 +00:00
Emmad Usmani
aafd93152e fix landing-page setting causing frontend to break (#33935)
* fix redirect breaking with `landing-page` setting

* write test
2023-09-20 15:44:02 +00:00
Nick Fitzpatrick
dcf662c327 Adding Model to Cypress Snapshot (#33308)
Co-authored-by: Ryan Laurie <iethree@gmail.com>
2023-09-20 13:39:37 +00:00
Uladzimir Havenchyk
1cf1b443aa [PivotTable] Improve scrolling performance (#33908)
* [PivotTable] Skip unnecessary rendering

* Update imports

* Oops. no need to render children 3 times

* Rename prop isScrolling -> showTooltip

* Rename hook parameter

* Delete test
2023-09-20 07:56:17 +00:00
Uladzimir Havenchyk
7d8412017e Rework FieldValuesWidget to skip initialization of Fields entity (#33916)
* Rework FieldValuesWidget to skip initialization of Fields entity

* Revert mocking

* Rename methods and add proper checks
2023-09-19 21:44:40 +00:00
Nemanja Glumac
9ea6200a7d Reduce the number of Cypress retries in run mode (#33965)
* Reduce the number of Cypress retries in run mode to two

[ci skip]
2023-09-19 18:20:12 +02:00
Nicolò Pretto
dd50037c74 Fix compare versions vunknown crashing for vUNKNOWN (#33946)
* fix compareVersions crashing on vUNKNOWN

* refactor: organize tests

* fix return type
2023-09-19 14:40:04 +00:00
Jeff Bruemmer
89e308ec38 update list of releases (#33954) 2023-09-19 08:22:13 -06:00
Nemanja Glumac
f2b0e2c22a Unskip repro for #24839 (#33948)
Closes #24839 that was obviously fixed by mlv2.
2023-09-19 15:25:40 +02:00
Cam Saul
c802a2358a Metabase event subsystem overhaul (#33392)
* Metabase event system overhaul

* Remove unused :event/pulse-update

* Revert some session changes

* Test fixes 🔧

* Last few fixes 🔧

* fix assertions in activity tests

* fix kondo error

* fix persisted_info_test ns

* Test fixes 🔧

* fix test

* fix final test by clearing view log before running it

---------

Co-authored-by: Noah Moss <noahbmoss@gmail.com>
Co-authored-by: Noah Moss <32746338+noahmoss@users.noreply.github.com>
2023-09-19 00:01:13 +00:00
Nemanja Glumac
83ae490b72 Fix E2E archive/unarchive dashboard flaky test (#33941)
* Fix the archive/unarchive dashboard flake

* Make test more resilient

* Log instead of comment

* Update the "delete" test scenarios
2023-09-18 23:37:06 +02:00
Noah Moss
77d0e06e29 fix persist-test failures (#33940) 2023-09-18 21:19:36 +00:00
Braden Shepherdson
fcbe62b88e [MLv2] Don't discard extra variadic args to drill-thru (#33926)
Fixes #33480.
2023-09-18 16:34:15 -04:00
Ngoc Khuat
c9139fd963 Less half-way migration: no more defendpoint-schema (#33885) 2023-09-18 22:31:09 +03:00
Cam Saul
a664cb1fea Update dir locals (#33871) 2023-09-18 12:21:16 -05:00
Uladzimir Havenchyk
bb90185ef6 Include subpath to the URL during downloading question results (#33856)
* Include subpath to the URL during downloading question results

* Fix test

* Simplify logic, drop tests

* Fix test

* Use api.basename
2023-09-18 15:05:51 +00:00
Nicolò Pretto
b932ef74e2 Fix 'object' visualization not showing 'details-only' fields (#33828)
* wip solution

* refactor: better naming for draft

* test: add unit test for 32718

* refactor: converted test to typescript

* create buildTableColumnSettings

* replace tableColumnSettings with buildTableColumnSettings

* revert immer use as it's not needed anymore
2023-09-18 14:28:34 +02:00
Ryan Laurie
a6815ce0f9 Scope test selectors in models metadata tests (#33842) 2023-09-16 15:47:03 -06:00
Nicolò Pretto
ba9835354d Whats new notification (#33593)
* Whats new notification (#33325)

* feat: add last-acknowledged-version to settings types

* whats new notification logic with mock ui

* updated logic to look for the release notes url  as for last sync

* move folder in nav/components

* wip dismiss logic

* wait for @sessionProperty to make sure notification would have loaded in case of failing test

* skipped test for manual testing/qa

* updated ui with mantine

* docs for getLatestEligibleReleaseNotes

* fix e2e to use icon

* use real sparkles image/icon

* refactor and clean up to use correct components

* moved all the logic into the util function to ease testing

* removed Paper import

* styled component instead of sx prop

* renamed things as per pr feedback

* fix ts error

* use createMockVersion

* removed getLastAcknowledgedVersion from 'settings.ts'

* added tests

* added multi user e2e test

* fix function not bein called by mistake

* removed new line that was added in previous commit

* test: adds test for case when current version is not present in version info

* fix logic to exclude versions not found in version-info

* releaseNotesUrl -> announcement_url

* fix manual test

* Whats new test refactor (#33592)

* moved NotificationContainer into styled.tsx file

* removed commented code

* move version list logic in helper function

* removed describe block wrapping everything

* refactored unit test for util function to prepare them to accept tests currently in the component

* fix test passing for the wrong reason

* switched order of cy.wait/cy.findBy to make test more resilient

* adds tests as suggested on pr

* moved test to unit test file, removed component tests already covered

* added jest test to check if endpoint is called when dismissing the notification

* use paper from metabase/ui (#33595)

* fix font size (#33596)

* added hover color to icon in what's new notification (#33633)

* added hover color to icon

* use colors from theme

* What's new - adds white labeling check to logic (#33673)

* adds white labeling check to logic

* sets isEmbedded and isWhiteLabeling as non optional

* made currentVersion non-optional

* Fix compareversions (#33671)

* adds typing to compareVersions util function

* sort versions before doing logic

* add logic to version comparison to make 0.46 = 0.46.0

* adds tests that is actuall needing the padding

* Apply suggestions from code review

Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>

* remove new test file before moving new one there

* moved old test file to be colocated

* added back new tests

* versionToNumericComponents

* correct VersionInfoTyping to make version always present

* fix for type error that appears in ci but not locally?

* refactor test to not use shuffle + whitespace fixes

* Update frontend/src/metabase/lib/utils.unit.spec.ts

* refactored versionToNumericComponents to use regex to be more readbale after suggestion of alex

* fix not working for v1

---------

Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>

* remove cy test used for manual test

---------

Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>
2023-09-15 15:10:48 +00:00
Uladzimir Havenchyk
1128622fa1 Drop unused packages (#33850)
* Drop redux-router

* Drop react-element-to-jsx-string

* Typo
2023-09-15 08:35:09 +00:00
Case Nelson
53d6dd9904 [MLv2] Adds hasWritePermission for native queries (#33899) 2023-09-14 21:28:32 +00:00
Case Nelson
863b2ad451 [MLv2] Macro for testing against a number of similar shaped but differently built queries at once (#33766)
* [MLv2] Macro for testing against a number of similar shaped but differently built queries at once

* Address review comments, add missing kondo hook

* Fix macros in cljs
2023-09-14 17:19:59 +00:00
Ryan Kienstra
72769e0760 Add unit tests for 2 /api/persist/ endpoints (#33776) 2023-09-14 13:43:18 +02:00
metamben
fa94e6e5da Prefer secret value to secret instance ID (#33877)
When secrets get updated, both the new value and the ID of the old
secret instance are in the details. Preferring the ID of the old
instance means that the connection test uses the old (and likely
invalid) secret.
2023-09-14 02:09:05 +03:00
Denis Berezin
e4058aee75 Add reproduction test (#33873) 2023-09-13 20:55:51 +00:00
Nemanja Glumac
4af43be8df Create pre-release Docker staging images that include Metabase version in the name (#33363) 2023-09-13 16:42:10 +02:00
Alexander Polyankin
ed62130cc5 Fix FE perf issue (#33831) 2023-09-13 11:04:05 +00:00
Ryan Laurie
aa3f4138e7 Remove unused d3 package (#33840) 2023-09-13 01:44:20 -06:00
Aleksandr Lesnenko
77c64754c0 fix cljs imports in static viz dev mode (#33341) 2023-09-12 17:10:34 +00:00
shaun
599d0c26bc Allow removing filter defaults on Subscriptions (EE) (#33359) 2023-09-12 16:27:00 +00:00
Denis Berezin
2f9d57221c Add metadata reload on question to model conversion (#33843)
* Add metadata reload on question to model conversion

* Add e2e test
2023-09-12 19:18:03 +03:00
Jeff Bruemmer
efb72cbd92 note on connection impersonation (#33863) 2023-09-12 11:06:15 +01:00
metamben
f3bd391dbd Allow multiple implicitly joinables for a single target field (#33845) 2023-09-12 01:17:27 +03:00
dpsutton
716e8b1f41 Fix parameter mappings on dashboards (#33837)
when running an x-ray on tables, we were sending back the following
parameter mappings:

BEFORE with bug:
```clojure
core=> (let [table (t2/select-one 'Table :id 1)]
         ;; products table
         (-> (automagic-analysis table {})
             :ordered_cards first
             (select-keys [:parameter_mappings :card])
             (update-in [:card] #(select-keys % [:dataset_query]))))
{:parameter_mappings ({:parameter_id "-1185138340",
                       :target [:dimension
                                [:field
                                 "CREATED_AT"  ;; <----- field reference by name
                                 {:base-type :type/DateTime}]],
                       :card_id G__246876}
                      {:parameter_id "241800831",
                       :target [:dimension
                                [:field
                                 "CATEGORY"    ;; <----- field reference by name
                                 {:base-type :type/Text}]],
                       :card_id G__246876}),
 :card {:dataset_query {:type :query,          ;; <----- mbql query
                        :database 1,
                        :query {:source-table 1,
                                :breakout ([:field
                                            64
                                            {:temporal-unit :quarter-of-year}]),
                                :aggregation (["count"])}}}}
```

After this change we have the following parameter mappings which use ids
as field references:

```clojure
core=> (let [table (t2/select-one 'Table :id 1)]
              ;; products table
              (-> (automagic-analysis table {})
                  :ordered_cards first
                  (select-keys [:parameter_mappings :card])
                  (update-in [:card] #(select-keys % [:dataset_query]))))
{:parameter_mappings ({:parameter_id "-1185138340",
                       :target [:dimension [:field 64 nil]], ;; <-- by id
                       :card_id G__186662}
                      {:parameter_id "241800831",
                       :target [:dimension [:field 58 nil]], ;; <-- by id
                       :card_id G__186662}),
 :card {:dataset_query {:type :query,
                        :database 1,
                        :query {:source-table 1,
                                :breakout ([:field
                                            64
                                            {:temporal-unit :quarter-of-year}]),
                                :aggregation (["count"])}}}}
```

This change was introduced in our refactoring to support x-rays on
models with commit message

* metabase.automagic-dashboards.filters - Fix to build-fk-map so that
parameters show up on model x-rays

I'm not sure what the reasoning was but we can revisit it when we want
to do some filters on models
2023-09-08 13:33:43 -05:00
Mark Bastian
50ed3b3f99 Automagic tests (#33732)
* metabase.automagic-dashboards.core - Docs, cleanup, and destructuring for clarity
metabase.api.search - Adding fix to realize search results
metabase.automagic-dashboards.filters - Fix to build-fk-map so that parameters show up on model x-rays
metabase.automagic-dashboards.populate - Fix typo
metabase.api.search-test - Unit tests for search fix

* Brought over tab saving of transient x-ray dashboard code to save-transient-dashboard!

Added initial cut of tabbed x-ray generation from mapping over linked entities to the automagic-dashboards api

* update signature

we'll need some filtering criteria for the tabs. we don't just want an
x-ray of orders, we want an x-ray of _Customer's orders_

* Added query-filter to /model_index/:model-index-id/primary_key/:pk-id API

* Fixed id propagation

* clean up the logic a little bit

* Intermediate step to trap bad generated queries

* First stab at queries with joins for x-rays

take a model, find joinable tables and create joins back to the model's
underlying table so we can filter where pk=selected-id.

```clojure
{:database_id 1,
 :database-id 1,
 :table_id 2,
 :dataset_query {:database 1,
                 :type :query,
                 :query {:source-table 2,
                         :where [:=
                                 [:field
                                  62
                                  {:join-alias "ORDERS__via__PRODUCT_ID"}]
                                 1],
                         :joins [{:alias "ORDERS__via__PRODUCT_ID",
                                  :fields :none,
                                  :strategy :left-join,
                                  :condition [:=
                                              [:field
                                               62
                                               {:join-alias "ORDERS__via__PRODUCT_ID"}]
                                              [:field 40 nil]],
                                  :source-table 1}]}}}
```

Note the where clause and the join, but selecting `:fields :none` from
the join. so it's

```sql
select j.*
from joinable j
left join model m
where m.id = <user-selection>
```

But x-rays of these queries strip out our joins :(

Here's what comes back in the automagic dashboard

```clojure
{:type :query,
 :database 1,
 :query {:source-table 2,
         :filter [:and
                  [:=
                   [:field
                    62
                    nil]
                   1]],
         :breakout ([:field
                     41
                     {:temporal-unit :month}]),
         :aggregation (["avg"
                        [:field
                         39
                         nil]])}}
```

It's a breakout by month of orders.created_at (field 41) aggregated by
orders.quantity (field 39) where products.id (field 62 of table) =
1. But there's no join to products any longer :(

And there's this nice little comment

```clojure
(defn- maybe-enrich-joins "Hack to shove back in joins when they get
automagically stripped out by the question decomposition into metrics"
```

So that's no great. More investigating to do

* Added in `:source-field` for our x-ray tabs so that filters would succeed.

* Merged fixes to filters.

* Adding in entity x-ray dashboard title

* Fixed entity x-ray description.

* Added model-link card to each tab in the dynamically generated entity x-rays.

* Adding min-width calculation for source model link card.

* Adding tests for min-width calculation for source model link card.

* Fixing import indentation

* tests for x-rays on indexed models

* Adding tests to metabase.api.automagic-dashboards-test to assert the existence of model link cards and meaningful dashboard names and descriptions.

* include model_index_id in search results for indexed entity

had the rest of the changes, just not the id of the model_index

* use negative integers, not gensyms for tab-ids

FE wants negative integers for ids that do not exist in the db yet. some
of the cards and such still use gensym and that seems to be ok for now.

* fix tabs on x-ray dashboard in FE

* add x-ray button to `SearchResult` component

* clean up styles for tabs in `AutomaticDashboardAppInner`

* Added tests to understand some of the logic in `field-candidates.` The selection of a candidate is variable depending on the specification of the dimension, the field type, the table type, how the context is populated, etc. These tests attempt to illustrate some of the logic.

* Adding tests in which multiple fields match to multiple dimensions.

* Added tests for bind-dimensions and much of the logic it calls.

* Removing `:transient_name` and `:transient_filters` from generated entity x-ray to ensure the right information is displayed on the generated dashboard.

* Formatting

* Formatting

* Formatting

* Formatting

* Fixing quoted instance of Card

* wslint

* Hook for `metabase.api.automagic-dashboards-test/with-indexed-model`

* wip

* wslint

* lint warnings on ns requires

unused ns qp
using a deprecated namespace so give an override

* better error message for no linked entities

they used to be in the let-404 so you would get a quite confusing error
message. Now it's a 400 and will show "No linked entities" if you expand
the error message. We still need to make this better. But this is an
obvious improvement on a 404.

* Adding default entity dashboard for when no linked entities are found.

* fix search tests

* call count is 16 now

* Fixing unit test

* Fixed the query filter in `metabase.api.automagic-dashboards` so that `create-linked-dashboard` doe not produce bad queries.

* remove model index destructure

* Assert that all query dashcards have the correct filter.

We're no longer making joins back to the model's underlying
table. Recognizing that we were joining on linked table's fk to the
model's underlying table's pk and then searching where pk = <pk-value>,
we can just filter where fk = <pk-value>, omit the join.

So these tests just grab all of the linked tables and assert that one of
those filters is found.

eg, suppose a model based on products. the linked tables are orders and
reviews. And rather than the queries:

```sql
select o.*
from orders o
left join products p
on p.id = o.product_id
where p.id = <pk-value>
```

we can just do

```sql
select *
from orders
where product_id = <pk-value>
```

And similar for reviews. And for each query in the dashboard we're
looking for one of the following:

```clojure
, #{[:= $orders.product_id 1] [:= $reviews.product_id 1]}
```

* Intermediate stage of fixing our tests

* Added missing `is` clauses to a few tests. This surfaced some minor formatting changes that would have broken the tests had they been working. Updated the tests to correspond to the changes (just has to do with pluralization).

* Fixed untyped event and added mock search data.

* Fixing entity x-rays for a single linked entity

* Adding logic to provide only a single linked entity view for entity x-rays if only one is generated.

* lint fix

* add tests for 1 linked-table = 0 tabs case

* Updated `create-linked-dashboard` with a threading macro for clarity and to be more clojuric.

* split single test into three

cam made a new linter to look for test forms over a certain
size. There's no great way to run only a single testing form so this
helps make things more atomic

* More tests to understand bind-dimensions and the functions it depends on.

* Added test for three column query linking all columns to the same underlying table.

* Handle expression refs in indexed-models

Custom columns look like the following:

```clojure
{:expressions {"full-name" [:concat <first-name> <last-name>]}
```

To index values, we need a sequence of primary key and the associated
text value. So we select them from a nested query on the model. But the
model's way to refer to an expression and queries _on_ the model are
different. To the model, it's an expression. To queries based on the
model, it's just another field.

And have field refs in the result_metadata `[:expression
"full-name"]`. But when selecting from a nested query, they are just
string based fields: `[:field "full-name" {:base-type :type/Text}]`.

old style query we issued when fetching values:

```clojure
{:database 122
 :type :query
 :query {:source-table "card__1715"
         :breakout [[:field 488 {:base-type :type/Integer}]
                    [:expression "full name"]] ;; <-- expression
         :limit 5001}}
```

new style after this change:

```clojure
{:database 122
 :type :query
 :query {:source-table "card__1715"
         :breakout [[:field 488 {:base-type :type/Integer}]
                    [:field "full name" {:base-type :type/Text}]]
         :limit 5001}}
```

* Normalize field references

The schema was expecting valid mbql field refs (aka vectors and
keywords) but was getting a list and string (`[:field 23 nil]`
vs ("field" 23 nil)`). So normalize the field ref so we can handle the
stuff over the wire

this nice little bit of normalization lived in models.interface and
comped two functions in mbql.normalize. A few places reused it so moved
it to the correct spot.

* Better error message in `fix-expression-refs`

handles [:field ...] and [:expression ...] clauses. Seems unlikely that
aggregations will flow through here as that's not a great way to label a
pk. But i'll add support for that in a follow up

* Move `normalize-field-ref` below definition of `normalize-tokens`

`normalize-tokens` is `declare`d earlier, but we aren't using the var as
a var, but in a def we derefence it. But that's nil as it hadn't been
defined yet. Caused lots of failures downstream, including in cljs land

```clojure
user=> (declare x)
user=> (def y x) ;; <- the use in a def gets its current value
user=> (def x 3) ;; <- and it's not reactive and backfilling
user=> y
```

* Added tests for `has-matches?` and `resolve-overloading`

* Adding filter examples into the `resolve-overloading` and `has-matches"` tests.

Filter and metric matching logic is identical, but these examples are added for completeness and illustration.

* tests WIP trying to fix merge changes

* Removing tap

* Removing duplicate def

* Added tests for card-candidates

---------

Co-authored-by: dan sutton <dan@dpsutton.com>
Co-authored-by: Emmad Usmani <emmadusmani@berkeley.edu>
2023-09-08 18:25:17 +00:00
Case Nelson
151aa40082 [MLv2] Adds with-different-table to change source table or card (#33763) 2023-09-08 12:08:47 -06:00
Jesse Devaney
6d19ba942c Refactor Archive App (#33601)
* refactor use-list-select hook

- toggleAll(items) felt unintuitive as some items could be selected while simultaneously unselecting others
  - switched to selectOnlyTheseItems(items) to be more explicit on what the function is doing
- updated consumers of useListSelect to use the new API

* convert to functional component

* convert HoC ListSelect to hook useListSelect

* convert redux connects to useSelectors

* refactor ArchiveApp and improve types

* remove unused eslint disable line

* update useListSelect because of changes

* convert ArchivedItem to TypeScript

* refactor Search.loadList to useSearchListQuery

* add E2E tests for archive page

* refactor

- remove dead code
- refactor duplicated code

* fix type error

* fix variable usage

* fix broken scroll update
2023-09-08 13:01:44 -04:00
Jeff Bruemmer
6af5621e84 update releases (#33834) 2023-09-08 11:06:02 -04:00
Uladzimir Havenchyk
a939123f7c [Dashboard] Make parameters widget container not sticky on small devices (#33806) 2023-09-08 14:36:54 +00:00
Nemanja Glumac
ca7d43417e Add the official build for release workflow (#33362)
* Add the official build for release workflow

[ci skip]

* Store full-length SHA-1 commit hash in an artifact

* Trigger pre-release when the official build workflow finishes

* Download the official uberjar instead of building it again

* Adapt `check-commit` job to use the release artifact

* Adapt `check-uberjar-health` job to use the release artifact

* Adapt `run-sanity-check` job to use the release artifact

* Adapt `containerize` job to use the release artifact

* Adapt `verify-docker-pull` job to use the release artifact

[ci skip]

* Checkout the repo

We need the folder structure to satisfy the JAR path.
[ci skip]

* Make `check-uberjar-healt` dependend on the commit check job

* Fix commit-id file path

[ci skip]

* Fix `containerize` reference to the release artifact commit output

[ci skip]

* Fix `release-artifact` outputs

[ci skip]
2023-09-08 09:18:51 +02:00
Kamil Mielnik
45df944e87 Refactor useLeaveConfirmation hook to a component (#33801)
* Move useLeaveConfirmation hook to global hooks directory

* Use useBeforeUnload in useLeaveConfirmation

* Remove redundant custom onConfirm prop

* Convert useLeaveConfirmation to TS

* Fix router & route props in PermissionsPageLayout

* Refactor useLeaveConfirmation into LeaveConfirmationModal

* Move withRouter from PermissionsPageLayout to LeaveConfirmationModal

* Remove redundant _.compose call

* Sort props

* Fix build
- ./bin/i18n/update-translation-template did not recognize the syntax

* Sort props
2023-09-08 14:09:38 +07:00
Cam Saul
1ec0be3e3f Stop making my eyes bleed! (#33684)
* Stop making my eyes bleed!

* Fix Kondo warnings
2023-09-07 20:47:13 -07:00
Ryan Laurie
343b7cb7f9 Test entity ID parameterizations (#33758) 2023-09-07 23:55:25 +00:00
Cam Saul
4cbf655d06 Fix broken drill thrus/make sure all drill thrus product valid queries after application (#33737)
* Fix broken drill thrus

* Fix some inputs

* WHY ARE WE CONSTRUCTING ALL THESE CLAUSES BY HAND =(
2023-09-07 20:22:39 +00:00
Vamsi Peri
19b2168c9a Add a reminder note to pick either backport or no-backport label (#33799) 2023-09-07 15:53:54 -04:00
Case Nelson
bbcabdffee [MLv2] Column metadata to legacy-field-ref (#33623)
* [MLv2] Column metadata to legacy-field-ref

Fixes #33622

Pulled from https://github.com/metabase/metabase/pull/32698

* [experimental] Allow selecting MLv2 metadata directly from app DB using Toucan 2 shenanigans

* Fix file that changed in merge

---------

Co-authored-by: Cam Saul <github@camsaul.com>
2023-09-07 17:40:13 +00:00
Nicolò Pretto
7fbccf6d55 disable "download results" and "edit question" from xray dashcards that have not been saved (#33638)
* attempt at detecting if we're in xray

* use dashboard.id to detect if inside xrays

* e2e test for xray 33637

* isXray passed down as prop from AutomaticDashboard

* isXray moved to shouldRender

* test: add unit test for #33637

* refactor: put all conditional rendering logic inside DashCardMenu.shouldRender

* remove e2e test as we prefer unit

* refactor: rename shouldShowDashCardMenu -> shouldShowDashCardMenu as per pr feedback
2023-09-07 17:36:22 +00:00
Oisin Coveney
ae95faad62 Convert SearchResults.jsx to typescript (#33712) 2023-09-07 18:59:33 +03:00
Nemanja Glumac
15ad8b3ce7 Fix e2e skipped test naming 2 (#33804)
The original attempt was #33777.

As revealed in #33799, the issue hasn't been fully fixed.
Take a look at this run: https://github.com/metabase/metabase/actions/runs/6110515399

The skipped test names are now in this format: e2e-tests-collectionsslow-ee
Let's see how do we create a name:

name: e2e-tests-${{ matrix.folder }}${{ matrix.context }}-${{ matrix.edition }}
So it's obvious that both folder and context are included, when in reality we need only one of the two.

The flaw in the logic was trying to remove the runner from the matrix. At least ONE matrix parameter needs to be different in the slow context. We achieve this by setting the runner to ubuntu-latest instead of ubuntu-22.04. This should now finally fix the names.

[ci skip]
2023-09-07 17:09:37 +02:00
Mahatthana (Kelvin) Nomsawadi
e7363d97d6 Fix object detail crashing when a table from foreign key is hidden (#33697)
* Fix object detail crashing when a table from foreign key is hidden

* Add basic Object detail unit test

* Add the rest of the test

* Make fetch mock idiomatic

* Address feedback: Improve test name clarity

Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>

* Address feedback: Improve test readability and correctness

* Fix type error

---------

Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>
2023-09-07 14:19:57 +01:00
Kamil Mielnik
b6359f3bec Update copy in useLeaveConfirmation modal (#33789) 2023-09-07 13:18:28 +00:00
Ngoc Khuat
524ed31174 Fix fetching field values for remapped fields (#33632)
Co-authored-by: Mahatthana (Kelvin) Nomsawadi <me@bboykelvin.dev>
Co-authored-by: Mahatthana Nomsawadi <mahatthana.n@gmail.com>
2023-09-07 13:03:19 +00:00
Nemanja Glumac
27ad12fc65 Fix E2E test that's breaking pre-release workflow (#33787)
We had to adjust E2E tests when we removed H2 support.
That was done in #33212.

But this broke the pre-release workflow.
That workflow doesn't have necessary docker services needed for this test
(postgres and mysql).

On top of that, adding both databases in this test is kind of redundant,
and definitely an overkill. We just want to make sure we can add a database.
So, why not use SQLite that doesn't require external services?

This PR accomplishes exactly that.
It simplifies and speeds up this particular test by using SQLite database.
2023-09-07 07:01:15 -06:00
Kamil Mielnik
89b258b83c Remove unused "No changes to permissions will be made." confirmation in PermissionsEditBar (#33785)
* Remove unused "No changes to permissions will be made." confirmation in PermissionsEditBar
- Remove shouldConfirmCancel prop

* Sort props
2023-09-07 19:41:08 +07:00
Nemanja Glumac
5afb2ed046 Fix e2e skipped tests naming (#33777)
* Update additional context for E2E stubbed/skipped tests

* Include two new E2E groups to stubbed/skipped E2E tests
2023-09-07 10:35:08 +02:00
Noah Moss
e1f456df6c Don't delete a connection impersonation policy when non-data perms are updated (#33762)
* Don't delete a connection impersonation policy when non-data perms are modified

* refactor

* apply similar fix to gtap code

* set feature flag in test
2023-09-07 08:21:00 +00:00
Cam Saul
90b4cde9af Fix failing Vertica test (#33764) 2023-09-07 08:25:17 +02:00
Mark Bastian
191b8165b3 Indexed Entity X-Rays (#33656)
# Primary objective: From an indexed entity, located the items referencing that entity and make a dashboard for that entity. This will make several dashboards, one for each entity, so the strategy is to combine these all into a single dashboard with tabs. If there are no linked entities as simple dashboard indicating that nothing interesting is linked. If there is a single linked entity we create a single dashboard (no tab) but with the same linked entity title.

A few of the main nses that were affected and other bullet point changes:

* metabase.api.automagic-dashboards - The vast majority of the work to create the unified dashboard is found here.
* metabase.automagic-dashboards.core - Docs, cleanup, and destructuring for clarity
* metabase.api.search - Adding fix to realize search results
* metabase.automagic-dashboards.filters - Fix to build-fk-map so that parameters show up on model x-rays
* metabase.automagic-dashboards.populate - Fix typo
* metabase.api.search-test - Unit tests for search fix
* Brought over tab saving of transient x-ray dashboard code to save-transient-dashboard!

---------

## Overall summary

The primary entry point to these changes can be found in `metabase.api.automagic-dashboards` at:

```clojure
(api/defendpoint GET "/model_index/:model-index-id/primary_key/:pk-id" ...
```

A simple reproduction of dashboard creation from indexed entities is shown here:

```clojure
(let [model-index-id 54 ;; This and pk-id will be specific to some indexed entity in your system
      pk-id          1]
  (binding [api/*current-user-permissions-set* (delay #{"/"})
            api/*current-user-id*              1]
    (let [model-index       (t2/select-one ModelIndex :id model-index-id)
          model             (t2/select-one Card (:model_id model-index))
          model-index-value (t2/select-one ModelIndexValue
                                           :model_index_id model-index-id
                                           :model_pk pk-id)
          linked            (#'api.magic/linked-entities
                              {:model             model
                               :model-index       model-index
                               :model-index-value model-index-value})
          dashboard         (#'api.magic/create-linked-dashboard
                              {:model             model
                               :linked-tables     linked
                               :model-index       model-index
                               :model-index-value model-index-value})]
      dashboard)))
```

---------

## Fixed the query filter in `metabase.api.automagic-dashboards` so that `create-linked-dashboard` doe not produce bad queries.

We're no longer making joins back to the model's underlying
table. Recognizing that we were joining on linked table's fk to the
model's underlying table's pk and then searching where pk = <pk-value>,
we can just filter where fk = <pk-value>, omit the join.

So these tests just grab all of the linked tables and assert that one of
those filters is found.

eg, suppose a model based on products. the linked tables are orders and
reviews. And rather than the queries:

```sql
select o.*
from orders o
left join products p
on p.id = o.product_id
where p.id = <pk-value>
```

we can just do

```sql
select *
from orders
where product_id = <pk-value>
```

And similar for reviews. And for each query in the dashboard we're
looking for one of the following:

```clojure
, #{[:= $orders.product_id 1] [:= $reviews.product_id 1]}
```

---------

## Handle expression refs in indexed-models

Custom columns look like the following:

```clojure
{:expressions {"full-name" [:concat <first-name> <last-name>]}
```

To index values, we need a sequence of primary key and the associated
text value. So we select them from a nested query on the model. But the
model's way to refer to an expression and queries _on_ the model are
different. To the model, it's an expression. To queries based on the
model, it's just another field.

And have field refs in the result_metadata `[:expression
"full-name"]`. But when selecting from a nested query, they are just
string based fields: `[:field "full-name" {:base-type :type/Text}]`.

old style query we issued when fetching values:

```clojure
{:database 122
 :type :query
 :query {:source-table "card__1715"
         :breakout [[:field 488 {:base-type :type/Integer}]
                    [:expression "full name"]] ;; <-- expression
         :limit 5001}}
```

new style after this change:

```clojure
{:database 122
 :type :query
 :query {:source-table "card__1715"
         :breakout [[:field 488 {:base-type :type/Integer}]
                    [:field "full name" {:base-type :type/Text}]]
         :limit 5001}}
```

---------

## Normalize field references

The schema was expecting valid mbql field refs (aka vectors and
keywords) but was getting a list and string (`[:field 23 nil]`
vs ("field" 23 nil)`). So normalize the field ref so we can handle the
stuff over the wire

this nice little bit of normalization lived in models.interface and
comped two functions in mbql.normalize. A few places reused it so moved
it to the correct spot.

* Better error message in `fix-expression-refs`

handles [:field ...] and [:expression ...] clauses. Seems unlikely that
aggregations will flow through here as that's not a great way to label a
pk. But i'll add support for that in a follow up

* Move `normalize-field-ref` below definition of `normalize-tokens`

`normalize-tokens` is `declare`d earlier, but we aren't using the var as
a var, but in a def we derefence it. But that's nil as it hadn't been
defined yet. Caused lots of failures downstream, including in cljs land

```clojure
user=> (declare x)
user=> (def y x) ;; <- the use in a def gets its current value
user=> (def x 3) ;; <- and it's not reactive and backfilling
user=> y
```

* Don't capture `declare`d vars in a def

need late binding. when the function is called, those vars will have a
binding. But if we use a `def`, it grabs their current value which is an
unbound var.

---------

Co-authored-by: dan sutton <dan@dpsutton.com>
Co-authored-by: Emmad Usmani <emmadusmani@berkeley.edu>
2023-09-06 15:05:55 -06:00
metamben
53aeec80a3 Improve notebook editor performance (#33761)
* Add caching
* Hand roll simplify-compound-filter
2023-09-06 20:21:52 +00:00
Nemanja Glumac
be30839eb7 [POC] Faster E2E tests in CI (#33124)
* Run slow E2E tests using faster runner

* Tag slow tests

* Add additional x-ray tests to the slow batch
2023-09-06 18:13:45 +02:00
Ngoc Khuat
b23765f2d4 Update kondo config for http-kit and next.jdbc (#33706) 2023-09-06 09:12:52 -07:00
Jerry Huang
0f06c5b6d6 Switch pulse email sending to use bcc instead of sending a seperate email (#33604)
* inital commit

* fix tests

* update test

* fix tests

* fix tests

* fix tests

* fix tests

* update test

* update tests

* update tests

* address changes

* fix tests

* fix test

* fix tess

---------

Co-authored-by: adam-james <21064735+adam-james-v@users.noreply.github.com>
2023-09-06 09:01:26 -07:00
Nemanja Glumac
8cb63dfa51 Fix unresolved var lib.join/current-join-alias (#33747)
The build is failing on master due to :cause "No such var: lib.join/current-join-alias"
This breaking change was introduced in #33574.

Searching for current-join-alias shows that all other references use a different namespace. Namely, lib.join.util.
This PR uses that namespace instead.

The function was moved in #32698. Both PRs have been opened, and have had CI green before the merge, but got out of sync. A merge queue would've prevented this.
2023-09-06 15:59:36 +02:00
Alexander Polyankin
c14b844505 Mantine button color (#33720) 2023-09-06 15:32:48 +03:00
Nemanja Glumac
69e076d9da Fix download-uberjar job logic (#33745)
This log shows the output of the files changed:
https://github.com/metabase/metabase/actions/runs/6087912385/job/16537680230#step:3:602

```
Changes output set to ["shared_sources","frontend_sources","frontend_specs","frontend_all","backend_sources","backend_specs","backend_all","sources","e2e_specs","e2e_all","codeql","i18n","visualizations"]
```

Yet, the `download-uberjar` job ran, and the `build` never ran.
This resulted in E2E test failures due to missing FE changes.

The fault in the logic introduced in #33190 was thinking that
`needs.files-changed.outputs.e2e_specs == 'true'` means the only output,
when in reality it means one of many outputs.

This PR should fix this by making sure that `needs.files-changed.outputs.e2e_all != 'true'`
is also respected. This translates to - if there were no source code changes.

[ci skip]
2023-09-06 13:46:41 +02:00
Braden Shepherdson
ed6c220b67 [MLv2] Add functions to support viz settings in FE (#32698) 2023-09-06 13:25:28 +03:00
Kamil Mielnik
d3a9d9d601 Fix redundant network requests triggered in object detail modal (#33710)
* Extract ObjectDetailBody to a separate file

* Extract ObjectDetailHeader to a separate file

* Extract ObjectDetailView to a separate file
- extract ObjectDetailWrapper.styled.tsx

* Extract ObjectDetailHeader unit tests

* Extract ObjectDetailBody unit tests

* Rename ObjectDetail.unit.spec.tsx to ObjectDetailView.unit.spec.tsx

* Remove the non-null assertion operator

* Use relative import

* Introduce hasFks

* Do not loadFKReferences() when there was no previous zoomed row
- this function will be called in useMount hook's callback

* Use project-wide != null pattern

* Remove loadFKReferences() on mount because it is duplicated later by useEffect

* Extract ObjectRelationships.styled

* Extract ObjectDetailTable.styled

* Fix imports

* Add repro test for #32720
2023-09-06 17:11:09 +07:00
Denis Berezin
5020895090 Added MLv2 drills integration for FKFilter and SummarizeColumnByTime drills (#32402) 2023-09-06 08:59:58 +00:00
Alexander Polyankin
ab5a816ba3 Mantine Select (#33505) 2023-09-06 08:26:23 +03:00
Ngoc Khuat
d3d0e1ef45 mt/user-http-request to call the app handler directly (#32070) 2023-09-06 05:23:20 +00:00
Cam Saul
e944046fa7 Migrate metabase.sync* to Malli (#33682)
* Sync use Malli

* Test fixes

* One last test fix 🔧

* Update Kondo config

* Test fixes

* Revert accidental whitespace

* Fix whitespace

* Fix more mystery whitespace

* Remove byte order marks

* Test fixes 🔧
2023-09-06 03:57:52 +00:00
Cam Saul
7e532a86db Move MLv2 metadata schemas into a metabase.lib.schema namespace (#33665)
* Move MLv2 metadata schemas into a metabase.lib.schema namespace

* Fix schema ref

* Fix schema references
2023-09-06 01:23:13 +00:00
Ryan Laurie
9d3ea413b0 Parameterize collection and dashboard ids in e2e tests (#33570)
* parameterize collection and dashboard ids in e2e tests

* fix copyPasta errors

* appease the linter

* obey the linter
2023-09-05 13:59:23 -06:00
Cam Saul
00e2565e23 Implement timeseries zoom drill thru (#33574)
* First crack at drill-thru, adding quick-filter-drill

* Adding object detail drill

Needs tests for the multi-PK case

* Add distribution-drill and foreign-key-drill

* Add sort drill

* summarize-column and part of automatic-insights

* Add `display-info` for drill-thrus and the special pivot functions

Clean up and should be ready for FE first crack

* Add `drill-thru` implementations for all current drills

* small fixes

* overhaul of available-drill-thru

Fixes several issues with targeting, merges in Mode logic, fixes
pivot-drills

Still TODO: other drills' mode conditions; lots of checking and testing
the various cases of what should be shown; writing tests for that.

* Add `display-info` for drill-thrus and the special pivot functions

Clean up and should be ready for FE first crack

* Add `display-info` for drill-thrus and the special pivot functions

Clean up and should be ready for FE first crack

* Integrating the basic drill-thru ops, with some debugging hacks

* Fix bad spelling of parameters

* bunch of a progress, :null sentinel, refactor to context

* tests for lots more cases; two missing drills

* adding underlying records drills, not yet working

* fixing up to work with upstream changes

* fixes from Denis' PR

* more progress debugging FE drills and adding tests

* drill tests coming along

* cleanup, test fixes

* display-info-js for recursion

* Add TS typing for displayInfo of drill thrus

* partial changes for underlying records

* hack hack

* splitting out progression logic to a separate file

* First crack at drill-thru, adding quick-filter-drill

* Adding object detail drill

Needs tests for the multi-PK case

* Add distribution-drill and foreign-key-drill

* Add sort drill

* summarize-column and part of automatic-insights

* Add `display-info` for drill-thrus and the special pivot functions

Clean up and should be ready for FE first crack

* Add `drill-thru` implementations for all current drills

* small fixes

* overhaul of available-drill-thru

Fixes several issues with targeting, merges in Mode logic, fixes
pivot-drills

Still TODO: other drills' mode conditions; lots of checking and testing
the various cases of what should be shown; writing tests for that.

* Add `display-info` for drill-thrus and the special pivot functions

Clean up and should be ready for FE first crack

* Add `display-info` for drill-thrus and the special pivot functions

Clean up and should be ready for FE first crack

* Integrating the basic drill-thru ops, with some debugging hacks

* Fix bad spelling of parameters

* bunch of a progress, :null sentinel, refactor to context

* tests for lots more cases; two missing drills

* adding underlying records drills, not yet working

* fixing up to work with upstream changes

* fixes from Denis' PR

* more progress debugging FE drills and adding tests

* drill tests coming along

* cleanup, test fixes

* display-info-js for recursion

* Add TS typing for displayInfo of drill thrus

* partial changes for underlying records

* hack hack

* splitting out progression logic to a separate file

* Lint and test cleanup

* MLv2 pivot reorganization part 1

* MLv2 pivots reorganization

* Revert some unneeded changes

* Don't enable the histogram test

* Fix lint errors and add a drill-thru-method implementation for sort

* `drill-thru` should support > 3 args

* Implement timeseries zoom drill thru

* Fix circular refs

* Fix `mu/defmethod` for Cljs

* Fix reader error in commented-out code 😒

* appease Eastwood

* PR feedback

---------

Co-authored-by: Braden Shepherdson <braden@metabase.com>
Co-authored-by: Denis Berezin <denis.berezin@metabase.com>
2023-09-05 12:11:06 -07:00
Nemanja Glumac
75a32ad9ea Nit: Remove the redundant assertion from common_test.clj (#33723)
[ci skip]
2023-09-05 17:52:43 +02:00
Nemanja Glumac
f518801ce0 Download previously saved uberjar for E2E workflow (#33190)
* PoC: Download previously saved uberjar for E2E workflow

* Separate `e2e_specs` and `e2e_all` file path triggers

* Fix file path result oputput

* Refine E2E tests conditional trigger

* Further refine E2E tests conditional trigger

* Download the uberjar directly where it's needed

* Work around inability to dynamically define job ouputs

* First obtain the artifact, then run anything else

* Map job outputs

https://docs.github.com/en/actions/using-jobs/defining-outputs-for-jobs

* Apply changes to visual regression tests

* Final logic cleanup

* Work around the API rate limit
2023-09-05 17:52:14 +02:00
Oisin Coveney
8174b8da1b Export Prop types for Mantine Components (#33711) 2023-09-05 18:36:46 +03:00
Noah Moss
ed9b4a7e6e Don't decode SSO redirect URLs before extracting host (#33703)
* Don't decode SSO redirect URLs before extracting host

* clean ns

* re-add kondo ignore

* address feedback
2023-09-05 14:40:42 +00:00
Anton Kulyk
bff2ceb537 Remove external op on the FE (#33433)
* Remove external op on the FE

* Clean commit
2023-09-05 12:44:16 +01:00
Kamil Mielnik
dcee76ba53 Refactor - Break ObjectDetail down (#33694)
* Extract ObjectDetailBody to a separate file

* Extract ObjectDetailHeader to a separate file

* Extract ObjectDetailView to a separate file
- extract ObjectDetailWrapper.styled.tsx

* Extract ObjectDetailHeader unit tests

* Extract ObjectDetailBody unit tests

* Rename ObjectDetail.unit.spec.tsx to ObjectDetailView.unit.spec.tsx
2023-09-05 15:06:31 +07:00
adam-james
f0479dab92 Modify GET /api/user endpoint to only work for admins/group managers (#33217)
* Modify GET /api/user endpoint to only work for admins/group managers

* Restrict group managers to only see users of groups they manage

* Adjust segmented user tests and dedupe when user in multiple groups

* Revert a small change that broke other tests. Change wasn't strictly needed anyway.

* Properly enable premium feature :advanced-permissions in group-manager test

* Fix sandbox user list tests. Count query needs distinct now bc of how group manager user list is returned

* Add back the filter I forgot to include in the count query

* Unused require due to a change in one of the tests

* Fix group-manager permissions logic on the user endpoint

* Update src/metabase/api/user.clj

Co-authored-by: Noah Moss <32746338+noahmoss@users.noreply.github.com>

* Changed endpoint's logic and impl slightly

 - cleaner group-ids-for-manager query
 - use existing validation/check-manager-of-group
 - simplify group-id-clause since at that point we know that the user is admin or group manager

Added a test case to ensure group-manager still only gets their groups users when group_id is not supplied

These scenarious should be accounted for in this setup now

;; ADMIN GM group_id  GM of group_id OUTCOME
;; t     t    t            t         can see users from that group
;; t     t    t            f         can see users from that group (bc admin can see)
;; t     f    t            f         can see users from that group (bc admin can see)
;; t     t    f            f         can see all (admin can see all)
;; f     t    f            f         can see users from all groups they manage
;; f     t    t            t         can see users from that group
;; f     t    t            f         cannot see (bc non admin, GM of different group)

* Alter tests to correctly check 403 in OSS setting

* Modify test to use generic verified by text since User endpoint is now more restricted.

* Strange pulse e2e test. Intercept the user api call to circumvent for now

* request recipients through /api/user/recipients instead of /api/user

* I don't even know anymore. Why did this change now?

Seems that there's a collection ID where before there was a null,
which caused redirect to collection/root

---------

Co-authored-by: Noah Moss <32746338+noahmoss@users.noreply.github.com>
Co-authored-by: Jesse Devaney <22608765+JesseSDevaney@users.noreply.github.com>
2023-09-04 15:56:52 -03:00
Oisin Coveney
f861316193 Add Right Arrow Icon (#33674) 2023-09-04 17:09:46 +03:00
Cam Saul
7bacd2fa79 Migrate QP/drivers code to use MLv2 metadata directly; make another 100+ tests parallel and shave 12 seconds off test suite (#33429)
* QP MLv2 Metadata Provider follow-ons

* Update lots of stuff to use MLv2 metadata instead of legacy metadata

* Fix lint warnings

* B I G  cleanup

* Everything is neat

* Mention new test pattern in driver dev changelog

* Appease Cljs by renaming a bunch of namespaces

* Move more stuff over

* Fix kondo errors

* Fix even more things

* Test fixes

* Fix JS export

* Test fixes 🔧

* Fix final MongoDB test
2023-09-02 17:41:12 +00:00
metamben
2bd21bf897 48 cycle simple bumps (#33630)
* Bump simple changes
* Account for changed exception message
* Add buddy-sign license
* Use maven coordinates to select tools.build version
2023-09-02 12:15:45 +00:00
Jeff Bruemmer
d2fabad93b docs - deprecate beanstalk (#33067)
* alternatives

* remove links

* remove mentions of eb

* remove eb from rds page
2023-09-01 23:21:49 +02:00
Luis Paolini
5695df919b Adding Snowflake to the list of DB's (#33677)
... you can reference when using native questions
2023-09-01 22:21:08 +02:00
metamben
4792f8acc5 Use field ID as name if the field cannot be resolved (#33648)
Fixes #33490.
2023-09-01 18:53:48 +03:00
Cam Saul
1d2e85ddee Move drill thrus to their own namespaces & numerous bug fixes (#33572)
* First crack at drill-thru, adding quick-filter-drill

* Adding object detail drill

Needs tests for the multi-PK case

* Add distribution-drill and foreign-key-drill

* Add sort drill

* summarize-column and part of automatic-insights

* Add `display-info` for drill-thrus and the special pivot functions

Clean up and should be ready for FE first crack

* Add `drill-thru` implementations for all current drills

* small fixes

* overhaul of available-drill-thru

Fixes several issues with targeting, merges in Mode logic, fixes
pivot-drills

Still TODO: other drills' mode conditions; lots of checking and testing
the various cases of what should be shown; writing tests for that.

* Add `display-info` for drill-thrus and the special pivot functions

Clean up and should be ready for FE first crack

* Add `display-info` for drill-thrus and the special pivot functions

Clean up and should be ready for FE first crack

* Integrating the basic drill-thru ops, with some debugging hacks

* Fix bad spelling of parameters

* bunch of a progress, :null sentinel, refactor to context

* tests for lots more cases; two missing drills

* adding underlying records drills, not yet working

* fixing up to work with upstream changes

* fixes from Denis' PR

* more progress debugging FE drills and adding tests

* drill tests coming along

* cleanup, test fixes

* display-info-js for recursion

* Add TS typing for displayInfo of drill thrus

* partial changes for underlying records

* hack hack

* splitting out progression logic to a separate file

* First crack at drill-thru, adding quick-filter-drill

* Adding object detail drill

Needs tests for the multi-PK case

* Add distribution-drill and foreign-key-drill

* Add sort drill

* summarize-column and part of automatic-insights

* Add `display-info` for drill-thrus and the special pivot functions

Clean up and should be ready for FE first crack

* Add `drill-thru` implementations for all current drills

* small fixes

* overhaul of available-drill-thru

Fixes several issues with targeting, merges in Mode logic, fixes
pivot-drills

Still TODO: other drills' mode conditions; lots of checking and testing
the various cases of what should be shown; writing tests for that.

* Add `display-info` for drill-thrus and the special pivot functions

Clean up and should be ready for FE first crack

* Add `display-info` for drill-thrus and the special pivot functions

Clean up and should be ready for FE first crack

* Integrating the basic drill-thru ops, with some debugging hacks

* Fix bad spelling of parameters

* bunch of a progress, :null sentinel, refactor to context

* tests for lots more cases; two missing drills

* adding underlying records drills, not yet working

* fixing up to work with upstream changes

* fixes from Denis' PR

* more progress debugging FE drills and adding tests

* drill tests coming along

* cleanup, test fixes

* display-info-js for recursion

* Add TS typing for displayInfo of drill thrus

* partial changes for underlying records

* hack hack

* splitting out progression logic to a separate file

* Lint and test cleanup

* MLv2 pivot reorganization part 1

* MLv2 pivots reorganization

* Revert some unneeded changes

* Don't enable the histogram test

* Fix lint errors and add a drill-thru-method implementation for sort

* `drill-thru` should support > 3 args

* Fix `mu/defmethod` for Cljs

* Fix reader error in commented-out code 😒

* appease Eastwood

---------

Co-authored-by: Braden Shepherdson <braden@metabase.com>
Co-authored-by: Denis Berezin <denis.berezin@metabase.com>
2023-09-01 06:46:16 +00:00
Cal Herries
b8489bd046 Create a privilege table and update it on sync for postgres (#33415) 2023-09-01 05:33:35 +00:00
Noah Moss
39ae29a757 Quote connection impersonation roles (#33651)
* quote impersonation roles for postgres conn impersonation

* also quote snowflake roles
2023-08-31 23:58:35 +00:00
metamben
58653e8146 Restore cumulative aggregations before annotation (#33620)
Fixes #21502.

* Fix flaky test
* Fix all occurrences of the typo replaced-indecies
2023-08-31 20:36:48 +00:00
Noah Moss
811bdd82e1 error if user doesnt have the impersonation attribute set (#33649) 2023-08-31 16:25:00 -04:00
Jesse Devaney
a608920fbf Refactor useListSelect hook (#33600)
* refactor use-list-select hook

- toggleAll(items) felt unintuitive as some items could be selected while simultaneously unselecting others
  - switched to selectOnlyTheseItems(items) to be more explicit on what the function is doing
- updated consumers of useListSelect to use the new API

* convert to typescript

* improve types

* add desired behavior verification for useListSelect
2023-08-31 16:01:16 -04:00
Cam Saul
7b962f73aa Fix Liquibase when running Cypress tests locally (#33629) 2023-08-31 18:05:37 +03:00
Noah Moss
c1d88baef0 Require default role to be set for using connection impersonation (#33444)
* throw exception if impersonated db doesn't have default role

* change text in snowflake plugin file

* fix bugs and add tests

* FE changes

* inline enabled? call

* add new driver feature connection-impersonation-requires-role

* use variant=brand

* break out impersonation-enabled-for-db? into a defenterprise helper function
2023-08-31 13:50:53 +00:00
Cam Saul
7ecde0dd52 Add findColumnForLegacyRef and findFilterableColumnForLegacyRef (#33569)
* MLv2: add `findColumnForLegacyRef` and `findFilterableColumnForLegacyRef`

* Fix JS tests

* Fix typo

* Remove stray comment
2023-08-31 04:06:58 +00:00
Ryan Laurie
8d6f164277 Obey hidden widget settings in ColumnSettings widgets (#33464)
* obey hidden widget settings in ColumnSettings widgets

* always show unambiguous sample dates
2023-08-30 14:50:40 -06:00
Noah Moss
66322524e6 Lower-case column names returned from internal queries so that they work with H2 (#33355)
* lower-case column names in internal queries so that things dont break for h2

* fix tests

* Update enterprise/backend/test/metabase_enterprise/audit_app/pages_test.clj

Co-authored-by: Ngoc Khuat <qn.khuat@gmail.com>

---------

Co-authored-by: Ngoc Khuat <qn.khuat@gmail.com>
2023-08-30 20:36:34 +00:00
metamben
ddc5cd2bd7 Make with-join-alias handle any unexpected value (#33618)
It's not only nil that can cause trouble, in some situations maps
(i.e., incomplete columns) can reach this point too.
2023-08-30 12:16:53 -06:00
Emmad Usmani
176ded679f fix url bug in sandbox editor (#33469) 2023-08-30 14:38:09 +00:00
Braden Shepherdson
e33b06fc8f [MLv2] Lay the foundation for implementing drill-thrus in MLv2 (#31735)
There are still some pieces missing, but this has gone far enough to prove the concept. Follow-up PRs can carry this forward.

## Missing parts

- Three drills (`automatic-insights`, `format`, `zoom-in`) are unimplemented.
- A handful of drills will be returned by `available-drill-thrus` but do not have `drill-thru-method` implementations so they can't be applied.
- Two or three drills have extra FE-only changes that need to be captured somewhere else. (Eg. changing the `card.display`)

## Interface

- `available-drill-thrus` returns opaque maps describing the set of applicable drills
- `display-info` on the drills to get an FE-friendly object
- `drill-thru` to apply a drill to a query when clicked.
2023-08-30 09:21:00 -04:00
Ngoc Khuat
9cffa38fc6 Index unindexed FKs for Postgres (#33578) 2023-08-30 11:55:02 +00:00
Cam Saul
e55e7f78c7 MLv2: generate 'consistent' display names (#33510)
* MLv2: generate 'consistent' display names (#24703)

* Handle blank 'source' description correctly

* Fix failing test
2023-08-30 05:19:48 +00:00
Mahatthana (Kelvin) Nomsawadi
81e14efb19 Modify the reproduction of #27768 to match the current state (#33588) 2023-08-30 05:36:36 +01:00
Alexander Polyankin
22e3ced240 Deprecate components for which mantine counterparts exist (#33597) 2023-08-29 23:54:26 +03:00
Cam Saul
7daf9d6a68 Fix required-native-extras for Cljs and add TypeScript wrappers (#33552)
* Fix `required-native-extras` for Cljs and add TypeScript wrappers

* Oops add missing TS function impls
2023-08-29 20:35:37 +00:00
Nick Fitzpatrick
74be152fbb ChartWithLegend refresh mode (#33590) 2023-08-29 14:30:59 -06:00
Vamsi Peri
3b79aa2a0e Cloverage on master (#33398)
* Run Cloverage job only on merge to `master`

* Use shorter `github.ref_name`

* [Reopened] Run Cloverage job only on merge to master

---------

Co-authored-by: Nemanja <31325167+nemanjaglumac@users.noreply.github.com>
2023-08-29 13:08:35 -04:00
metamben
4b27f570db Let filter-parts preserve binning/bucketing information of column (#33544)
Fixes #33527.
2023-08-29 15:37:50 +00:00
Alexander Polyankin
55c09b43d5 Mantine Paper (#33491) 2023-08-29 18:15:54 +03:00
Cam Saul
435fada0b2 MLv2 schema should enforce distinct breakouts and fields (#33512)
* MLv2 schema should enforce  distinct breakouts and fields #32489

* Enforce distinct breakouts and fields (#32489)
2023-08-29 03:25:21 +00:00
Vamsi Peri
f8ba495992 Run chromatic ci with label (#33507)
* Run chromatic CI job when there is a label called chromatic

* Fix: Run chromatic job when one of the labels is chromatic

* Run frontend checks when a new label is added - this will cover adding chromatic label too

* added unlabeled event to frontend workflow

* undo formatting changes
2023-08-29 02:39:34 +00:00
Jeff Bruemmer
ff4eb91b30 update anchor link (#33551) 2023-08-28 14:58:42 -06:00
Jerry Huang
9c7ed363ca Fix rendering issue with hidden columns (#33518)
* fix rendering deleted columns

* update fn name
2023-08-28 20:39:25 +00:00
Alexander Polyankin
ca8f88f1b1 Fix passing args in storybook for mantine components (#33536) 2023-08-28 21:40:12 +03:00
Denis Berezin
8ae401a968 Fix underlying records drill title for negative metric values (#33506) 2023-08-28 16:42:23 +00:00
Nick Fitzpatrick
de7ce0e2f5 Moving Dashboard name to HTML Node (#33463) 2023-08-28 13:08:14 -03:00
Nicolò Pretto
e38826911b rename jest config file to default naming to make it pickup automatically (#33529) 2023-08-28 17:22:29 +02:00
Jeff Bruemmer
d22bd5b070 update examples (#33534) 2023-08-28 10:25:35 -04:00
Ryan Laurie
98c00f8bd2 reduce flakes in x-ray test (#33420) 2023-08-28 08:05:48 -06:00
Ryan Laurie
45b6424b6f Fix null series title in line charts (#33331)
* show empty value for breakouts in settings and legend

* add and update tests

* handle empty column breakouts in rowcharts

* show legend for single cardinality breakouts
2023-08-28 08:05:30 -06:00
Cal Herries
95bf6a9093 Fix typo (#33522) 2023-08-28 13:18:15 +00:00
Mahatthana (Kelvin) Nomsawadi
a989649ffd Fix question name not showing when using Entity.Name (#33432)
* Fix question name not being shown in some cases

* Remove export default to conform to the styleguide

* Convert EntityName to TypeScript

* Fix question name not renderding when using EntityName

* Add a test to cover #33192
2023-08-28 10:48:58 +01:00
Mahatthana (Kelvin) Nomsawadi
2e16e356e7 Add test to cover #16151 (#33431) 2023-08-28 05:35:02 +01:00
Mahatthana (Kelvin) Nomsawadi
d56dd469b5 Add test to cannot use click behavior on boolean columns on MySQL (#33400)
* Add missing types in Cypress

* Add a repro for metabase#18067
2023-08-28 05:34:48 +01:00
Cam Saul
5116f76bad Fix #33083 (part 2) (#33453)
* Fix #33083 (part 2)

* Equality nonsense

* Test fix

* Remove leftover test

* Cljs fix

* Appease Kondo

* Appease Kondo more

* PR feedback

* `index-of-matching-metadata`

* Update some other things to use `index-of-closest-matching-metadata`

* PR feedback

* Don't use metadata provider for ref <=> metadata comparisons

* mark-selected-columns doesn't need metadata provider

* Update some join stuff to match with metadata

* Update more stuff to use `closest-matching-metadata`

* Test fix 🔧

* Test fix

* Take advantage of the QP now using MLv2 metadata providers to simplify test

* Well ok maybe we do need the 3-arity after all =(

* Test fix

* Remove stray NOCOMMIT

* Some cleanup and extra tests

* Hopefully the last few test fixes

* Ok NOW I think I fixed stuff.

* Add a test for binning display name (degrees)

* Fix indentation

* Give up on the Card nonsense for now

* Ok I give up

* Revert changes to testing
2023-08-26 17:59:50 +00:00
Alexander Polyankin
167153ca32 Mantine TextInput and NumberInput (#33381) 2023-08-25 20:10:46 +00:00
Cam Saul
b316c60456 Some MLv2 joins conveniences (#33454) 2023-08-25 14:13:06 -05:00
metamben
0d64e17783 Handle nil in with-join-alias (#33502) 2023-08-25 18:52:35 +00:00
Jeff Bruemmer
06b8bf68c7 docs - recipient suggestion controls (#33500) 2023-08-25 18:10:56 +00:00
Cam Saul
f58359289e Crazy fast QP tests! **I shaved 21 seconds off the test suite this week alone!** (#33483) 2023-08-25 08:57:28 -07:00
Nicolò Pretto
738bc1b703 re-export BoxProps from mantine/core (#33493) 2023-08-25 15:24:37 +02:00
Cal Herries
d161a9cf59 Allow native questions with filters with default values to be cleared (#31891) 2023-08-25 09:56:59 +00:00
metamben
f72e985ed0 Add find-filter-for-legacy-filter conversion helper (#33426) 2023-08-24 20:06:57 +00:00
Cam Saul
a66db9e981 QP: use MLv2 metadata provider. Eliminate 50% of app DB calls and improve performance by 10%+ (#33221)
* QP use MLv2 metadata provider (34/2)

* (22/2)

* (21 / 0)

* (20 / 4)

* (7 / 2)

* (2/0)

* Cleanup; (3/0)

* Last two test fixes

* (36 / 2)

* (8 / 1)

* Reorder stuff

* Test fixes 🔧

* Test fixes

* Some test fixes

* More test fixes 🔧

* Test fix 🔧

* MongoDB test fix

* B I G  cached metadata provider performance improvements

* Revert breaking change

* Fix Kondo

* Make sure application database metadata provider returns Database :features

* Test fix 🔧

* Parallel tests for QP macroexpansion middleware

* `with-current-user` is fine in parallel tests.

* Add test util remap metadata providers and rework remap middleware to use mock MLv2 data

* Address PR feedback

* Improve unrelated flaky test

* Some test improvements

* Fix lint error

* MLv2-ize `nest-query-test`

* Fix typo in PR feedback changes

* More parallelization and test fixes 🔧

* Convert lots more tests to mock metadata

* Test fix? 🔧

* Fix Card update logic

* Another Card update logic fix 🔧

* Another round of fixes 🔧

* Hopefully no more test fixes 🔧

* Evil test fixes 🔧

* Test fix 1

* Test fix
2023-08-24 19:20:20 +00:00
Uladzimir Havenchyk
ec26c7ec66 Put hash to the bundle filename instead of query (#33459)
vendor.bundle.js?4f4d380db6ab590ae9c1 -> vendor.4f4d380db6ab590ae9c1.js
2023-08-24 18:18:09 +00:00
Jerry Huang
94f748bfd2 Fix issue with some table columns that are unable to be rendered (#33448)
* fix render table

* update change
2023-08-24 18:11:01 +00:00
metamben
df163979fd Add filter-parts conversion helper (#33419) 2023-08-24 18:06:00 +00:00
metamben
9a9216fc8b Add find-visible-column-for-legacy-ref (#33447) 2023-08-24 20:49:55 +03:00
Vamsi Peri
aaa758bcb1 Run chromatic CI job when there is a label called chromatic (#33462)
* Run chromatic CI job when there is a label called chromatic

* Fix: Run chromatic job when one of the labels is chromatic
2023-08-24 13:25:54 -04:00
Luiz Arakaki
1b37235b43 Add Materialize as a partner driver (#33409) 2023-08-24 17:24:34 +00:00
Harsiddh Dave
0f23f31962 Update README.md with steps to setup Dev environment (#32365)
* Update README.md with steps to setup Dev environment

Added steps to setup development environment on your local system

* Update README.md

Co-authored-by: Jeff Bruemmer <jeffbruemmer@gmail.com>

* Update README.md

Co-authored-by: Jeff Bruemmer <jeffbruemmer@gmail.com>

* Update README.md

Co-authored-by: Jeff Bruemmer <jeffbruemmer@gmail.com>

* Update README.md

Co-authored-by: Jeff Bruemmer <jeffbruemmer@gmail.com>

* Update README.md

Co-authored-by: Jeff Bruemmer <jeffbruemmer@gmail.com>

* Update README.md

Co-authored-by: Jeff Bruemmer <jeffbruemmer@gmail.com>

---------

Co-authored-by: Jeff Bruemmer <jeffbruemmer@gmail.com>
2023-08-24 12:21:31 -04:00
Ngoc Khuat
742f4a61c5 Migrate to the new with-temp (#33440) 2023-08-24 15:57:48 +00:00
Jeff Bruemmer
482f729a7a note on serialization issues (#32360) 2023-08-24 15:54:42 +00:00
Alexander Polyankin
e26e58229a Forbid mantine usages outside of ui folder (#33456) 2023-08-24 16:57:20 +03:00
Alexander Polyankin
b3b71e40ef Fix eslint/import plugin config (#33455) 2023-08-24 16:56:47 +03:00
Uladzimir Havenchyk
06918d8aca [Filter] Save value on blur in text/number based widgets with sql query (#33374)
* Add test

* Update imports

* Add value normalization and save value on blur

* Update e2e/test/scenarios/dashboard-filters/dashboard-filters-sql-number.cy.spec.js

Co-authored-by: Mahatthana (Kelvin) Nomsawadi <me@bboykelvin.dev>

* Update e2e/test/scenarios/dashboard-filters/dashboard-filters-sql-number.cy.spec.js

Co-authored-by: Mahatthana (Kelvin) Nomsawadi <me@bboykelvin.dev>

* Use helper

* Simplify test

---------

Co-authored-by: Mahatthana (Kelvin) Nomsawadi <me@bboykelvin.dev>
2023-08-24 12:26:18 +00:00
abdul aziz ali
da85276c07 Add new environment setting reset-token-ttl-hours (#32132)
* Add new setting reset-token-ttl-h. Expose in selectors (#12829)

* Add reset-token-ttl-h setter, fix call in reset-token-ttl-ms. Add additional reset-token-ttl-h tests. (#12829)

* Revert previous changes. Define reset-token-ttl-hours and reset-token-ttl-hours-test (#12829)

* Fix formatting errors (#12829)
2023-08-23 19:12:28 -04:00
Luiz Arakaki
c6583878a7 add materialize as a partner driver and remove it from community (#33412) 2023-08-23 16:19:12 -04:00
Jeff Bruemmer
db6f80779a docs - note on reverting to default homepage (#33434) 2023-08-23 12:28:50 -04:00
Luiz Arakaki
88137845a0 Add Materialize logo asset for frontend client (#33437)
Co-authored-by: Bobby Iliev <bobby@bobbyiliev.com>
2023-08-23 10:33:24 -04:00
Cal Herries
d9cd059a4a Only log session cookie SameSite=None warning when connection is insecure (#33386) 2023-08-23 17:19:15 +03:00
Cam Saul
d54caf8894 Parallelize QP tests (August 2023 attempt) (#33068)
* Parallel QP tests; linter improvements; move QP test fns

* Cleanup

* Move query->expected-cols

* Fix QP test namespace

* Test fix 🔧

* Fix merge issues

* Revert unrelated changes

* Test fix 🔧

* Fix some things that are actually ^:parallel safe

* Remove Oracle logic for destroying DBs from different sessions since we don't test on AWS anymore

* Use ReentrantReadWriteLock for getting + creating test datasets to avoid race conditions

* Add non-`metabase.test` versions of things to the disallowed list for `^:parallel` tests
2023-08-22 19:44:02 +00:00
Luis Paolini
7bf6112f4a Update running-metabase-on-azure.md (#32709) 2023-08-22 20:09:21 +02:00
Cam Saul
a195650fe4 Fix #33083 (#33395) 2023-08-22 09:07:45 -07:00
Uladzimir Havenchyk
1efa6c6f00 Import types with a keyword type (#32678)
* Update react related imports

* Update places with combined default and named type

* Autofix type imports

* Fix unused eslint-disable

* Include cljs_release to eslintignore

* Autofix type imports

* Add typescript rule
2023-08-22 15:15:07 +00:00
Cam Saul
807ea42992 Make sure we're not doing application DB calls on core.async threads (#33397) 2023-08-22 22:00:45 +07:00
Roman Abdulmanov
3fcc04c1e2 Minor text change (#33404) 2023-08-22 16:56:03 +04:00
Roman Abdulmanov
7acd20a7f6 Bug triage integration with Slack (#33402)
Added bug bot integration with Slack
2023-08-22 16:41:05 +04:00
Mahatthana (Kelvin) Nomsawadi
3805e93785 Add test to dashboard parameter should occupy whole horizon space when navigating to dashboards inapp in interactive embed (#33337)
* Add a repro for #30645

* Reuse util function

* Extract logic to generate next unsaved card id to another function
2023-08-22 13:26:15 +01:00
Alexander Polyankin
9b058b823b Make mantine colors compatible with v7 (#33372) 2023-08-22 14:47:26 +03:00
Vamsi Peri
120dc56cdb Revert "Run Cloverage job only on merge to master (#33270)" (#33396)
This reverts commit a577652992.
2023-08-21 23:08:24 -04:00
Nemanja Glumac
a577652992 Run Cloverage job only on merge to master (#33270) 2023-08-21 23:07:42 -04:00
lbrdnk
6e2a43de74 Add recursive capabilities to segment expansion (#32342)
* Add recursive capabilities to segment expansion

* Add test

* Add error type

* Update `nested-segments-test`

* Remove redundant `Database` and `Table`

* Convert use of `with-temp*` to `t2.with-temp`
2023-08-21 14:29:11 -07:00
Noah Moss
dcfa4c9f33 remove audit view migrations (#33312) 2023-08-21 17:14:33 -04:00
metamben
66245a66f0 Fix handling of JS undefined (#33387)
In CLJS there's no distinction between nil and undefined, but JS there is
and goog.object/get does not check undefined.
2023-08-22 00:13:18 +03:00
Jesse Devaney
1711c38f7b Fix: stop prompting non-admin users to configure email or slack (#32989)
* fix specific aria-label for generic sidebar

* hide dashboard subscription button

- when user is non-admin and email & slack are not configured

* forward non-admin user to configured subscription form

* fix: show pulse list after creation for non-admins

- when pulse count is 0 and a new pulse is added by non-admins, it used to auto-redirect to the creation form again b/c the new pulse was not loaded before the forwarding would occur again

* refactor magic strings

* fix error when pulses has no length attribute

* validate forwarding in subscriptions for non-admins

* add remaining specs

* updated tests for new subscriptions forwarding for non-admins

* update tests for subscriptions forwarding for non-admins

* update tests for subscriptions forwarding for non-admins

* fix unit tests

* update dashboard subscriptions button to exclude heading cards

* [WIP] convert E2E tests to unit tests

* convert subscriptions button test to unit test

* restore some E2E tests

* fix unit tests

- new fetch request occurring in child component DashboardHeader was causing these tests to fail on the fetch request because there was no fallback
2023-08-21 17:04:09 -04:00
Cal Herries
47e7e47089 Refactoring: Add clearFilterWidget e2e helper (#33332) 2023-08-21 18:02:00 +00:00
Uladzimir Havenchyk
c64c7cc939 Rework Popover to avoid warnings from react (#33369) 2023-08-21 11:41:02 +00:00
Kamil Mielnik
d4bbb52b59 Add reproduction test - Broken added series on dashcard prevents you from editing the card (#33328)
* Use findByLabelText as we're targeting a checkbox input

* Add reproduction test for #22265

* Break second question after adding it to series

* Format code

* Correct the repro: Use valid question first before turning it invalid

* Speed up E2E test by preparing data using API

---------

Co-authored-by: Mahatthana Nomsawadi <mahatthana.n@gmail.com>
2023-08-21 12:39:33 +01:00
Nemanja Glumac
f363a6966f Split admin E2E group and merge it with auditing (#33357)
* Split `admin` E2E group and merge it with `auditing`

* Run new `admin-2` group in CI
2023-08-21 13:03:45 +02:00
Alexander Polyankin
d9154056ee Fix findDOMNode in Popover (#33367) 2023-08-21 13:30:27 +03:00
Alexander Polyankin
f1d2316bfc Fix CSP issues in the color picker (#33349) 2023-08-21 09:45:38 +00:00
Ngoc Khuat
cd69f15761 Refactor error handling for implicit actions (#32935) 2023-08-20 07:46:06 +00:00
Ryan Laurie
bb24bedacd Update H2 tests (#33212)
* remove add new h2 db test

* update setup specs to test mysql and postgres connections

* check for mongodb connection string errors
2023-08-19 11:02:19 +00:00
Aleksandr Lesnenko
683b2c286f Fix no self service export (#33317)
* Pass dashboardId and dashcardId in QueryDownloadWidget in ViewFooter
* Add missing dashboardId and dashcardId in QueryDownloadWidget.tsx
* spec

---------

Co-authored-by: Robin <e.robin154@gmail.com>
2023-08-18 14:44:13 -05:00
Alexander Polyankin
10c5bc7def Pass nonce for google button styles (#33339) 2023-08-18 19:27:01 +00:00
Nemanja Glumac
198e74106c Remove unused update-version-info script (#33344) 2023-08-18 11:43:35 -07:00
Nemanja Glumac
cd6aa464d4 Rename build.version-info to version-properties (#33345)
We have to sets of functions that deal with the information about Metabase version.
1. During build process we create `version.properties` file
2. During release we create new `version-info.json` or `version-info-ee.json` files that we store in AWS

The first contains the information about the current Metabase version.
It's used to generate info in "About Metabase" window, among others.

Calling both namespaces `version-info` leads to unnecessary confusion.
This commit should make the disctinction between the two more obvious and clear.
2023-08-18 20:42:59 +02:00
Alexander Polyankin
f734097bf1 Mantine Loader (#33329) 2023-08-18 21:17:51 +03:00
Alexander Polyankin
dbfca6c6d1 Use variants API (#33333) 2023-08-18 14:20:07 +00:00
Uladzimir Havenchyk
149f199298 Add a repro for the issue 16663 (#33268)
* Add a repro for 16663

* Make test real

* Address review

* Update e2e/test/scenarios/dashboard-filters/reproductions/16663-filters-can-stay-in-url.cy.spec.js

Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>

* typo

---------

Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>
2023-08-18 14:19:16 +00:00
Alexander Polyankin
f9d328cb8f Mantine Title (#33277) 2023-08-18 11:07:27 +00:00
Mahatthana (Kelvin) Nomsawadi
f0dd90e64b Add an E2E test to click behavior not working on non-numeric ID fields (#33254)
* Modify an E2E test and unskipped it

* Fix calling wrap when table is undefined

* troubleshooting CI

* Fix failed test on CI
2023-08-18 07:53:52 +01:00
Ngoc Khuat
3d2d69b687 Fix field Values search for PKs (#33006) 2023-08-18 06:36:31 +00:00
Oisin Coveney
65c91608f0 Ensure that entity links aren't opened in new tab (#33260) 2023-08-18 02:14:42 +03:00
Nick Fitzpatrick
333fbad5c6 Adding is-true and is-false operators (#33062)
* Adding is-true and is-false operators

* Adding unit tests

* All Operators adjustment

* PR Feedback

* add "is equal to" in spec

* adding e2e test

---------

Co-authored-by: Jesse Devaney <22608765+JesseSDevaney@users.noreply.github.com>
2023-08-17 18:00:14 -03:00
Nemanja Glumac
02a0143d3c Optimize the frontend CI workflow (#33269)
We're currently running way too many jobs on every single commit in CI.

Frontend code coverage is a good example.
We can safely move it to run only on the merge to master.

Experimental run showed that running FE unit tests without the coverage takes 22 minutes.
The run with the coverage takes ~33 minutes on the same machine.

Furthermore, we don't have to run Chromatic on every single run.
On merge to master should be more than enough.
2023-08-17 22:16:44 +02:00
Nick Fitzpatrick
ebf47f88aa Removed placeholder, added issuer props to list of saml settings (#33247)
* added issuer props to list of saml settings

* adding e2e test

* using unit test instead
2023-08-17 17:06:02 -03:00
Alexander Polyankin
064f7a8f4a Allow custom fonts in mantine components (#33271) 2023-08-17 16:53:34 +00:00
Anton Kulyk
54d1d6ad2c Convert NativeQueryEditor subcomponents to TypeScript (#33226)
* Convert `VisibilityToggler` to TypeScript

* Conver `RightClickPopover` to TypeScript

* Convert `DataReferenceButton` to TypeScript

* Convert `NativeVariablesButton` to TypeScript

* Convert `SnippetSidebarButton` to TypeScript

* Convert `NativeQueryEditorSidebar` to TypeScript

* Make `size` prop required for sidebar buttons

* Fix setting default prop value twice

* Address comments

* Remove `NativeVariablesButton.shouldRender`
2023-08-17 16:23:33 +01:00
metamben
3f2b9ab091 Add test for metabase.lib.js.metadata/parse-objects (#33239) 2023-08-17 18:01:21 +03:00
Jeff Bruemmer
7b87247a2b fix link (#33273) 2023-08-17 14:49:29 +00:00
Kamil Mielnik
bb00748b09 Show new syncing tables as greyed out in data reference page (#33157)
* Add disabled prop to ListItem

* Disable syncing tables in data reference page

* Add disabled prop to Root

* Format code

* Add a test case for disabled ListItem

* Extract PLACEHOLDER_TEXT

* Fix typo

* Update test name

* Add test boilerplate

* Add a basic rendering test for TableList

* Add data-testid prop to ListItem

* Add tests for tables with various initial_sync_status

* Improve assertions

* Add style assertions

* Remove unused argument and inline defaultProps
2023-08-17 19:58:48 +07:00
Alexander Polyankin
a09e3ee149 Mantine button (#33175) 2023-08-17 15:27:56 +03:00
Anton Kulyk
e3f49cddc3 Convert TagEditorSidebar to TypeScript (#33227)
* Convert `TagEditorHelp` to TypeScript

* Convert `TagEditorParam` to TypeScript

* Convert `TagEditorSidebar` to TypeScript

* Fix export
2023-08-17 13:17:17 +01:00
Anton Kulyk
0ef26e645c Convert native QB actions to TypeScript (#33234) 2023-08-17 13:16:48 +01:00
Nemanja Glumac
a47039c6b6 Fix E2E models flake (#33257)
The flake happened when adding models to the dashboard
due to the conflicting intercepted routes that we're waiting for.

This commit removes intercepts and waits altogether.
It relies on UI instead.

Example of a failed run:
https://github.com/metabase/metabase/actions/runs/5882560809/job/15953891019?pr=33245#step:14:502
2023-08-17 06:04:03 -06:00
Nicolò Pretto
bec9c9581f refactor with pull request comments 33128 (#33256) 2023-08-17 12:53:50 +02:00
Cal Herries
b5da00bbc3 Remove hasParameterValue (#33223) 2023-08-17 11:21:41 +03:00
Nemanja Glumac
35653d3096 [E2E] Downloads in embedded questions (#32626)
* Add E2E tests for downloads in embedding questions pt1

This commit adds tests that make sure preventing downloads from the
embedding questions is not possible without a token.

* Add E2E tests for premium embedding downloads

This commit adds tests that make sure the premium token allows one to
disable downloads for embedded questions.
2023-08-17 07:52:21 +02:00
Jerry Huang
fac827fab9 Hide columns from SQL Query such that they will take effect in dashboard subscription email/slack (#32991)
* initial columns

* fix tests

* only filter when exists

* add test

* add whitespace

* add noah code

* fix test

* add column reordering

* fix issues with column ordering

* rename test

* Update src/metabase/pulse/render/body.clj

Co-authored-by: Noah Moss <32746338+noahmoss@users.noreply.github.com>

---------

Co-authored-by: Noah Moss <32746338+noahmoss@users.noreply.github.com>
2023-08-17 02:31:05 +00:00
Jeff Bruemmer
59d727d746 docs - add weekday example (#33248) 2023-08-17 00:00:08 +00:00
Case Nelson
5d9f2bf64b [MLv2] Include temporal-bucketing on selected join condition columns (#33138)
* [MLv2] Include temporal-bucketing on selected join condition columns

* Update test/metabase/lib/join_test.cljc

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>

---------

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>
2023-08-16 14:04:55 -06:00
shaun
b1c0b5042c Allow creating a collection on the go when duplicating items (#33118) 2023-08-16 13:58:00 -05:00
Cal Herries
ca2059f34e Refactor viz auto-selection: merge switchTableScalar into maybeResetDisplay (#33185) 2023-08-16 18:33:28 +00:00
Aleksandr Lesnenko
b28d01458c describe the visualization interface (#33196) 2023-08-16 18:18:57 +00:00
Jeff Bruemmer
411d4b20f2 docs - serialization migration note (#32414)
* migration note

* note about same version
2023-08-16 17:04:39 +00:00
Cam Saul
ec33a542a3 MLv2 improvements: import more lib.metadata.calculation stuff; more test helpers (#33015)
* MLv2 cleanup: import more lib.metadata.calculation stuff; more test helpers

* Update QP code

* Test fix 🔧

* Fix bad :require

* Fix bad :require
2023-08-16 16:25:02 +00:00
Uladzimir Havenchyk
18b94c93c4 Do not run query if dashboard filter is not connected to the card (#33197) 2023-08-16 15:13:00 +00:00
Ryan Laurie
e57f1a40d2 Fix DB Connection Test flake (#33177) 2023-08-16 15:10:13 +00:00
Denis Berezin
31e83ed96d Drills migration preparation - unified types, moved Mode, detached actions from drills (#33143)
* Drills migration preparation - unified types, moved Mode, detached actions from drills

* Click actions components renaming

* Moved Automatic Insights back to drills
2023-08-16 14:35:21 +00:00
Mahatthana (Kelvin) Nomsawadi
d239393ef3 Add more missing translations (#33123)
* Translate admin audit

* Add missing translations in admin audit details

* Translate MappingEditor

* Translate AddMemberRow

* Translate GroupsListing

* Add missing translation in admin collection permission

* Translate MoveCollectionModal

* Translate invite user form

* Translate Table conditional settings select

* Translate date format options

* Format gauge chart settings

* Remove unused audit tables

* Add missing translation

* Don't translate email
2023-08-16 14:33:44 +01:00
Alexander Polyankin
c2f43e2959 Fix viz icons color (#33225) 2023-08-16 13:30:17 +00:00
Tim Macdonald
d36c063392 Tune MySQL and Postgres CSV uploads to use less memory (#33167) 2023-08-16 14:26:26 +01:00
Nicolò Pretto
4431d9d487 cancel ongoing cards when saving a dashboard (#33128)
* cancels ongoing cards when saving a dashboard

* refactor: change from stub to spy so that we can also see in the inspector that the request has been cancelled

* test that the data will eventually be displayed
2023-08-16 15:20:36 +02:00
Cal Herries
f40805b12c Stop native parameters defaults changing chart type after save or load (#33211) 2023-08-16 12:59:08 +00:00
Tim Macdonald
9964f6bb53 Add the last-acknowledged-version user setting (#33198)
[Fixes #33193]
2023-08-16 12:03:09 +00:00
Anton Kulyk
166f321942 Fixes for MLv2 types (#33200)
* Fix `filterClause` return type

* Add `FilterOperatorDisplayInfo`

* Make `ColumnWithOperators` a subset of `ColumnMetadata`

* Fix `ExternalOp` marked as opaque

* Use `ColumnMetadata` in `ExternalOp` `args`
2023-08-16 11:34:43 +01:00
Ryan Laurie
0f65cde6e7 Round small y-axis values to zero with no min/max difference on the Y scale (#33179)
* Round small values to zero with no min/max difference on the Y scale

* dont show nulls as zero
2023-08-15 22:42:29 +00:00
Ryan Laurie
8dabbdfffc increase sanity check test timeout (#33108) 2023-08-15 22:16:20 +00:00
metamben
aee9b3e37f Parse metadata of card fields passed from JS (#33206)
Fixes #32948.
2023-08-16 01:12:43 +03:00
Cam Saul
50080815d3 mu/defn should include fn name in errors & perf improvements (#33069) 2023-08-15 22:12:03 +00:00
Noah Moss
7c4ef577bb bump saml (#33204) 2023-08-15 17:19:26 -04:00
Tim Macdonald
bf13813e42 Remove obsolete CLI flags for export; fix collection specification (#33189)
* Remove obsolete CLI flags for `export`; fix collection specification

[Fixes #33168]

* Allow comma-separated IDs
2023-08-15 21:55:19 +01:00
Cam Saul
8148254dfd Squash and rebase onto master so this is not blocked waiting for upstream PR reviews. (#33016) 2023-08-15 18:31:32 +00:00
Case Nelson
0dea0149d0 Improve sql parameter mismatch error message (#33114)
* Improve sql parameter mismatch error message

It is possible to write native sql queries that try to hide parameters
within comments or identifiers. Unfortunately PreparedStatement will
almost always explode in these cases since you can only parameterize
values in sql caluses. The error message of various drivers is quite
poor, so we add a heuristic to look for these poor messages and replace
it with a message prompting the user to look for a misuse of parameters.

* Address review comments

* Exclude drivers that do not support getParameterCount
2023-08-15 12:24:08 -06:00
Cam Saul
3d3490356c Remove :metabase.lib.*/ keys from :field refs when converting to legacy (#33111)
* Remove `:metabase.lib.*` keys from field refs when converting refs to legacy

* Fix hardcoded database ID
2023-08-15 17:50:56 +00:00
adam-james
d1ad5194d9 Normalize Formatted strings on \space char. (#33186)
* Normalize Formatted strings on \space char.

Some JVMs use nbsp chars in their formatted strings. I noticed weird test failures that printed the same because of
this and it was confusing. So I propose a simple string replace to normalize on one type of space char only.

* Change use of strings in str/replace to chars to pass the linter
2023-08-15 10:31:01 -07:00
Nemanja Glumac
2aaef97c7e Consolidate E2E dashboard specs (#33073)
* Consolidate "create new dashboard" workflow

* Consolidate "add new dashboard card" tests

* Remove redundant repro for 25705

* Group and consolidate "title and description" tests

* Move repro 26826 to the main `dashboard` corpus

* Fix `visualization-options` spec name

* Make `dashboardHeader` more specific

* Consolidate "duplicate dashboard" tests

* Clean up and consolidate all dashboard management test

* Fix test failure

https://www.deploysentinel.com/ci/runs/64d9eb30fa6644982d115267

* Fix dashboard auto apply filters test failure

https://www.deploysentinel.com/ci/runs/64d9e91c7b3e6a1ddb9363c8

* Fix custom homepage test

https://www.deploysentinel.com/ci/runs/64d9e9a8f048784ce96aedf2

* Another attempt to fix a failing test

* Bring back a test removed during rebase
2023-08-15 19:13:29 +02:00
Alexander Polyankin
e2e3c10ea1 Mantine menu (#33097) 2023-08-15 15:40:35 +00:00
Oisin Coveney
925f8183d7 Add emotion.d.ts (#33191) 2023-08-15 15:23:16 +00:00
Uladzimir Havenchyk
847bc00b37 Add docs about running tests with snowplow (#33159)
* Add docs about running tests with snowplow

[skip ci]

* Update docs/developers-guide/e2e-tests.md

Co-authored-by: Nemanja Glumac <31325167+nemanjaglumac@users.noreply.github.com>

---------

Co-authored-by: Nemanja Glumac <31325167+nemanjaglumac@users.noreply.github.com>
2023-08-15 11:43:54 +00:00
Alexander Polyankin
783ecec4ee Remove unsafe-eval from script-src (#33188) 2023-08-15 11:32:07 +00:00
Alexander Polyankin
7820266e7d Remove unsafe-inline from style-src (#32526) 2023-08-15 09:55:48 +00:00
metamben
a13940ac3e Fix alias of LHS from join (#33103)
Porting fix alias of joined column LHS of standard join conditions (#32987)

* Check if the LHS has the alias of the current join before stripping its alias.
* Remove dependent joins when removing a join
2023-08-15 04:32:06 +00:00
Aleksandr Lesnenko
a47b7f813e fixes x-ray loading order (#33145) 2023-08-14 22:50:59 +00:00
Cam Saul
cff0a71bbe Improved mu/defn error messages (#32966)
* Simplified impl.

* Fix kondo errors

* Cljs test fix 🔧
2023-08-15 00:33:14 +03:00
Oisin Coveney
34bf7103eb Make changes to Checkbox based on Text component changes (#33099) 2023-08-14 19:50:29 +00:00
Emmad Usmani
dcf0105e39 fix ChartSettingInputNumeric not accepting decimals on safari (#33056)
* fix `ChartSettingInputNumeric` decimals on safari

* add unit test
2023-08-14 19:19:55 +00:00
Jeff Bruemmer
ce5da71f9d docs - update config file docs (#33142) 2023-08-14 13:05:19 -04:00
Jeff Bruemmer
d7cda8d3a0 docs - remove user flag (#33136) 2023-08-14 17:00:20 +00:00
Anton Kulyk
fbd8e6306c Migrate NativeQueryEditor to TypeScript (#33102)
* Extend `ace-builds.d.ts`

* Partially migrate to TypeScript

Define component props and state types, add straightforward types

* Add editor ref null checks

* Add null checks for optional fn props

* Fix missing types (simple)

* Add straightforward ace editor null checks

* Cast editor type on load

* Fix `cardTagIdAtCursor` method

* Fix `handleCursorChange` method

* Fix missing arguments for ace's `setScrollMargin`

* Use `Question` methods over properties

* Use ace's completer types

* Add editor null checks

* Fix `setTableId` method

* Fix `_updateSize` method

* Fix `getCardTagCompletions` method

* Fix `getSnippetCompletions` method

* Fix autocompletion types

* Fix scroll margin

* Fix `fetchQuestion` type

* Fix resizable box

* Remove redundant editor null check

* Fix incorrect type

* Break down `OwnProps`

* Fix `_lastAutoComplete` type

* Minor fix

* Minor fix

* Avoid ace editor type casting

* Add radix to `parseInt`
2023-08-14 17:35:52 +01:00
Noah Moss
43ff98be7f Fix redirect URI validation for relative paths (#33100)
* don't throw when host is nil

* fix test ns name

* Update enterprise/backend/test/metabase_enterprise/sso/integrations/sso_utils_test.clj

Co-authored-by: Cam Saul <1455846+camsaul@users.noreply.github.com>

---------

Co-authored-by: Cam Saul <1455846+camsaul@users.noreply.github.com>
2023-08-14 12:35:21 -04:00
Alexander Polyankin
e8d9c21470 Revert "Remove unsafe-eval from script-src (#32982)" (#33164) 2023-08-14 18:12:22 +03:00
Uladzimir Havenchyk
4a83f5bcf2 Quick fix for UI glitches caused by changing z-index at dashboards (#33153) 2023-08-14 18:10:38 +03:00
Anton Kulyk
844075c1fd Extract styled components from NativeQueryEditor (#33059)
* Extract `aceEditorStyle`

* Extract drag handle

* Port more `NativeQueryEditorRoot` class names

* Port editor root and resizable box

* Remove redundant class names

* Remove `.NativeQueryEditor` class

* Use CSS variable colors in `NativeQueryEditor.css`

* Add a comment on `NativeQueryEditor.css`
2023-08-14 14:37:23 +01:00
Ryan Laurie
42fcc78901 add column rename via popover test (#33066) 2023-08-14 07:32:07 -06:00
Kamil Mielnik
71fdba7ec4 User friendly error message when combining series that cannot be visualized together (#33119)
* Use named import for ErrorView

* Export ErrorView and ErrorViewProps from Visualization

* Define AddSeriesModalErrorView

* Make ErrorView component configurable in Visualization by introducing errorView prop

* Use AddSeriesModalErrorView thanks to new errorView prop

* Fix export type syntax

* Remove the dot for consistency with other error messages

* Rename AddSeriesModalErrorView to ErrorView and extract it to a separate file

* Allow translating the custom error message

* Don't show custom ErrorView when there is only one series (or none)

* Add a test case for a single incomplete chart

* Inline: dashcardData

* Add a reproduction e2e test for #32231

* Add explicit assertion for the error message

* Add a test case for default error message when there is only 1 series

* Remove redundant setup functions

* Wait for series query endpoint

* Rename ErrorView to VisualizationErrorView

* Rename VisualizationErrorView to MultipleSeriesErrorView

* Improve assertions

* Use editDashboard helper

* Use data-testid for AddSeriesModal

* Refactor errorView prop into errorMessageOverride
- Do not export ErrorViewProps and Error out of Visualization
2023-08-14 19:58:43 +07:00
Nemanja Glumac
f9a8b66388 Fix flaky reproduction for #15891 (#33154) 2023-08-14 14:24:22 +02:00
Tim Macdonald
6585f0c182 Search by table description (#33089)
* Search by table description

[Fixes #25792]
2023-08-14 10:53:58 +00:00
Kamil Mielnik
ae9d22cb3a Show new syncing tables as greyed out in data reference pane (#33076)
* Use MetabaseApi where possible in entities/tables.js

* Mock syncing state

* Disable table link if sync is not complete

* Disable model link if sync is not complete

* Gray out the disabled link by inheriting body color

* Revert "Disable model link if sync is not complete"

This reverts commit 5423834bc6.

* Revert "Mock syncing state"

This reverts commit 4546f7655e.

* Export DatabaseTablesPaneProps

* Use SearchResult type instead of any

* Add a unit test boilerplate

* Implement test cases for various initial_sync_status for tables

* Update names

* Add explanatory comments and functions
2023-08-14 17:32:42 +07:00
Kamil Mielnik
11f8b03667 Fix - Can't subsequently run actions for different objects from dashboards (#33087)
* Fix initial values not reloading in the action modal

* Add a repro test for #33084

* Use cy.button helper
2023-08-14 17:27:30 +07:00
Alexander Polyankin
b220f902ac Fix crash in admin settings in a non-default locale (#33133) 2023-08-14 13:06:31 +03:00
Alexander Polyankin
ecf4b62311 Remove unsafe-eval from script-src (#32982) 2023-08-14 13:04:37 +03:00
Case Nelson
cca78aa960 Temporarily comment out flaky bigquery tests. (#33141)
Part of #33140
2023-08-14 08:06:16 +00:00
Mahatthana (Kelvin) Nomsawadi
32a4c3452b Fix dashboard actions linked with filters don't work (#33034)
* Fix dashboard actions linked with filters don't work

* Add E2E test

* Make assertion clearer
2023-08-14 11:18:39 +04:00
Maz Ameli
d364f321b2 Add Latvian and update translations for 47 (#32996)
* add latvian and update translations for 47

* translate untagged strings found in review

* okay but really this time is it I swear
2023-08-14 11:01:07 +04:00
shaun
7f9dc7d5eb Creating a collection when saving a question/dashboard should return to the question/dashboard save modal with the new collection selected (#32778) 2023-08-12 23:18:47 -05:00
shaun
bce9d9f41d Add future e2e spec to improve Filter <> DatePicker compatibility (#32288) 2023-08-12 06:02:36 +00:00
Jeff Bruemmer
082215f701 docs - h2 update (#33019) 2023-08-11 16:49:36 +00:00
Alexander Polyankin
4393a94265 Fix dynamic message id in translations (#33122) 2023-08-11 18:46:03 +03:00
Jeff Bruemmer
73cb16ee60 remove optional field (#33096) 2023-08-11 10:01:48 -04:00
Nemanja Glumac
71cabbdc04 Reduce number of tests stored in memory (#32868)
From the Cypress docs
https://docs.cypress.io/guides/references/configuration#Global

The number of tests for which snapshots and command data are kept in memory. Reduce this number if you are experiencing high memory consumption in your browser during a test run.

The default value is 50.
We're dialing it down to 1.
2023-08-11 14:46:58 +02:00
Nemanja Glumac
a33eaf7369 Fix a question suffix created when deep copying a dashboard with question (#33081)
Fixes #33080
2023-08-11 13:55:49 +02:00
Oisin Coveney
4c73a88b9a Make sure filter button only appears when search bar is open (#33077) 2023-08-11 09:49:49 +03:00
Cam Saul
8845188509 Test metadata helper function consolidation (#33031)
* Test metadata helper function consolidation

* More code consolidation
2023-08-11 01:45:01 +00:00
shaun
5a2a6a4a2d Wrap long column names in chart settings sidebar (#33024) 2023-08-10 17:51:02 -05:00
Luis Paolini
3e9df68848 Wink for GCP users (#33092) 2023-08-10 16:42:18 -04:00
Noah Moss
a40023a5ec Fix misc errors in currency metadata (#33009)
* fix currency metadata

* fix test

* change renminbi back to yuan because that's what Intl.NumberFormat uses
2023-08-10 13:50:34 -04:00
Ryan Laurie
b7ea23761f Dont crash with bad fieldValues filter options (#33025)
* reproduce #32985

* don't crash fieldValuesWidget when we get null options
2023-08-10 14:44:36 +00:00
Ryan Laurie
0b0edf1b91 [MLv2] Expose field_id mlv2 function (#33021)
* expose field_id mlv2 function

* Update frontend/src/metabase-lib/fields.ts

Co-authored-by: Anton Kulyk <kuliks.anton@gmail.com>

---------

Co-authored-by: Anton Kulyk <kuliks.anton@gmail.com>
2023-08-10 08:38:06 -06:00
Ryan Laurie
50da90465a Convert DefaultPicker to typescript (#32797)
* convert DefaultPicker to typescript

* unit test DefaultPicker

* update types

* use rowvalue
2023-08-10 08:37:49 -06:00
lbrdnk
9fef23dc6b Unify semicolon and comment handling in nested native queries (#30677)
* Unify semicolon and comment handling in nested native queries

* Use different comment and semicolon removal approach

* Apply suggestions from code review

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>

* Update base and effective type verification for oracle

* Avoid running test with snowflake and bigquery

* Update `breakout-results` and test

1. In `breakout-results` case driver statement was redundant.
Original code had field name and types hardcoded. During further
examination, I've realized name and types are available thanks
to the use of `qp.test/col`, so are just "unhardcoded" :)

2. `card-id-native-source-queries-test` is altered, so instead of
hardcoding native sub-queries, roughly equivalent* mbql query is
compiled and its native form is used. This way I can hopefully avoid
problems with extraction of cloud databases' table names for testing
purposes.

* By roughly equivalent I mean instead of using * for selecting
fields, mbql is compiled selecting fields explicitly. Also limit is added
in some cases, but local testing showed no problems with that.

---------

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>
2023-08-10 14:09:30 +02:00
lbrdnk
a98bfa1f2a Modify :contains, :starts-with and :ends-with so field or expression can be used as the second argument (#32446)
* Update `LIKE` to handle fields and expressions

Previously only string could be used with like clause, ie. as second
argument of `:starts-with`, `:ends-with` or `:contains`. This commit modifies
translation of those functions, so fields or expressions can be
used in place of second argument.

* Make only expression or field args use `concat`

Using concat with values unnecessarily complects generated sql.

* Update tests

* Extend mongo string matching capabilities

Make mongo filter compilation use `$regexMatch` for `:contains`,
`:starts-with` and `:ends-with` so expressions and fields
can be matched against.

* Adjust mongo specific tests

* Update druid

Druid's filters work with `:contains`, `:starts-with` and `:ends-with`,
but only if second argument is literal pattern. This commit updates
existing code, so expection is thrown if `pattern` has different form
than `[:value ...]`.

* Address review comments - sql

* Address review comments - mongo

* Use mbql `:concat` instead of `hx/call :concat`

Vertica, orcacle and sqlite handle concat differently than other
drivers. To overcome this limitation, `pre`, `post` and `arg` are
wrapped into mbql's concat expression which is then translated
with regards to the specifics of particular driver.

* Update according to the review feedback

---------

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>
2023-08-10 14:07:16 +02:00
lbrdnk
88b9ee0f79 Update mongo native param substitution (#33003)
Change is compatible with prior implementation. Match clause like
the following, `{$match: {"something": "Facebook"}}`, does exact match
if `something` is a scalar, and in case `something` was an array, match
would check whether it contains the `Facebook` value. Same behavior,
as with `{$match: {"something": {$in: ["Facebook"]}}}`.

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>
2023-08-10 14:06:16 +02:00
Anton Kulyk
16c74a5967 Group NativeQueryEditor files in a single directory (#33055)
* Group native editor files in a single directory

* Fix mocking

* Clean up imports
2023-08-10 12:50:14 +01:00
Kamil Mielnik
34d895a30d Add an e2e test to reproduce issue 28756 (#33004)
* Add reproduction test for #28756

* Reuse DASHBOARD_SLOW_TIMEOUT
2023-08-10 12:27:43 +07:00
metamben
858573b517 [MLv2] Support segments (#32882)
* Support segments

Fixes #32409.
2023-08-10 02:21:20 +03:00
metamben
f752c84d58 Generate correct reference for broken out expressions (#32993) 2023-08-09 23:18:12 +00:00
Aleksandr Lesnenko
f4cc36af31 fix funnel shows card title in the chart viewport in QB (#32992) 2023-08-09 21:37:38 +00:00
Uladzimir Havenchyk
86dd5eb47f Fix styling of ParametersWidgetContainer (#33051) 2023-08-09 18:22:28 +00:00
Oisin Coveney
afd64fdcbb Search Filter Milestone 1 - Type Filters for Search (#32742) 2023-08-09 18:12:45 +00:00
metamben
1579dfae8c Remove slf4j dependencies from org.apache.sshd/sshd-core (#32766)
This change assumes that org.slf4j/jcl-over-slf4j is not really in use.
2023-08-09 20:05:40 +03:00
Cam Saul
e8755469d3 Fix long display names for joined columns from Cards (#32930)
* Fix fallback long display name for Cards

* Test updates
2023-08-09 17:00:43 +00:00
Cam Saul
34d212ca2d Marked columns as selected without regards to :temporal-unit (#33030)
* Fix #32920

* Remove stray println
2023-08-09 09:14:46 -07:00
lbrdnk
f06411d4fe Make mongo query's :case expression realize during compilation (#32248)
* Make `:branches` realize during `:case` compilation

Previously `:branches` were generated with use of `for`,
yeilding lazy sequence. It caused problems, if the sequence
got realized after processing of query ie. without initialized
qp store. That was the case with /dataset/native api
call containing `:case` with `:now`.

* Update /dataset/native test

---------

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>
2023-08-09 17:53:11 +02:00
Anton Kulyk
1ce8e2c2cf Don't lock display for models (#33047)
* Reproduce #32963

* Don't lock display for models
2023-08-09 16:48:38 +01:00
Oisin Coveney
34cceaa329 Add Text and Anchor Mantine Components (#32898) 2023-08-09 18:15:11 +03:00
Ryan Laurie
8e456f4842 Reproduce failed breakout detection in multistage queries (#32872)
* test custom column after aggregations

* skip repro
2023-08-09 08:58:07 -06:00
Jeff Bruemmer
afb1a552f8 docs - rename embedding (#32927) 2023-08-09 14:49:02 +00:00
Uladzimir Havenchyk
e3259496a4 Address dashboard visual glitches caused by css refactoring (#33011) 2023-08-09 14:24:46 +00:00
Nemanja Glumac
4b08866be1 Create new dashboard-cards E2E group (#33005)
* Move dashboard bookmarks spec to `organization`

* Move dashboard filter related specs to appropriate group

* Create new `dashboard-cards` E2E group
2023-08-09 16:16:56 +02:00
Mahatthana (Kelvin) Nomsawadi
379ecc1988 Add missing translations (#33035) 2023-08-09 13:15:32 +00:00
Ngoc Khuat
4cb7a25675 Fix flaky Login history test (#33032)
* Fix for login history, the fix was written by Cam

* kondo
2023-08-09 13:41:52 +02:00
Jeff Bruemmer
25be72ce5e add Latvian to list of languages (#33013) 2023-08-08 12:32:43 -04:00
Kamil Mielnik
0f3b3df0f8 Fix - Cannot remove questions when combining questions to create multi-series charts (#32949)
* Fix removing series from the legend
- Fixes #12794

* Use slice instead of filter

* Format code (-1 LOC)

* Refactor AddSeriesModal to TS

* Fix typing error

* Refactor state.state into state.isLoading
- remove leftover isLoadingMetadata

* Hide the "x" button for the first legend item in the chart in AddSeriesModal

* Fix typo

* Use named export for AddSeriesModal

* Fix dashcardData typing

* Export Props

* Add test boilerplate

* Reduce test setup boilerplate

* Reduce test setup boilerplate

* Add test for the 'x' button

* Add tests for removing series from legend

* Add comprehensive test case
2023-08-08 20:55:07 +07:00
Ngoc Khuat
cc7a6afd65 Change log level for api.field/search-values to error (#33000) 2023-08-08 09:11:22 +00:00
Uladzimir Havenchyk
7b6fdbaa6b Fix stacking of dashcards (#32796) 2023-08-08 08:42:43 +00:00
Nicolò Pretto
ba3ec47636 fix: cancel ongoing query when removing card from dashboard (#32842)
* fix: cancel ongoing query when removing card from dashboard

* test: #12926 remove card test with xhr.abort stub

* test: use cy.on(fail instead, to specifically expect that request to be aborted

* Revert "test: use cy.on(fail instead, to specifically expect that request to be aborted"

This reverts commit 75e204e8e2c45cc490d79729ee12795ea10291fa.

* refactor: move cancelFetchCardData inside removeCardFromDashboard, which becomes a thunk

* doc jsdocs for should_wait param in visitDashboard

* "undo remove card" re-fetches the card

* test: test for undo -> re-fetch card

* refactor: removed unused param

* revert should_wait on visitDashboard in favor or manually using cy.visit

* artificially slow down requests via cy instead of using pg_sleep

* rename before block

* when undoing remove card, only refetch data if needed

* remove debug console log

* refactor: remove .within call with only one function call inside

* docs: add comment to req.continue

* test: adds assertion that the query data is actually loaded

* remove data already present check as it is already in the thunk
2023-08-08 09:51:00 +02:00
Nemanja Glumac
cbdb4fab7b Remove redundant embedding-standalone E2E spec (#32969)
Introduced in #32598, even though it already exists.
https://github.com/metabase/metabase/blob/master/e2e/test/scenarios/embedding/embedding-smoketests.cy.spec.js#L317:L325

[ci skip]
2023-08-08 06:11:31 +02:00
Maz Ameli
13eb422ebd embiggen chart selection icons (#32965) 2023-08-07 10:29:01 -07:00
Anton Kulyk
501f58ed0a Remove unused getFieldTarget function (#32976) 2023-08-07 17:06:16 +01:00
Ngoc Khuat
5c2f0aafcf Build Metabase without clojure source (#32938) 2023-08-07 17:40:28 +03:00
Anton Kulyk
940a781300 Fix errors when removing custom columns used by other clauses (#32850)
* Add repro test

* Run MLv2 clean-up before running a query

* Clean redundant stages

* Fix test

* Use both clean ups
2023-08-07 15:00:12 +01:00
Nemanja Glumac
8338de2bad Introduce a backport reminder CI workflow (#32972)
* Introduce backport reminder CI workflow

* Only trigger against `master`

* Re-trigger when author adds a label

* Disable PR bot reviews

* Keep the job name terse
2023-08-07 11:52:02 +02:00
Tim Macdonald
5c1b2af3b1 Fully hydrate PUT-ed collections, which the FE depends on (#32798)
* Fully hydrate PUT-ed collections, which the FE depends on

[Fixes #30235]

* Add repro test for #30235

* Set token features properly

---------

Co-authored-by: Denis Berezin <denis.berezin@metabase.com>
2023-08-07 09:35:43 +01:00
Cam Saul
18c1b1984e QP: use Malli (#32657)
* QP: use Malli

* Fix schema names

* Fix missing namespaces

* Fix busted stuff

* Simplify the new schema

* Test fix 🔧

* Test fixes 🔧

* MongoDB fixes 🔧

* FAST mu/defn

* Malli registry

* Misc fixes

* Some cleanup

* Misc cleanup and test fixes 🔧

* mu/disable-enforcement

* Test fix

* Fix Cljs version of `disable-enforcement`

* Misc improvements

* Update tests

* Fix Kondo warnings

* Fix Kondo warnings

* Fix busted Malli schema

* PR feedback

* Fix busted schema

* Kondo fixx

* Test fixes 🔧

* Use Malli version of `describe` now that PR was merged

* Work around https://github.com/metosin/malli/issues/924

* Test fixes 🔧

* Improvements

* Test fix
2023-08-06 14:50:18 -07:00
Cam Saul
8cc1dd01ad Fix load-from-h2 bugs with H2 databases (#32837) (#32960) 2023-08-06 20:17:41 +00:00
Aleksandr Lesnenko
6cdac48f5b fix x-axis default value (#32875) 2023-08-04 22:03:01 +00:00
Jeff Bruemmer
feeaaf3947 Change full-app embedding to interactive embedding in admin section (#32774) 2023-08-04 16:43:32 -04:00
Uladzimir Havenchyk
94aa7f736f Allow workflow to be cancelled via UI or by concurrent job (#32951)
based on https://github.com/orgs/community/discussions/26303 and my experience, workflows with `always()` will not cancel even if a new run of the same workflow appears with concurrency and cancel-in-progress:true. Official documentation suggests using `!cancelled()` instead
2023-08-04 18:25:02 +00:00
Case Nelson
1ef3cd5d83 [MLv2] Add function to sync join-condition temporal bucketing options (#32807)
* [MLv2] Add function to sync join-condition temporal bucketing options

* Return the modified join-condition instead of the whole query

* Adding tests

* Fix linter
2023-08-04 12:24:32 -06:00
Noah Moss
3fe96902f9 improve error handling in SSO utils (#32879) 2023-08-04 11:10:35 -04:00
Nemanja Glumac
0f897c1d28 Run Cypress using Chromium 111.0.5563.146 (#32946)
* Install Chrome immediately after checkout

* Switch to Chromium 111.0.5563.146
2023-08-04 14:24:06 +00:00
Kamil Mielnik
b6036b5e1c Fix - Update Modal flickers on initial load (#32671)
* Add actions dropdown to object detail modal (#32331)

* Rename showActions to showControls

* Use Flex

* Import Flex from local modules

* Make horizontalAttachments a prop in EntityMenu

* Use EntityMenu to create actions dropdown

* Render actions menu conditionally

* Add useActionListQuery

* Fetch actions in ObjectDetailHeader

* Remove unused canRunActions prop

* Move logic to root component

* Fix tests

* Use canRunAction and fetch databases in ObjectDetail view

* Rename actions to actionItems and getActions to getActionItems

* Extract getActionItems to utils

* Update tests

* Rename modelActions to actions

* Extract isValidImplicitDeleteAction and isValidImplicitUpdateAction out of getActionItems

* Consolidate getActionItems

* Use theme scale values for Mantine Flex component

* Either render all controls or none

* Fix default props/state in EntityMenu

* Fix props

* Update ObjectDetail unit tests

* Add unit tests for isValidImplicitDeleteAction and isValidImplicitUpdateAction

* Update tests with more specific non-implicit action cases

* Use singular form to match function interface

* Add unit tests for getActionItems

* Update test case name

* Avoid using Database constructor
- Use metadata.database() instead

* Add integration tests for basic cases when action menu is rendered and not

* Fix post-merge error

* Endpoint to fetch implicit actions param values (#32466)

* Add default update action to actions dropdown in object detail modal (#32433)

* Rename showActions to showControls

* Use Flex

* Import Flex from local modules

* Make horizontalAttachments a prop in EntityMenu

* Use EntityMenu to create actions dropdown

* Render actions menu conditionally

* Add useActionListQuery

* Fetch actions in ObjectDetailHeader

* Remove unused canRunActions prop

* Move logic to root component

* Fix tests

* Use canRunAction and fetch databases in ObjectDetail view

* Rename actions to actionItems and getActions to getActionItems

* Extract getActionItems to utils

* Update tests

* Rename modelActions to actions

* Extract isValidImplicitDeleteAction and isValidImplicitUpdateAction out of getActionItems

* Consolidate getActionItems

* Use theme scale values for Mantine Flex component

* Either render all controls or none

* Fix default props/state in EntityMenu

* Fix props

* Update ObjectDetail unit tests

* Add unit tests for isValidImplicitDeleteAction and isValidImplicitUpdateAction

* Update tests with more specific non-implicit action cases

* Use singular form to match function interface

* Add unit tests for getActionItems

* Update test case name

* Sort imports

* Rename initialValues to values

* Rename dashcardParamValues to initialValues

* Lift fetchInitialValues up from ActionParametersInputForm

* Rename refetchValues to prefetchValues

* Fix tests

* Refactor shouldPrefetch to be a prop

* Get rid of dashboard and dashcard props from ActionParametersInputForm

* Lift the canPrefetch condition up as it is not desired outside of dashboards

* Hook update action with temporary API

* Use executeActionId in fetchInitialValues

* Fix post-merge conflict

* Rename prefetchValues to prefetchDashcardValues

* Use the new endpoint

* Use rem values instead of scale values
- See https://github.com/metabase/metabase/pull/32331#discussion_r1267827835

* Lift data reloading out of executeRowAction

* Add onSuccess prop to ActionExecuteModal

* Use onSubmitSuccess from ActionParametersInputForm

* Reload question after action is successful

* Fix stale prop issues in ActionParametersInputForm

* Fix object id in initialValues

* Add prefetchesInitialValues prop to make useActionForm more generic

* Ignore public actions for now

* Fix id mixup

* Update unit test

* Remove redundant memoization

* Use modern JS syntax instead of noop

* Move getNextId to __support__/utils

* Extract isImplicitDeleteAction & isImplicitUpdateAction

* Reuse isImplicitDeleteAction

* Log error to console

* Get rid of useLatest

* Fix post-merge build error

* Add a spinner to action modal when fetching values

* Use Flex instead of styled component

* Add default delete action to actions dropdown in object detail modal (#32556)

* Rename showActions to showControls

* Use Flex

* Import Flex from local modules

* Make horizontalAttachments a prop in EntityMenu

* Use EntityMenu to create actions dropdown

* Render actions menu conditionally

* Add useActionListQuery

* Fetch actions in ObjectDetailHeader

* Remove unused canRunActions prop

* Move logic to root component

* Fix tests

* Use canRunAction and fetch databases in ObjectDetail view

* Rename actions to actionItems and getActions to getActionItems

* Extract getActionItems to utils

* Update tests

* Rename modelActions to actions

* Extract isValidImplicitDeleteAction and isValidImplicitUpdateAction out of getActionItems

* Consolidate getActionItems

* Use theme scale values for Mantine Flex component

* Either render all controls or none

* Fix default props/state in EntityMenu

* Fix props

* Update ObjectDetail unit tests

* Add unit tests for isValidImplicitDeleteAction and isValidImplicitUpdateAction

* Update tests with more specific non-implicit action cases

* Use singular form to match function interface

* Add unit tests for getActionItems

* Update test case name

* Sort imports

* Rename initialValues to values

* Rename dashcardParamValues to initialValues

* Lift fetchInitialValues up from ActionParametersInputForm

* Rename refetchValues to prefetchValues

* Fix tests

* Refactor shouldPrefetch to be a prop

* Get rid of dashboard and dashcard props from ActionParametersInputForm

* Lift the canPrefetch condition up as it is not desired outside of dashboards

* Hook update action with temporary API

* Use executeActionId in fetchInitialValues

* Fix post-merge conflict

* Rename prefetchValues to prefetchDashcardValues

* Use the new endpoint

* Use rem values instead of scale values
- See https://github.com/metabase/metabase/pull/32331#discussion_r1267827835

* Lift data reloading out of executeRowAction

* Add onSuccess prop to ActionExecuteModal

* Use onSubmitSuccess from ActionParametersInputForm

* Reload question after action is successful

* Fix stale prop issues in ActionParametersInputForm

* Fix object id in initialValues

* Add prefetchesInitialValues prop to make useActionForm more generic

* Ignore public actions for now

* Fix id mixup

* Update unit test

* Add DeleteObjectModal

* Introduce useActionQuery

* Use useActionQuery in DeleteObjectModal

* Hook action execution

* Fix typo in copy

* Sort exports

* Remove redundant memoization

* Use modern JS syntax instead of noop

* Move getNextId to __support__/utils

* Extract isImplicitDeleteAction & isImplicitUpdateAction

* Reuse isImplicitDeleteAction

* Fix object modal getting closed with Escape key when delete or update modals are open

* Rename isUpdateModalOpen to isActionExecuteModalOpen, updateActionId to actionId

* Navigate to sibling row or close the modal on deletion

* Revert "Navigate to sibling row or close the modal on deletion"

This reverts commit 8b24685eee.

* Close object detail on deletion

* Add error handling

* Add error handling

* Greatly simplify DeleteObjectModal
- remove useActionQuery usage
- remove useActionQuery
- remove DeleteObjectModal.styled.tsx

* Improve diff

* Shorten code

* Always cast objectId to number
- See https://metaboat.slack.com/archives/C057T1QTB3L/p1690292706101109?thread_ts=1690279562.697669&cid=C057T1QTB3L
  "the reason you’re not seeing it fail on the sample dataset is probably because you’re
  using h2 for sample-dataset. it’ll fail the same if you use a postgres one.
  h2 is probably more loose in type so it allows sending a string for id.
  nevertheless, I think you can use cast it to the correct type using the param type.
  I think we did that on the UI where we execute actions from model details page."

* Inline disabled into JSX

* Use a more friendly error message when failed to delete an object because it's referenced by other objects
- See: https://metaboat.slack.com/archives/C057LE0Q4PQ/p1690377421352469?thread_ts=1690208614.530869&cid=C057LE0Q4PQ

* Use useAsyncFn to avoid race conditions

* Add typing to NO_VALUES constant

* Remove redundant condition

* Introduce useActionQuery hook

* Get rid of HOCs in ActionExecuteModal using useActionQuery

* Do not crash app on unexpected events

* Refactor ActioExecuteModal to use named export

* WIP: Lift data fetching out ActionParametersInputForm
- Update ActionExecuteModal
- TODO:
  - update from dashboard does not work yet
  - other usages

* Revert "Use a more friendly error message when failed to delete an object because it's referenced by other objects"

This reverts commit 28327ac9b5.

Friendly message is going to be implemented in https://github.com/metabase/metabase/issues/32694

* Rename initialValues back to dashcardParamValues in ActionVizForm

* Don't move ActionExecuteModal to keep nice diff

* Fix export

* Fix typing

* Handle empty state in ActionExecuteModal

* Move useActionInitialValues to hooks

* Tests for basic deletes and updates on object detail views (#32525)

* Rename showActions to showControls

* Use Flex

* Import Flex from local modules

* Make horizontalAttachments a prop in EntityMenu

* Use EntityMenu to create actions dropdown

* Render actions menu conditionally

* Add useActionListQuery

* Fetch actions in ObjectDetailHeader

* Remove unused canRunActions prop

* Move logic to root component

* Fix tests

* Use canRunAction and fetch databases in ObjectDetail view

* Rename actions to actionItems and getActions to getActionItems

* Extract getActionItems to utils

* Update tests

* Rename modelActions to actions

* Extract isValidImplicitDeleteAction and isValidImplicitUpdateAction out of getActionItems

* Consolidate getActionItems

* Use theme scale values for Mantine Flex component

* Either render all controls or none

* Fix default props/state in EntityMenu

* Fix props

* Update ObjectDetail unit tests

* Add unit tests for isValidImplicitDeleteAction and isValidImplicitUpdateAction

* Update tests with more specific non-implicit action cases

* Use singular form to match function interface

* Add unit tests for getActionItems

* Update test case name

* Sort imports

* Rename initialValues to values

* Rename dashcardParamValues to initialValues

* Lift fetchInitialValues up from ActionParametersInputForm

* Rename refetchValues to prefetchValues

* Fix tests

* Refactor shouldPrefetch to be a prop

* Get rid of dashboard and dashcard props from ActionParametersInputForm

* Lift the canPrefetch condition up as it is not desired outside of dashboards

* Hook update action with temporary API

* Use executeActionId in fetchInitialValues

* Fix post-merge conflict

* Rename prefetchValues to prefetchDashcardValues

* Use the new endpoint

* Use rem values instead of scale values
- See https://github.com/metabase/metabase/pull/32331#discussion_r1267827835

* Lift data reloading out of executeRowAction

* Add onSuccess prop to ActionExecuteModal

* Use onSubmitSuccess from ActionParametersInputForm

* Reload question after action is successful

* Fix stale prop issues in ActionParametersInputForm

* Fix object id in initialValues

* Add prefetchesInitialValues prop to make useActionForm more generic

* Add test cases for other types of actions

* Ignore public actions for now

* Add e2e test for actions in object detail view

* Add second step and extract helpers

* Remove duplication by changing hierarchy

* Add step with enabling model actions

* Fix visiting model page

* Remove redundant code

* Ignore public actions for now

* Fix id mixup

* Update unit test

* Add objectId argument and function to open the modal

* Define whole order object to reuse

* Implement assertOrderFormPrefilled

* Assert Created At

* Add assertion to check whether object with new id has been reloaded

* Use all caps for constants

* Verify updating an object

* Fix test name

* Assert toast is shown on update

* Format code

* Use writable tables instead of sample db to avoid persisting updates between tests
- do not mock objects, assert against whatever comes from API

* Format code to wake GitHub up

* Add DeleteObjectModal

* Introduce useActionQuery

* Use useActionQuery in DeleteObjectModal

* Hook action execution

* Fix typo in copy

* Sort exports

* Remove redundant memoization

* Use modern JS syntax instead of noop

* Move getNextId to __support__/utils

* Extract isImplicitDeleteAction & isImplicitUpdateAction

* Reuse isImplicitDeleteAction

* Fix object modal getting closed with Escape key when delete or update modals are open

* Rename isUpdateModalOpen to isActionExecuteModalOpen, updateActionId to actionId

* Navigate to sibling row or close the modal on deletion

* Revert "Navigate to sibling row or close the modal on deletion"

This reverts commit 8b24685eee.

* Close object detail on deletion

* Add error handling

* Add error handling

* Greatly simplify DeleteObjectModal
- remove useActionQuery usage
- remove useActionQuery
- remove DeleteObjectModal.styled.tsx

* Improve diff

* Shorten code

* Rename initialValues back to dashcardParamValues in ActionVizForm

* Extract assertScoreUpdatedInTable

* Extract visitModelDetail

* Add deletion and toast assertion

* Remove unused arguments

* Assert delete failed

* Update tests order after starting with writable db

* Move assertions to beginning of the test, remove enableDatabaseActions

* Test disabling model actions

* Add extra assertion

* Update names

* Update the deletion assertion

* Remove unused code

* Wrap tests in another describe, setup dashboard test

* Fix setup, use asAdmin util

* Add assertion for dashboard object view

* Update test names

* Extract actions to a constant

* Add test to open update object modal

* Update assertion order

* Add test to open delete object modal

* Organize tests

* Add a test case for implicit public delete action & implicit archived delete action

* Remove redundant async

* Reuse findActionInActionMenu

* Remove redundant constant

* Fix tests

* Add a test case for databases with disabled actions

* Update wording

* Use dataset instad of a query question

* Revert name change as it does not make sense

* Format code

* Add a test case for users with no write permission

* Add a test case for when showControls is false

* Add a test case for models with clauses

* Use metadata.question() instead of new Question()

* Remove duplicated code

* Update ActionVizForm

* Improve success callback in ActionExecuteModal

* Remove commented out code

* Update test to account for the loading state

* Fix import and name

* Move test cases to ActionExecuteModal

* Extract Options interface

* Move the "Choose a record to update" empty state to ActionParametersInputModal (the only place where it's used)
- Remove hasPrefetchedValues

* Update test with missing prop

* Clean up ActionExecuteModal tests

* Add ActionVizForm test suite

* Rename Props back to ActionExecuteModalProps for consistency

* Tests for various number of PKs in a model (#32784)

* Add a test case for 0 PKs in a model

* Add a test case for 2 PKs in a model

* Improve test names

* Fix typo

* Use plural form for "PK"

* Fix header action not shown in empty state

* Bring back hasPrefetchedValues
- this is to avoid showing spinner when initial values have already been loaded (e.g. when automatically closing the ExecuteActionModal after successful update)

* Bring back hasPrefetchedValues logic and update tests

* ESLint

* Use checkNotNull

* Fix handling 0 as an id in initialValues in ObjectDetail

* Add assertion that the flicker that used to occur before this PR does not occur anymore

---------

Co-authored-by: Ngoc Khuat <qn.khuat@gmail.com>
2023-08-04 20:37:05 +07:00
Mahatthana (Kelvin) Nomsawadi
9c64560dc8 Add tests to dashboard should work if some cards are broken (#32910)
* Add a repro

* Not hardcoding the question IDs

* Address review: Improve readability
2023-08-04 13:56:11 +01:00
Anton Kulyk
2181d118b7 Make it easier to configure QueryColumnPicker color (#32893)
* Add `ColorName` type to `metabase/lib/colors`

* Add `color` prop to `BucketPickerPopover`

* Add `color` prop `QueryColumnPicker`

* Fix `AggregationPicker`

* Fix `AggregateStep`

* Fix `BreakoutStep`

* Fix `SortStep`

* Fix bucket picker in `SummarizeSidebar`

* Avoid redundant `div`
2023-08-04 12:09:29 +01:00
Mahatthana (Kelvin) Nomsawadi
31a8c32133 Add tests to showing most recent dashboard revisions (#32899)
* Reuse dashboard E2E util

* Add the repro

* Add UI assertion to avoid ambiguity
2023-08-04 11:31:23 +01:00
Vamsi Peri
044e0c4d84 Added props to the FormFooter component to optionally add a border (#32810) 2023-08-04 10:06:14 +00:00
Nemanja Glumac
ddadd1c3a0 Install terser-webpack-plugin (#32892) 2023-08-04 10:20:18 +02:00
Ryan Laurie
4560ef7fe2 Improve actions-in-object-detail test (#32922)
* dont hard code table ID in actions test

* simplify test

* break down and wait more, remove page loads

* Remove superfluous intercept and wait

* Make sure repaint happened

* Make sure virtualized table populates all rows

* Add grep tags

* Increase the request timeout

---------

Co-authored-by: Nemanja <31325167+nemanjaglumac@users.noreply.github.com>
2023-08-04 10:19:45 +02:00
Mahatthana (Kelvin) Nomsawadi
5d66b0f467 Add repro to undo move dashboard doesn't always work in v44 (#32835)
* Add repro

* Correct new E2E helper behavior
2023-08-04 08:42:21 +01:00
Vamsi Peri
7a176d5d94 The error message we show when Google SSO login fails had a bit of CSS issue. Fixed that with some flex box styling. (#32817) 2023-08-04 03:49:30 +00:00
Cam Saul
de8eaa880f Prevent mismatches between engine and details (#32736)
* Prevent malicious H2 connection string properties

* Disallow new H2 connections

* Prevent mismatches between engine and details (#151)

Co-authored-by: Cam Saul <github@camsaul.com>

* Fix Kondo lint warning

* Test fix 🔧

* Fix E2E tests in `setup` spec

* Fix E2E tests in `add-new-database` spec

* Improved test

---------

Co-authored-by: dan sutton <dan@dpsutton.com>
Co-authored-by: Nemanja <31325167+nemanjaglumac@users.noreply.github.com>
2023-08-04 01:17:55 +00:00
Maz Ameli
9383467d59 Fix info icon on scalar/trend dashboard cards (#32779)
* add info_filled and update ScalarValue to use it

* fix scalar viz unit spec
2023-08-03 17:37:58 -07:00
Jerry Huang
4c41f848ba Fix nils in subscriptions for values in series (#32813)
* replace nils initial code

* add test
2023-08-03 23:14:22 +00:00
Cal Herries
6e5fd7bdb2 Change field values to have consistent shape in API responses (#32599) 2023-08-04 01:03:57 +02:00
Cam Saul
096f6cf6ee Migrate collection and permissions namespaces to Malli (#32647)
* Migrate collection and permissions namespaces to Malli

* Fix docstring

* Fix Kondo warnings
2023-08-03 21:20:49 +00:00
Jeff Bruemmer
f538747a0f data ref section (#32706) 2023-08-03 16:38:20 -04:00
shaun
c99b56ff58 Systematize date range formats in Filter name (#32490) 2023-08-03 18:29:56 +00:00
Cam Saul
bd5ceedd3d Fast mu/defn (#32843)
* FAST mu/defn

* Malli registry

* Misc fixes

* Some cleanup

* Misc cleanup and test fixes 🔧

* mu/disable-enforcement

* Test fix

* Fix Cljs version of `disable-enforcement`
2023-08-03 09:52:29 -07:00
Ngoc Khuat
e62908effe Define a new persist-models-enabled setting for database. (#32825) 2023-08-03 21:45:50 +07:00
Noah Moss
96dc3d79b9 Get rid of backfill query for user-recent-views (#32873)
* get rid of backfill query for user-recent-views

* clean ns
2023-08-03 09:20:50 -04:00
Cam Saul
24f1cc9106 Move random stuff in metabase.test to metabase.test.util.misc (#32878) 2023-08-03 10:47:27 +01:00
7423 changed files with 729606 additions and 388019 deletions

View File

@@ -1 +0,0 @@
{:lint-as {babashka.fs/with-temp-dir clojure.core/let}}

View File

@@ -1 +0,0 @@
{:hooks {:macroexpand {sci.core/copy-ns sci.core/copy-ns}}}

View File

@@ -1,9 +0,0 @@
(ns sci.core)
(defmacro copy-ns
([ns-sym sci-ns]
`(copy-ns ~ns-sym ~sci-ns nil))
([ns-sym sci-ns opts]
`[(quote ~ns-sym)
~sci-ns
(quote ~opts)]))

View File

@@ -1,145 +0,0 @@
(ns better-cond.core
"A clj-kondo hook to allow linting of better-cond `cond` macro.
This supports better-cond version 2.0.0+.
To use in a project, change the namespace to hooks.better-cond,
put this code in file .clj-kondo/hooks/better_cond.clj, and include
a config.edn entry in the :hooks key like:
:hooks {:analyze-call {better-cond.core/cond hooks.better-cond/cond}}
Note that the expansion of :when-let and :when-some forms currently
takes a shortcut that *would* lead to incorrect values in some
cases of restructuring during actual expansion/evaluation, e.g.,
:when-let [[x y] nil] would not abort the cond, though :when-let
[[x y] [nil nil]] would. However, for linting purposes, the current
expansion approach works just fine. It seems unnecessary to do the
full expansion in these cases for linting purposes, though that could
be done if needed."
(:refer-clojure :exclude [cond])
(:require
[clj-kondo.hooks-api :as api]
[clojure.string :as str]))
(def better-cond-simple-keys
"Special constructs in better cond, either as keywords or symbols.
This includes those keys that are simply transformed. Note that
:when-let and :when-some are *not* included as better-cond allows
multiple bindings but clojure does not. These two must be handled
separately."
#{:let :when :do
'let 'when 'do})
(def better-cond-complex-keys
"Special constructs in better cond, either as keywords or symbols.
This includes those keys that require a multi-step transformation.
For example, :when-let and :when-some get converted to a let
wrapping a when, wrapping the continuing cond. Note that clojure
does not support multiple bindings in the standard when-let and
when-some macros."
{:when-let 'identity
'when-let 'identity
:when-some 'some?
'when-some 'some?})
(defn extract-binding-forms
[bindings]
(keep-indexed #(when (even? %1) %2) bindings))
(defn process-pairs
"Transforms a `cond` with the clauses given as a collection of explicit pairs.
Handles all the special better-cond constructs as keywords or symbols.
Returns a rewrite-clj list-node representing the transformed code."
[node-pairs]
(loop [[[lhs rhs :as pair] & pairs] node-pairs
new-body [(api/token-node 'clojure.core/cond)]] ; Avoid reprocessing the cond with ns here
(if pair
(let [lhs-sexpr (api/sexpr lhs)]
(clojure.core/cond
(= 1 (count pair)) ;; better-cond allows single clause for default
, (api/list-node (conj new-body (api/keyword-node :else) lhs))
(better-cond-simple-keys lhs-sexpr) ;; Handle special better-cond constructs
, (api/list-node
(conj new-body
(api/keyword-node :else)
(api/list-node [(api/token-node (symbol #_"clojure.core" (name lhs-sexpr)))
rhs
(process-pairs pairs)])))
(better-cond-complex-keys lhs-sexpr) ;; Multi stage constructs
, (api/list-node
(conj new-body
(api/keyword-node :else)
(api/list-node [(api/token-node 'let)
rhs
(api/list-node [(api/token-node 'when)
(api/list-node ;; ATTN: shortcut here; fine for linting
[(api/token-node 'every?)
(api/token-node (better-cond-complex-keys lhs-sexpr))
(api/vector-node (->> rhs
api/sexpr
extract-binding-forms
(map api/token-node)))])
(process-pairs pairs)])])))
:else
, (recur pairs (conj new-body lhs rhs))))
(api/list-node new-body))))
(defn cond-hook
[{:keys [node]}]
(let [expr (let [args (rest (:children node))
pairs (partition-all 2 args)]
(process-pairs pairs))]
{:node (with-meta expr
(meta node))}))
(defn process-if-let-pairs [pairs then else]
(if (seq pairs)
(let [[lhs rhs] (first pairs)]
(if (and (api/keyword-node? lhs)
(= :let (api/sexpr lhs)))
(api/list-node (conj [(api/token-node 'clojure.core/let) rhs
(process-if-let-pairs (next pairs) then else)]))
(let [test (api/token-node (gensym "test"))]
(api/list-node
(conj [(api/token-node 'clojure.core/let) (api/vector-node [test rhs])
(api/list-node [(api/token-node 'if) test
(api/list-node
[(api/token-node 'clojure.core/let)
(api/vector-node [lhs test])
(process-if-let-pairs (next pairs) then else)])
else])])))))
then))
(defn if-let-hook
[{:keys [node]}]
(let [expr (let [[binding-vec then else] (rest (:children node))
pairs (partition-all 2 (:children binding-vec))
node (process-if-let-pairs pairs then else)]
node)]
{:node (with-meta expr
(meta node))}))
(defn when-let-hook
[{:keys [node]}]
(let [expr (let [[binding-vec & body] (rest (:children node))]
(api/list-node
[(api/token-node 'better-cond.core/if-let)
binding-vec
(api/list-node (list* (api/token-node 'do)
body))]))]
{:node (with-meta expr
(meta node))}))
(defn defnc-hook [{:keys [node]}]
(let [[defnc-node name-node arg-node & body]
(:children node)
new-node (api/list-node [(api/token-node (if (str/ends-with? (str defnc-node)
"defnc-")
'clojure.core/defn-
'clojure.core/defn))
name-node
arg-node
(api/list-node
(list* (api/token-node 'better-cond.core/cond)
body))])]
{:node new-node}))

View File

@@ -1,9 +0,0 @@
{:hooks
{:analyze-call
{better-cond.core/cond better-cond.core/cond-hook
better-cond.core/defnc better-cond.core/defnc-hook
better-cond.core/defnc- better-cond.core/defnc-hook
better-cond.core/if-let better-cond.core/if-let-hook
better-cond.core/if-some better-cond.core/if-let-hook
better-cond.core/when-let better-cond.core/when-let-hook
better-cond.core/when-some better-cond.core/when-let-hook}}}

View File

@@ -1,19 +0,0 @@
(ns clj-kondo.com.gfredericks.test.chuck.checking
(:require
[clj-kondo.hooks-api :as api]))
(defn checking
[{{:keys [children]} :node}]
(let [[_checking desc & opt+bindings+body] children
[opts binding-vec & body] (if (api/vector-node? (first opt+bindings+body))
(into [(api/map-node {})] opt+bindings+body)
opt+bindings+body)]
(when-not (even? (count (:children binding-vec)))
(throw (ex-info "checking requires an even number of bindings" {})))
{:node (api/list-node
(list*
(api/token-node 'let)
(api/vector-node (into [(api/token-node (symbol (gensym "_checking-desc"))) desc]
(:children binding-vec)))
opts
body))}))

View File

@@ -1,4 +0,0 @@
{:hooks
{:analyze-call
{com.gfredericks.test.chuck.clojure-test/checking
clj-kondo.com.gfredericks.test.chuck.checking/checking}}}

View File

@@ -1,2 +0,0 @@
{:lint-as
{humane-are.core/are+ clojure.test/are}}

View File

@@ -1,39 +0,0 @@
{:config-paths
["macros"]
:lint-as
{toucan2.core/build clojure.core/identity
toucan2.core/compile clojure.core/identity
toucan2.query/with-built-query clojure.core/let
toucan2.tools.compile/build clojure.core/identity
toucan2.tools.compile/compile clojure.core/identity}
:hooks
{:analyze-call
{toucan2.connection/with-connection hooks.toucan2.connection/with-connection
toucan2.connection/with-transaction hooks.toucan2.connection/with-transaction
toucan2.core/with-connection hooks.toucan2.connection/with-connection
toucan2.core/with-transaction hooks.toucan2.connection/with-transaction
toucan2.tools.simple-out-transform/define-out-transform hooks.toucan2.tools.simple-out-transform/define-out-transform
toucan2.tools.with-temp/with-temp hooks.toucan2.tools.with-temp/with-temp}
:macroexpand
{toucan.db/with-call-counting macros.toucan2.execute/with-call-count
toucan.models/defmodel macros.toucan.models/defmodel
toucan2.core/define-after-insert macros.toucan2.tools.after-insert/define-after-insert
toucan2.core/define-after-select macros.toucan2.tools.helpers/define-after-select
toucan2.core/define-after-update macros.toucan2.tools.after-update/define-after-update
toucan2.core/define-before-delete macros.toucan2.tools.helpers/define-before-delete
toucan2.core/define-before-insert macros.toucan2.tools.before-insert/define-before-insert
toucan2.core/define-before-select macros.toucan2.tools.helpers/define-before-select
toucan2.core/define-before-update macros.toucan2.tools.before-update/define-before-update
toucan2.execute/with-call-count macros.toucan2.execute/with-call-count
toucan2.tools.after-insert/define-after-insert macros.toucan2.tools.after-insert/define-after-insert
toucan2.tools.after-select/define-after-select macros.toucan2.tools.helpers/define-after-select
toucan2.tools.after-update/define-after-update macros.toucan2.tools.after-update/define-after-update
toucan2.tools.before-delete/define-before-delete macros.toucan2.tools.helpers/define-before-delete
toucan2.tools.before-insert/define-before-insert macros.toucan2.tools.before-insert/define-before-insert
toucan2.tools.before-select/define-before-select macros.toucan2.tools.helpers/define-before-select
toucan2.tools.before-update/define-before-update macros.toucan2.tools.before-update/define-before-update
toucan2.tools.default-fields/define-default-fields macros.toucan2.tools.default-fields/define-default-fields
toucan2.tools.named-query/define-named-query macros.toucan2.tools.named-query/define-named-query}}}

View File

@@ -1,14 +0,0 @@
(ns hooks.toucan2.connection
(:require [clj-kondo.hooks-api :as hooks]))
(defn with-connection [{{[_ bindings & body] :children} :node}]
(let [[conn-binding connectable] (:children bindings)]
{:node (hooks/list-node
(list*
(hooks/token-node 'let)
(hooks/vector-node [conn-binding (or connectable
(hooks/token-node 'nil))])
body))}))
(defn with-transaction [node]
(with-connection node))

View File

@@ -1,37 +0,0 @@
(ns hooks.toucan2.tools.simple-out-transform
(:require [clj-kondo.hooks-api :as hooks]))
(defn- ignore-unused-binding [x]
(vary-meta x assoc :clj-kondo/ignore [:unused-binding]))
(defn define-out-transform
[{{[_define-out-transform dispatch-value {[instance-binding] :children, :as bindings} & body] :children, :as node} :node}]
{:node (-> (hooks/list-node
[(hooks/token-node 'do)
dispatch-value
(hooks/list-node
(list*
(hooks/token-node 'fn)
(-> (hooks/vector-node
[(ignore-unused-binding (with-meta (hooks/token-node '&query-type) (meta bindings)))
(ignore-unused-binding (with-meta (hooks/token-node '&model) (meta bindings)))
instance-binding])
(with-meta (meta bindings)))
body))])
(with-meta (meta node)))})
(comment
(defn test-define-out-transform []
(as-> '(tools.simple-out-transform/define-out-transform [:toucan.query-type/select.instances ::after-select]
[instance]
(let [wow 1000]
;; don't do after-select if this select is a result of doing something like insert-returning instances
(if (isa? &query-type :toucan2.pipeline/select.instances-from-pks)
instance
(after-select instance)))) <>
(hooks/parse-string (pr-str <>))
(define-out-transform {:node <>})
(:node <>)
(hooks/sexpr <>)
(binding [*print-meta* false #_true]
(clojure.pprint/pprint <>)))))

View File

@@ -1,22 +0,0 @@
(ns hooks.toucan2.tools.with-temp
(:require [clj-kondo.hooks-api :as hooks]))
(defn with-temp [{{[_with-temp {bindings :children} & body] :children} :node}]
(let [bindings* (into
[]
(comp (partition-all 3)
(mapcat (fn [[model binding attributes]]
(let [binding (or binding (hooks/token-node '_))
attributes (or attributes (hooks/token-node 'nil))]
[binding (hooks/list-node
(list
(hooks/token-node 'do)
model
attributes))]))))
bindings)
node* (hooks/list-node
(list*
(hooks/token-node 'let)
(hooks/vector-node bindings*)
body))]
{:node node*}))

View File

@@ -1,5 +0,0 @@
(ns macros.toucan.models)
(defmacro defmodel
[model _table-name]
`(def ~model "Docstring." ~(keyword (name model))))

View File

@@ -1,4 +0,0 @@
(ns macros.toucan2.common)
(defn ignore-unused [symb]
(vary-meta symb assoc :clj-kondo/ignore [:unused-binding]))

View File

@@ -1,6 +0,0 @@
(ns macros.toucan2.execute)
(defmacro with-call-count
[[call-count-fn-binding] & body]
`(let [~call-count-fn-binding (fn [])]
~@body))

View File

@@ -1,10 +0,0 @@
(ns macros.toucan2.tools.after-insert
(:require [macros.toucan2.common :as common]))
(defmacro define-after-insert
[model [instance-binding] & body]
`(do
~model
(fn [~(common/ignore-unused '&model)
~instance-binding]
~@body)))

View File

@@ -1,10 +0,0 @@
(ns macros.toucan2.tools.after-update
(:require [macros.toucan2.common :as common]))
(defmacro define-after-update
[model [instance-binding] & body]
`(do
~model
(fn [~(common/ignore-unused '&model)
~instance-binding]
~@body)))

View File

@@ -1,10 +0,0 @@
(ns macros.toucan2.tools.before-insert
(:require [macros.toucan2.common :as common]))
(defmacro define-before-insert
[model [instance-binding] & body]
`(do
~model
(fn [~(common/ignore-unused '&model)
~instance-binding]
~@body)))

View File

@@ -1,10 +0,0 @@
(ns macros.toucan2.tools.before-update
(:require [macros.toucan2.common :as common]))
(defmacro define-before-update
[model [instance-binding] & body]
`(do
~model
(fn [~(common/ignore-unused '&model)
~instance-binding]
~@body)))

View File

@@ -1,6 +0,0 @@
(ns macros.toucan2.tools.default-fields
(:require [macros.toucan2.common :as common]))
(defmacro define-default-fields [model & body]
`(let [~(common/ignore-unused '&model) ~model]
~@body))

View File

@@ -1,27 +0,0 @@
(ns macros.toucan2.tools.helpers
(:require [macros.toucan2.common :as common]))
(defmacro define-before-select [dispatch-value [args-binding] & body]
`(do
~dispatch-value
(fn [~(common/ignore-unused '&query-type)
~(common/ignore-unused '&model)
~args-binding]
~@body)))
(defmacro define-after-select [model [instance-binding] & body]
`(do
~model
(fn [~(common/ignore-unused '&query-type)
~(common/ignore-unused '&model)
~(common/ignore-unused '&parsed-args)
~instance-binding]
~@body)))
(defmacro define-before-delete
[model [instance-binding] & body]
`(do
~model
(fn [~(common/ignore-unused '&model)
~instance-binding]
~@body)))

View File

@@ -1,22 +0,0 @@
(ns macros.toucan2.tools.named-query
(:require [macros.toucan2.common :as common]))
;;; separate function because recursive macroexpansion doesn't seem to work.
(defn- define-named-query*
[query-name query-type model resolved-query]
`(do
~query-name
~query-type
~model
(fn [~(common/ignore-unused '&query-type)
~(common/ignore-unused '&model)
~(common/ignore-unused '&parsed-args)
~(common/ignore-unused '&unresolved-query)]
~resolved-query)))
(defmacro define-named-query
([query-name resolved-query]
(define-named-query* query-name :default :default resolved-query))
([query-name query-type model resolved-query]
(define-named-query* query-name query-type model resolved-query)))

View File

@@ -1,4 +0,0 @@
{:linters
{:unresolved-symbol
{:exclude
[(clojure.test/is [partial= re= schema= =?])]}}}

View File

@@ -1,5 +0,0 @@
{:hooks
{:analyze-call
{next.jdbc/with-transaction
hooks.com.github.seancorfield.next-jdbc/with-transaction}}
:lint-as {next.jdbc/on-connection clojure.core/with-open}}

View File

@@ -1,18 +0,0 @@
(ns hooks.com.github.seancorfield.next-jdbc
(:require [clj-kondo.hooks-api :as api]))
(defn with-transaction
"Expands (with-transaction [tx expr opts] body)
to (let [tx expr] opts body) pre clj-kondo examples."
[{:keys [:node]}]
(let [[binding-vec & body] (rest (:children node))
[sym val opts] (:children binding-vec)]
(when-not (and sym val)
(throw (ex-info "No sym and val provided" {})))
(let [new-node (api/list-node
(list*
(api/token-node 'let)
(api/vector-node [sym val])
opts
body))]
{:node new-node})))

View File

@@ -1,18 +0,0 @@
(ns hooks.com.github.seancorfield.next-jdbc
(:require [clj-kondo.hooks-api :as api]))
(defn with-transaction
"Expands (with-transaction [tx expr opts] body)
to (let [tx expr] opts body) per clj-kondo examples."
[{:keys [:node]}]
(let [[binding-vec & body] (rest (:children node))
[sym val opts] (:children binding-vec)]
(when-not (and sym val)
(throw (ex-info "No sym and val provided" {})))
(let [new-node (api/list-node
(list*
(api/token-node 'let)
(api/vector-node [sym val])
opts
body))]
{:node new-node})))

View File

@@ -1,14 +1,50 @@
{:config-paths ["macros"]
:linters
{:unresolved-symbol
{:aliased-namespace-symbol {:level :warning}
:invalid-arity {:skip-args [metabase.mbql.util.match/match]} ; TODO (cam): can we fix these?
:keyword-binding {:level :warning}
:main-without-gen-class {:level :warning}
:misplaced-docstring {:level :warning}
:missing-body-in-when {:level :warning}
:missing-docstring {:level :warning}
:missing-else-branch {:level :warning}
:namespace-name-mismatch {:level :warning}
:non-arg-vec-return-type-hint {:level :warning}
:reduce-without-init {:level :warning}
:redundant-fn-wrapper {:level :warning}
:refer-all {:level :warning, :exclude [clojure.test]}
:single-key-in {:level :warning}
:unused-referred-var {:exclude {compojure.core [GET DELETE POST PUT]}}
:use {:level :warning}
:warn-on-reflection {:level :warning}
:metabase/defsetting-must-specify-export {:level :warning}
;;
;; disabled linters
;;
:unexpected-recur {:level :off} ; TODO (cam): I think we just need to tell it how to handle MBQL match and we can enable this?
:used-underscored-binding {:level :off} ; false positives: see https://github.com/clj-kondo/clj-kondo/issues/2152
;;
;; TODO (cam): here are some more linters we should experiment with enabling -- some might be useful.
;;
;; :docstring-leading-trailing-whitespace {:level :warning}
;; :docstring-no-summary {:level :warning}
;; :shadowed-var {:level :warning}
:unresolved-symbol
{:exclude
[instaparse.core/transform
[(build.uberjar/with-duration-ms)
(cljs.test/is [=? malli=])
(clojure.core.logic/fresh)
(clojure.core.logic/matcha)
(clojure.core.logic/run)
(clojure.test/is [query= sql= =? malli=])
(clojure.test/is [query= =? malli=])
(clojure.tools.macro/macrolet)
instaparse.core/transform
(metabase.async.streaming-response/streaming-response)
(metabase.driver.druid.query-processor-test/druid-query-returning-rows)
(metabase.mbql.util.match/match)
@@ -25,33 +61,6 @@
(taoensso.nippy/extend-freeze)
(taoensso.nippy/extend-thaw)]}
:refer-all {:level :warning
:exclude [clojure.test]}
;; TODO (cam): I think we just need to tell it how to handle MBQL match and we can enable this?
:unexpected-recur {:level :off}
;; TODO (cam): can we fix these?
:unused-referred-var {:exclude {compojure.core [GET DELETE POST PUT]}}
:missing-else-branch {:level :warning}
:misplaced-docstring {:level :warning}
:non-arg-vec-return-type-hint {:level :warning}
:missing-body-in-when {:level :warning}
:missing-docstring {:level :warning}
;; TODO (braden): This is useful, but it doesn't grok eg. enterprise/backend/src
:namespace-name-mismatch {:level :off}
:use {:level :warning}
:redundant-fn-wrapper {:level :warning}
:invalid-arity {:skip-args [metabase.mbql.util.match/match]}
:warn-on-reflection {:level :warning}
;; TODO (cam): here are some more linters we should experiment with enabling -- some might be useful.
;; :docstring-no-summary {:level :warning}
;; :docstring-leading-trailing-whitespace {:level :warning}
;; :reduce-without-init {:level :warning}
;; :used-underscored-binding {:level :warning}
;; :single-key-in {:level :warning}
;; :keyword-binding {:level :warning}
;; :main-without-gen-class {:level :warning}
;; :shadowed-var {:level :warning}
:deprecated-var
{:exclude
{metabase.cmd/dump {:namespaces ["metabase\\.cmd-test" "metabase-enterprise\\.serialization\\.cmd-test"]}
@@ -59,12 +68,6 @@
metabase.db.data-migrations/data-migrations {:namespaces ["metabase\\.db\\.data-migrations"]}
metabase.db.data-migrations/defmigration {:namespaces ["metabase\\.db\\.data-migrations"]}
metabase.db.data-migrations/run-migration-if-needed! {:namespaces ["metabase\\.db\\.data-migrations"]}
metabase.driver.common/ThreadSafeSimpleDateFormat {:namespaces ["metabase\\.driver.*"]}
metabase.driver.common/create-db-time-formatters {:namespaces ["metabase\\.driver.*"]}
metabase.driver.common/current-db-time {:namespaces ["metabase.*"]}
metabase.driver.common/current-db-time-date-formatters {:namespaces ["metabase\\.driver.*"]}
metabase.driver.common/current-db-time-native-query {:namespaces ["metabase\\.driver.*"]}
metabase.driver.common/first-successful-parse {:namespaces ["metabase\\.driver.*"]}
metabase.driver.sql-jdbc.execute.old-impl/set-timezone-sql {:namespaces ["metabase\\.driver.*"]}
metabase.driver.sql-jdbc.execute/set-time-zone-if-supported! {:namespaces ["metabase\\.driver.*"]}
metabase.driver/current-db-time {:namespaces ["metabase.*"]}
@@ -72,110 +75,43 @@
metabase.public-settings.premium-features/enable-enhancements? {:namespaces ["metabase\\.models.*"]}
metabase.query-processor.middleware.resolve-joins/maybe-resolve-source-table {:namespaces ["metabase.*"]}
metabase.query-processor.util/normalize-token {:namespaces ["metabase.*"]}
metabase.util.honeysql-extensions/* {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/*honey-sql-version* {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/+ {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/- {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/->boolean {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/->date {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/->datetime {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/->integer {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/->time {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/->timestamp {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/->timestamp-with-time-zone {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions// {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/IdentifierType {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/abs {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/at-time-zone {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/call {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/cast {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/cast-unless-type-in {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/ceil {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/concat {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/database-type {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/day {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/dec {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/floor {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/format {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/hour {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/identifier {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/identifier? {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/inc {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/is-of-type? {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/literal {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/maybe-cast {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/minute {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/mod {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/month {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/quarter {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/quoted-cast {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/raw {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/round {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/second {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/type-info {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/type-info->db-type {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/unwrap-typed-honeysql-form {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/week {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/with-database-type-info {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/with-type-info {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
metabase.util.honeysql-extensions/year {:namespaces ["^metabase\\.driver\\..*$" "^metabase\\.test\\.data\\..*" "^metabase\\.query-processor-test\\..*$"]}
schema.core/both {:namespaces ["metabase.*"]}
schema.core/either {:namespaces ["metabase.*"]}}}
:discouraged-var
{clojure.core/print {:message "Use clojure.tools.logging instead of clojure.core/print"}
clojure.core/println {:message "Use clojure.tools.logging instead of clojure.core/println"}
clojure.core/printf {:message "Use clojure.tools.logging instead of clojure.core/printf"}
clojure.core/prn {:message "Use clojure.tools.logging instead of clojure.core/prn"}
clojure.core/pr {:message "Use clojure.tools.logging instead of clojure.core/pr"}
clojure.java.jdbc/get-connection {:message "Use sql-jdbc.execute/do-with-connection-with-options (for drivers) or t2/with-connection (for the app DB) instead of jdbc/get-connection"}
clojure.java.jdbc/with-db-connection {:message "Use sql-jdbc.execute/do-with-connection-with-options (for drivers) or t2/with-connection (for the app DB) instead of jdbc/with-db-connection"}
clojure.java.jdbc/with-db-metadata {:message "Use sql-jdbc.execute/do-with-connection-with-options + .getMetaData instead of jdbc/with-db-metadata"}
clojure.pprint/pprint {:message "Use clojure.tools.logging instead of clojure.pprint/pprint"}
clojure.string/lower-case {:message "Use metabase.util/lower-case-en instead of clojure.string/lower-case"}
clojure.string/upper-case {:message "Use metabase.util/upper-case-en instead of clojure.string/upper-case"}
honeysql.core/call {:message "Use hx/call instead because it is Honey SQL 2 friendly"}
honeysql.core/raw {:message "Use hx/raw instead because it is Honey SQL 2 friendly"}
java-time/with-clock {:message "Use mt/with-clock"}
java.util.UUID/randomUUID {:message "Use clojure.core/random-uuid instead of java.util.UUID/randomUUID"}
medley.core/random-uuid {:message "Use clojure.core/random-uuid instead of medley.core/random-uuid"}
metabase.test/with-temp {:message "Use t2.with-temp/with-temp instead of metabase.test/with-temp"}
;; metabase.test/with-temp* {:message "Use t2.with-temp/with-temp instead of metabase.test/with-temp*"}
toucan.db/select {:message "Use t2/select instead of toucan.db/select"}
toucan.db/select-one {:message "Use t2/select-one instead of toucan.db/select-one"}
toucan.db/select-one-id {:message "Use t2/select-one-pk instead of toucan.db/select-one-id"}
toucan.db/select-one-field {:message "Use t2/select-one-fn instead of toucan.db/select-one-field"}
toucan.db/select-ids {:message "Use t2/select-pks-set instead of toucan.db/select-ids"}
toucan.db/select-field {:message "Use t2/select-fn instead of toucan.db/select-field"}
toucan.db/select-field->field {:message "Use t2/select-fn->fn instead of toucan.db/select-field->field"}
toucan.db/select-field->id {:message "Use t2/select-fn->pk instead of toucan.db/select-field->id"}
toucan.db/select-id->field {:message "Use t2/select-pk->field instead of toucan.db/select-id->field"}
toucan.db/simple-insert! {:message "Use t2/insert-returning-pks! with table name instead of toucan.db/simple-insert!"}
toucan.db/simple-insert-many! {:message "Use t2/insert-returning-pks! with table name instead of toucan.db/simple-insert-many!"}
toucan.db/simple-delete! {:message "Use t2/delete! with table name instead of toucan.db/simple-delete!"}
toucan.db/delete! {:message "Use t2/delete! instead of toucan.db/delete!"}
toucan.db/insert! {:message "Use t2/insert-returning-instances! instead of toucan.db/insert!"}
toucan.db/update! {:message "Use t2/update! instead of toucan.db/update!"}
toucan.db/update-where! {:message "Use t2/update! instead of toucan.db/update-where!"}
toucan.db/query {:message "Use mdb.query/query instead of toucan.db/query"}
toucan.db/count {:message "Use t2/count instead of toucan.db/count"}
toucan.db/exists? {:message "Use t2/exists? instead of toucan.db/exists?"}
toucan.db/transaction {:message "Use t2/with-transaction instead of toucan.db/transaction"}
toucan.db/with-call-counting {:message "Use t2/with-call-count instead of toucan.db/with-call-counting"}
toucan.db/execute! {:message "Use t2/query-one instead of toucan.db/execute!"}
toucan.db/reducible-query {:message "Use mdb.query/reducible-query instead of toucan.db/reducible-query"}
toucan.db/resolve-model {:message "Use metabase.db.util/resolve-model instead of toucan.db/resolve-model"}
toucan.models/defmodel {:message "Define a method for t2/table-name instead of toucan.models/defmodel"}
toucan.models/primary-key {:message "Use metabase.db.util/primary-key instead of toucan.models/primary-key"}
toucan.models/model? {:message "Use mdb.u/toucan-model? instead of toucan.models/model?"}
toucan.hydrate/hydrate {:message "Use t2/hydrate instead of toucan.hydrate/hydrate"}
toucan.util.test/with-temp-defaults {:message "Use t2.with-temp/with-temp-defaults instead of toucan.util.test/with-temp-defaults"}
toucan.util.test/with-temp {:message "Use t2.with-temp/with-temp instead of toucan.util.test/with-temp"}
toucan.util.test/with-temp* {:message "Use t2.with-temp/with-temp instead of toucan.util.test/with-temp*"}}
{clojure.core/print {:message "Use metabase.util.log instead of clojure.core/print"}
clojure.core/println {:message "Use metabase.util.log instead of clojure.core/println"}
clojure.core/printf {:message "Use metabase.util.log instead of clojure.core/printf"}
clojure.core/prn {:message "Use metabase.util.log instead of clojure.core/prn"}
clojure.core/pr {:message "Use metabase.util.log instead of clojure.core/pr"}
clojure.core/tap> {:message "Don't use tap> is source code"}
clojure.core/time {:message "Don't use time in source code"}
clojure.java.jdbc/get-connection {:message "Use sql-jdbc.execute/do-with-connection-with-options (for drivers) or t2/with-connection (for the app DB) instead of jdbc/get-connection"}
clojure.java.jdbc/with-db-connection {:message "Use sql-jdbc.execute/do-with-connection-with-options (for drivers) or t2/with-connection (for the app DB) instead of jdbc/with-db-connection"}
clojure.java.jdbc/with-db-metadata {:message "Use sql-jdbc.execute/do-with-connection-with-options + .getMetaData instead of jdbc/with-db-metadata"}
clojure.pprint/pprint {:message "Use metabase.util.log instead of clojure.pprint/pprint"}
clojure.string/lower-case {:message "Use metabase.util/lower-case-en instead of clojure.string/lower-case"}
clojure.string/upper-case {:message "Use metabase.util/upper-case-en instead of clojure.string/upper-case"}
fipp.edn/pprint {:message "Use metabase.util.log instead of fipp.edn/pprint"}
honeysql.core/call {:message "Use hx/call instead because it is Honey SQL 2 friendly"}
honeysql.core/raw {:message "Use hx/raw instead because it is Honey SQL 2 friendly"}
java-time/with-clock {:message "Use mt/with-clock"}
java.util.UUID/randomUUID {:message "Use clojure.core/random-uuid instead of java.util.UUID/randomUUID"}
malli.core/explainer {:message "Use metabase.util.malli.registry/explainer instead of malli.core/explainer"}
me.flowthing.pp/pprint {:message "Use metabase.util.log instead of me.flowthing.pp/pprint"}
medley.core/random-uuid {:message "Use clojure.core/random-uuid instead of medley.core/random-uuid"}
metabase.lib.equality/find-column-indexes-for-refs {:message "Use lib.equality/closest-matches-in-metadata or lib.equality/find-closest-matches-for-refs instead of lib.equality/find-column-indexes-for-refs"}
metabase.test/with-temp* {:message "Use mt/with-temp instead of mt/with-temp*"}
toucan2.tools.with-temp {:message "Use mt/with-temp instead of t2.with-temp/with-temp"}}
:discouraged-namespace
{camel-snake-kebab.core {:message "CSK is not Turkish-safe, use the versions in metabase.util instead."}
clojure.tools.logging {:message "Use metabase.util.log instead of clojure.tools.logging directly"}
honeysql.core {:message "Use Honey SQL 2. Honey SQL 1 is removed as a dependency in Metabase 49+."}
honeysql.format {:message "Use Honey SQL 2. Honey SQL 1 is removed as a dependency in Metabase 49+."}
honeysql.helpers {:message "Use Honey SQL 2. Honey SQL 1 is removed as a dependency in Metabase 49+."}
honeysql.types {:message "Use Honey SQL 2. Honey SQL 1 is removed as a dependency in Metabase 49+."}
honeysql.util {:message "Use Honey SQL 2. Honey SQL 1 is removed as a dependency in Metabase 49+."}
metabase.util.jvm {:message "All of metabase.util.jvm is re-exported from metabase.util; prefer that"}}
:unresolved-var
@@ -252,6 +188,7 @@
metabase.api.notify api.notify
metabase.api.permission-graph api.permission-graph
metabase.api.permissions api.permissions
metabase.api.permissions-test-util perm-test-util
metabase.api.pivots api.pivots
metabase.api.premium-features api.premium-features
metabase.api.preview-embed api.preview-embed
@@ -274,6 +211,7 @@
metabase.api.util api.util
metabase.async.streaming-response.thread-pool thread-pool
metabase.automagic-dashboards.core magic
metabase.automagic-dashboards.dashboard-templates dashboard-templates
metabase.automagic-dashboards.populate populate
metabase.cmd.copy.h2 copy.h2
metabase.config config
@@ -321,6 +259,7 @@
metabase.driver.sql.parameters.substitution sql.params.substitution
metabase.email-test et
metabase.email.messages messages
metabase.formatter formatter
metabase.http-client client
metabase.lib.util lib.util
metabase.mbql.normalize mbql.normalize
@@ -339,6 +278,7 @@
metabase.models.interface mi
metabase.models.moderation-review moderation-review
metabase.models.native-query-snippet native-query-snippet
metabase.models.params params
metabase.models.permissions perms
metabase.models.permissions-group perms-group
metabase.models.permissions-group-membership perms-group-membership
@@ -358,9 +298,9 @@
metabase.pulse.markdown markdown
metabase.pulse.render render
metabase.pulse.render.body body
metabase.pulse.render.common common
metabase.pulse.render.style style
metabase.pulse.parameters params
metabase.pulse.test-util pulse.test-util
metabase.pulse.parameters pulse-params
metabase.query-processor-test qp.test
metabase.query-processor.context qp.context
metabase.query-processor.error-type qp.error-type
@@ -387,6 +327,9 @@
metabase.query-processor.timezone qp.timezone
metabase.query-processor.util qp.util
metabase.related related
metabase.search.config search.config
metabase.search.filter search.filter
metabase.search.util search.util
metabase.search.scoring scoring
metabase.server.middleware.auth mw.auth
metabase.server.middleware.browser-cookie mw.browser-cookie
@@ -425,6 +368,7 @@
metabase.test.domain-entities test.de
metabase.test.mock.util mock.util
metabase.test.sync test.sync
metabase.test.redefs test.redefs
metabase.test.util.js test.js
metabase.test.util.timezone test.tz
metabase.timeseries-query-processor-test.util tqpt
@@ -439,9 +383,7 @@
metabase.util.encryption encryption
metabase.util.encryption-test encryption-test
metabase.util.files u.files
metabase.util.honey-sql-1 h1x
metabase.util.honey-sql-2 h2x
metabase.util.honeysql-extensions hx
metabase.util.i18n i18n
metabase.util.i18n.impl i18n.impl
metabase.util.jvm u.jvm
@@ -465,8 +407,10 @@
toucan.db db
toucan.models models}}
:metabase/validate-deftest {:level :warning}
:metabase/missing-test-expr-requires-in-cljs {:level :warning}}
:metabase/validate-deftest {:level :warning}
:metabase/missing-test-expr-requires-in-cljs {:level :warning}
:metabase/i-like-making-cams-eyes-bleed-with-horrifically-long-tests {:level :warning}
:metabase/warn-about-schema= {:level :warning}}
:lint-as
{clojure.core.logic/defne clj-kondo.lint-as/def-catch-all
@@ -475,6 +419,7 @@
honeysql.helpers/defhelper clj-kondo.lint-as/def-catch-all
honeysql.util/defalias clojure.core/def
metabase-enterprise.serialization.test-util/with-random-dump-dir clojure.core/let
metabase-enterprise.serialization.test-util/with-dbs clojure.core/fn
metabase.actions.test-util/with-actions clojure.core/let
metabase.api.common/let-404 clojure.core/let
metabase.api.search-test/do-test-users clojure.core/let
@@ -487,7 +432,8 @@
metabase.db.schema-migrations-test.impl/with-temp-empty-app-db clojure.core/let
metabase.domain-entities.malli/defn schema.core/defn
metabase.driver.mongo.query-processor/mongo-let clojure.core/let
metabase.driver.mongo.util/with-mongo-connection clojure.core/let
metabase.driver.mongo.connection/with-mongo-client clojure.core/let
metabase.driver.mongo.connection/with-mongo-database clojure.core/let
metabase.driver.sql-jdbc.actions/with-jdbc-transaction clojure.core/let
metabase.driver.sql-jdbc.connection/with-connection-spec-for-testing-connection clojure.core/let
metabase.driver.sql-jdbc.execute.diagnostic/capturing-diagnostic-info clojure.core/fn
@@ -514,12 +460,18 @@
metabase.test/with-actions clojure.core/let
metabase.test/with-open-channels clojure.core/let
metabase.test/with-single-admin-user clojure.core/fn
metabase.test/with-temp-dir clojure.core/let
metabase.test/with-temp-empty-app-db clojure.core/let
metabase.test/with-temp-file clojure.core/let
metabase.test/with-user-in-groups clojure.core/let
metabase.upload-test/with-upload-table! clojure.core/let
metabase.util.files/with-open-path-to-resource clojure.core/let
metabase.util.malli.defn/defn schema.core/defn
metabase.util.malli.fn/fn schema.core/fn
metabase.util.malli/defmethod schema.core/defmethod
metabase.util.malli/defn schema.core/defn
metabase.util.malli/fn schema.core/fn
metabase.util.ssh/with-ssh-tunnel clojure.core/let
monger.operators/defoperator clojure.core/def
potemkin.types/defprotocol+ clojure.core/defprotocol
@@ -535,22 +487,24 @@
{:analyze-call
{cljs.test/deftest hooks.clojure.test/deftest
cljs.test/is hooks.clojure.test/is
cljs.test/use-fixtures hooks.clojure.test/use-fixtures
clojure.test/deftest hooks.clojure.test/deftest
clojure.test/is hooks.clojure.test/is
clojure.test/use-fixtures hooks.clojure.test/use-fixtures
metabase-enterprise.advanced-config.caching-test/with-temp-persist-models hooks.common/with-seven-bindings
metabase-enterprise.advanced-permissions.models.permissions.application-permissions-test/with-new-group-and-current-graph hooks.common/with-two-top-level-bindings
metabase-enterprise.audit-app.pages-test/with-temp-objects hooks.common/with-one-binding
metabase-enterprise.serialization.test-util/with-temp-dpc hooks.toucan.util.test/with-temp*
metabase-enterprise.serialization.test-util/with-temp-dpc hooks.toucan2.tools.with-temp/with-temp
metabase.analytics.prometheus-test/with-prometheus-system hooks.common/with-two-bindings
metabase.api.automagic-dashboards-test/with-indexed-model hooks.metabase.api.automagic-dashboards-test/with-indexed-model
metabase.api.alert-test/with-alert-in-collection hooks.common/with-four-bindings
metabase.api.card-test/with-persistence-setup hooks.common/with-one-top-level-binding
metabase.api.card-test/with-temp-native-card hooks.common/with-two-bindings
metabase.api.card-test/with-temp-native-card-with-params hooks.common/with-two-bindings
metabase.api.card-test/with-temp-native-card! hooks.common/with-two-bindings
metabase.api.card-test/with-temp-native-card-with-params! hooks.common/with-two-bindings
metabase.api.collection-test/with-french-user-and-personal-collection hooks.common/with-two-top-level-bindings
metabase.api.common/defendpoint hooks.metabase.api.common/defendpoint
metabase.api.common/defendpoint-async hooks.metabase.api.common/defendpoint
metabase.api.common/defendpoint-async-schema hooks.metabase.api.common/defendpoint
metabase.api.common/defendpoint-schema hooks.metabase.api.common/defendpoint
metabase.api.dashboard-test/with-chain-filter-fixtures hooks.common/let-one-with-optional-value
metabase.api.dashboard-test/with-simple-dashboard-with-tabs hooks.common/with-one-binding
metabase.api.card-test/with-card-param-values-fixtures hooks.common/let-one-with-optional-value
@@ -570,6 +524,9 @@
metabase.db.schema-migrations-test.impl/test-migrations hooks.metabase.db.schema-migrations-test.impl/test-migrations
metabase.dashboard-subscription-test/with-link-card-fixture-for-dashboard hooks.common/let-second
metabase.driver.bigquery-cloud-sdk-test/calculate-bird-scarcity hooks.metabase.query-processor-test.expressions-test/calculate-bird-scarcity
metabase.lib.test-util.macros/$ids hooks.metabase.test.data/$ids
metabase.lib.test-util.macros/mbql-query hooks.metabase.test.data/mbql-query
metabase.lib.test-util.macros/with-testing-against-standard-queries hooks.metabase.lib.test-util.macros/with-testing-against-standard-queries
metabase.mbql.schema.macros/defclause hooks.metabase.mbql.schemas.macros/defclause
metabase.models.collection-test/with-collection-hierarchy hooks.common/let-one-with-optional-value
metabase.models.collection-test/with-personal-and-impersonal-collections hooks.common/with-two-bindings
@@ -579,7 +536,7 @@
metabase.models.interface/define-batched-hydration-method hooks.metabase.models.interface/define-hydration-method
metabase.models.pulse-test/with-dashboard-subscription-in-collection hooks.common/with-four-bindings
metabase.models.pulse-test/with-pulse-in-collection hooks.common/with-four-bindings
metabase.models.setting.multi-setting/define-multi-setting hooks.metabase.models.setting/defsetting
metabase.models.setting.multi-setting/define-multi-setting hooks.metabase.models.setting/define-multi-setting
metabase.models.setting/defsetting hooks.metabase.models.setting/defsetting
metabase.public-settings.premium-features/defenterprise hooks.metabase.public-settings.premium-features/defenterprise
metabase.pulse.test-util/checkins-query-card hooks.metabase.test.data/$ids
@@ -612,10 +569,10 @@
metabase.test/with-log-level hooks.common/with-ignored-first-arg
metabase.test/with-log-messages-for-level hooks.common/with-ignored-first-arg
metabase.test/with-non-admin-groups-no-root-collection-perms hooks.common/do*
metabase.test/with-temp* hooks.toucan.util.test/with-temp*
metabase.test/with-temp hooks.toucan2.tools.with-temp/with-temp
metabase.test/with-temp-file hooks.metabase.test.util/with-temp-file
metabase.test/with-temporary-setting-values hooks.metabase.test.util/with-temporary-setting-values
toucan.util.test/with-temp* hooks.toucan.util.test/with-temp*}
metabase.util.malli.registry/def hooks.metabase.util.malli.registry/def}
:macroexpand
{clojurewerkz.quartzite.jobs/build macros.quartz/build-job
@@ -643,11 +600,11 @@
metabase.related-test/with-world macros.metabase.related-test/with-world
metabase.shared.util.namespaces/import-fn macros.metabase.shared.util.namespaces/import-fn
metabase.test.data.users/with-group-for-user macros.metabase.test.data.users/with-group-for-user
metabase.test.util/with-temp-env-var-value macros.metabase.test.util/with-temp-env-var-value
metabase.test.util/with-temp-env-var-value! macros.metabase.test.util/with-temp-env-var-value!
metabase.test.util/with-temporary-raw-setting-values macros.metabase.test.util/with-temporary-raw-setting-values
metabase.test/with-group-for-user macros.metabase.test.data.users/with-group-for-user
metabase.test/with-persistence-enabled macros.metabase.test.persistence/with-persistence-enabled
metabase.test/with-temp-env-var-value macros.metabase.test.util/with-temp-env-var-value
metabase.test/with-temp-env-var-value! macros.metabase.test.util/with-temp-env-var-value!
metabase.test/with-temporary-raw-setting-values macros.metabase.test.util/with-temporary-raw-setting-values}}
:config-in-comment
@@ -669,45 +626,31 @@
:name test-namespaces}
{:pattern "^(?!.*-test(?:\\..*)?$)(?!.*test-util$)(?!^metabase\\.test.*).*$"
:name source-namespaces}
{:pattern "metabase\\.cmd.*"
{:pattern "(?:(?:^metabase\\.cmd.*)|(?:^build.*)|(?:^metabuild-common.*)|(?:^release.*)|(?:^i18n.*)|(?:^lint-migrations-file$))"
:name printable-namespaces}
{:pattern "^metabase\\.lib\\.*"
:name metabase-lib}
;; Basically everything except `metabase.driver.` or `metabase.test-data.` except for the drivers explicitly called
;; out below. Remove these drivers from the regex once we switch to Honey SQL 2.
;;
;; This regex is way too big to easily read or write by hand, so use the [[metabase.util.regex/rx]] macro to
;; generate it. It was generated from the following form:
;; QP source namespaces: `metabase.query-processor.*`, `metabase-enterprise.sandbox.query-processor.*`, and
;; `metabase.driver.*`, excluding `-test` namespaces.
;;
;; (str
;; (metabase.util.regex/rx
;; #"^metabase\."
;; [:not [:and #"util\." [:or "honeysql-extensions" "honey-sql-1"]]]
;; [:not "query-processor-test"]
;; [:not [:and
;; [:or "driver" #"test\.data"]
;; #"\."
;; [:or
;; [:and "sql" [:? "-jdbc"]]
;; #"(?:sql(?:-jdbc)?)"
;; "bigquery-cloud-sdk"
;; [:and "presto" [:? [:or "-common" "-jdbc"]]]
;; "sqlserver"]
;; [:? "-test"]
;; [:or #"\." #"$"]]]
;; ".*"))
;;
;; Please keep this form updated when you change the generated regex! <3
{:pattern "^metabase\\.(?!util\\.(?:(?:honeysql-extensions)|(?:honey-sql-1)))(?!query-processor-test)(?!(?:(?:driver)|(?:test\\.data))\\.(?:(?:sql(?:-jdbc)?)|(?:(?:sql(?:-jdbc)?))|(?:bigquery-cloud-sdk)|(?:presto(?:(?:(?:-common)|(?:-jdbc)))?)|(?:sqlserver))(?:-test)?(?:(?:\\.)|(?:$))).*"
:name honey-sql-2-namespaces}]
{:pattern "metabase(?:(?:(?:-enterprise\\.sandbox)?\\.query-processor\\.)|(?:\\.driver\\.)).*(?<!-test)$"
:name qp-and-driver-source-namespaces}]
:config-in-ns
{test-namespaces
{:linters
{:inline-def {:level :off}
:missing-docstring {:level :off}
:private-call {:level :off}
:hooks.metabase.test.data/mbql-query-first-arg {:level :error}}}
{:inline-def {:level :off}
:missing-docstring {:level :off}
:private-call {:level :off}
:metabase/defsetting-must-specify-export {:level :off}
:hooks.metabase.test.data/mbql-query-first-arg {:level :error}
:metabase/test-helpers-use-non-thread-safe-functions {:level :warning}}
:hooks
{:analyze-call
{clojure.core/defmacro hooks.clojure.core/non-thread-safe-form-should-end-with-exclamation
clojure.core/defn hooks.clojure.core/non-thread-safe-form-should-end-with-exclamation
clojure.core/defn- hooks.clojure.core/non-thread-safe-form-should-end-with-exclamation}}}
source-namespaces
{:linters
@@ -717,28 +660,20 @@
printable-namespaces
{:linters
{:discouraged-var {:level :off}}}
honey-sql-2-namespaces
{:linters
{:discouraged-namespace
{clj-yaml.core {:message "Use metabase.util.yaml"}
honeysql.core {:message "Use Honey SQL 2"}
honeysql.format {:message "Use Honey SQL 2"}
honeysql.helpers {:message "Use Honey SQL 2"}
honeysql.types {:message "Use Honey SQL 2"}
honeysql.util {:message "Use Honey SQL 2"}
metabase.util.honeysql-extensions {:message "Use h2x"}
metabase.util.honey-sql-1 {:message "Use h2x"}}}}
{:main-without-gen-class {:level :off}
:discouraged-var {clojure.pprint/pprint {:level :off}
clojure.core/print {:level :off}
clojure.core/printf {:level :off}
clojure.core/println {:level :off}
clojure.string/lower-case {:level :off}
clojure.string/upper-case {:level :off}}}}
;; enable all the extra linters we haven't enabled in the core app yet in MLv2. It's all new code so we can adhere
;; to the new stricter rules from day 1
metabase-lib
{:linters
{:docstring-leading-trailing-whitespace {:level :warning}
:reduce-without-init {:level :warning}
:used-underscored-binding {:level :warning}
:single-key-in {:level :warning}
:keyword-binding {:level :warning}
:shadowed-var {:level :warning}
:metabase/deftest-not-marked-parallel-or-synchronized {:level :warning}
@@ -746,5 +681,24 @@
;; eventually we should do this for the whole codebase, but the args are in the opposite order so switching them
;; all at once isn't trivial, at least we can stop using it in new code.
:discouraged-var
{medley.core/map-keys {:message "Use clojure.core/update-keys"}
medley.core/map-vals {:message "Use clojure.core/update-vals"}}}}}}
{medley.core/map-keys {:message "Use clojure.core/update-keys"}
medley.core/map-vals {:message "Use clojure.core/update-vals"}
metabase.test/with-temp {:message "Don't use application database inside MLv2 code"}}
:discouraged-namespace
{toucan.db {:message "Don't use application database inside MLv2 code"}
toucan.models {:message "Don't use application database inside MLv2 code"}
toucan.util.test {:message "Don't use application database inside MLv2 code"}
toucan2.core {:message "Don't use application database inside MLv2 code"}}}}
qp-and-driver-source-namespaces
{:linters
{:discouraged-namespace
{toucan.db {:message "Don't use application database directly in QP code; use QP Store/metadata provider"}
toucan.models {:message "Don't use application database directly in QP code; use QP Store/metadata provider"}
toucan.util.test {:message "Don't use application database directly in QP code; use QP Store/metadata provider"}
toucan2.core {:message "Don't use application database directly in QP code; use QP Store/metadata provider"}}
:discouraged-var
{metabase.db.query/query {:message "Don't use application database directly in QP code; use QP Store/metadata provider"}
metabase.db.query/reducible-query {:message "Don't use application database directly in QP code; use QP Store/metadata provider"}}}}}}

View File

@@ -0,0 +1,200 @@
(ns hooks.clojure.core
(:require
[clj-kondo.hooks-api :as hooks]
[clojure.string :as str]))
(defn- node->qualified-symbol [node]
(try
(when (hooks/token-node? node)
(let [sexpr (hooks/sexpr node)]
(when (symbol? sexpr)
(let [resolved (hooks/resolve {:name sexpr})]
(when-not (= :clj-kondo/unknown-namespace (:ns resolved))
(symbol (name (:ns resolved)) (name (:name resolved))))))))
;; some symbols like `*count/Integer` aren't resolvable.
(catch Exception _
nil)))
(def ^:private white-card-symbols
'#{;; these toucan methods might actually set global values if it's used outside of a transaction,
;; but since mt/with-temp runs in a transaction, so we'll ignore them in this case.
toucan2.core/delete!
toucan2.core/update!
toucan2.core/insert!
toucan2.core/insert-returning-instance!
toucan2.core/insert-returning-instances!
toucan2.core/insert-returning-pk!
toucan2.core/insert-returning-pks!
clojure.core.async/<!!
clojure.core.async/>!!
clojure.core.async/alts!!
clojure.core.async/close!
clojure.core.async/poll!
clojure.core.memoize/memo-clear!
clojure.core/conj!
clojure.core/persistent!
clojure.core/reset!
clojure.core/swap!
clojure.core/volatile!
clojure.core/vreset!
clojure.core/vswap!
clojure.java.jdbc/execute!
methodical.core/add-aux-method-with-unique-key!
methodical.core/remove-aux-method-with-unique-key!
next.jdbc/execute!
;; TODO: most of these symbols shouldn't be here, we should go through them and
;; find the functions/macros that use them and make sure their names end with !
;; best way to do this is try remove each of these and rely on kondo output to find places where it's used
clojure.test/grant-collection-perms!
clojure.test/grant-collection-perms-fn!
clojure.test/grant-perms-fn!
clojure.test/purge-old-entries!
clojure.test/revoke-collection-perms!
clojure.test/save-results!
metabase-enterprise.advanced-permissions.models.permissions/update-db-download-permissions!
metabase-enterprise.internal-user/install-internal-user!
metabase-enterprise.sso.integrations.saml-test/call-with-login-attributes-cleared!
metabase.actions/perform-action!
metabase.analytics.snowplow-test/fake-track-event-impl!
metabase.analytics.snowplow/track-event-impl!
metabase.api.public-test/add-card-to-dashboard!
metabase.cmd.dump-to-h2/dump-to-h2!
metabase.cmd.load-from-h2/load-from-h2!
metabase.core/ensure-audit-db-installed!
metabase.db.schema-migrations-test.impl/run-migrations-in-range!
metabase.db.setup/migrate!
metabase.db.setup/setup-db!
metabase.db/setup-db!
metabase.driver.mongo-test/create-database-from-row-maps!
metabase.driver.postgres-test/create-enums-db!
metabase.driver.postgres-test/drop-if-exists-and-create-db!
metabase.driver.sql-jdbc.execute/execute-statement!
metabase.email-test/reset-inbox!
metabase.email/send-email!
metabase.models.action/insert!
metabase.models.collection.graph-test/clear-graph-revisions!
metabase.models.collection.graph-test/do-with-n-temp-users-with-personal-collections!
metabase.models.field-values/create-or-update-full-field-values!
metabase.models.model-index/add-values!
metabase.models.moderation-review/create-review!
metabase.models.on-demand-test/add-dashcard-with-parameter-mapping!
metabase.models.permissions/grant-application-permissions!
metabase.models.permissions/grant-collection-read-permissions!
metabase.models.permissions/grant-collection-readwrite-permissions!
metabase.models.permissions/grant-full-data-permissions!
metabase.models.permissions/grant-native-readwrite-permissions!
metabase.models.permissions/grant-permissions!
metabase.models.permissions/revoke-application-permissions!
metabase.models.permissions/revoke-data-perms!
metabase.models.permissions/update-data-perms-graph!
metabase.models.permissions/update-group-permissions!
metabase.models.persisted-info/ready-database!
metabase.models.revision/revert!
metabase.models.setting-test/test-user-local-allowed-setting!
metabase.models.setting-test/test-user-local-only-setting!
metabase.models.setting.cache/restore-cache!
metabase.models.setting/set!
metabase.models.setting/validate-settings-formatting!
metabase.permissions.test-util/with-restored-perms!
metabase.pulse/send-notifications!
metabase.pulse/send-pulse!
metabase.query-processor.streaming.interface/begin!
metabase.query-processor.streaming.interface/finish!
metabase.query-processor.streaming.interface/write-row!
metabase.sample-data/try-to-extract-sample-database!
metabase.setup/create-token!
metabase.sync.sync-metadata.fields.sync-metadata/update-field-metadata-if-needed!
metabase.sync.sync-metadata/sync-db-metadata!
metabase.sync.util-test/sync-database!
metabase.sync.util/store-sync-summary!
metabase.sync/sync-database!
metabase.task.index-values/job-init!
metabase.task.persist-refresh/job-init!
metabase.task.persist-refresh/refresh-tables!
metabase.task.persist-refresh/schedule-persistence-for-database!
metabase.task/delete-task!
metabase.test.data.bigquery-cloud-sdk/execute!
metabase.test.data.impl/copy-db-tables-and-fields!
metabase.test.data.impl/get-or-create-database!
metabase.test.data.impl/get-or-create-test-data-db!
metabase.test.data.interface/create-db!
metabase.test.data.interface/destroy-db!
metabase.test.data.oracle/create-user!
metabase.test.data.oracle/drop-user!
metabase.test.data.sql-jdbc.load-data/make-insert!
metabase.test.data.users/clear-cached-session-tokens!
metabase.test.initialize/do-initialization!
metabase.test.initialize/initialize-if-needed!
metabase.test.integrations.ldap/start-ldap-server!
metabase.test.util.log/ensure-unique-logger!
metabase.test.util.log/set-ns-log-level!
metabase.test.util/do-with-temp-env-var-value!
metabase.test.util/restore-raw-setting!
metabase.test.util/upsert-raw-setting!
metabase.test/initialize-if-needed!
metabase.test/test-helpers-set-global-values!
metabase.test/with-temp-env-var-value!
metabase.upload-test/set-local-infile!
metabase.util.files/create-dir-if-not-exists!
metabase.util.ssh-test/start-mock-servers!
metabase.util.ssh-test/stop-mock-servers!})
(defn- end-with-exclamation?
[s]
(str/ends-with? s "!"))
(defn- non-thread-safe-form-should-end-with-exclamation*
[{[defn-or-defmacro form-name] :children, :as node}]
(when-not (and (:string-value form-name)
(end-with-exclamation? (:string-value form-name)))
(letfn [(walk [f form]
(f form)
(doseq [child (:children form)]
(walk f child)))]
(walk (fn [form]
(when-let [qualified-symbol (node->qualified-symbol form)]
(when (and (not (contains? white-card-symbols qualified-symbol))
(end-with-exclamation? qualified-symbol))
(hooks/reg-finding! (assoc (meta form-name)
:message (format "The name of this %s should end with `!` because it contains calls to non thread safe form `%s`."
(:string-value defn-or-defmacro) qualified-symbol)
:type :metabase/test-helpers-use-non-thread-safe-functions)))))
node))
node))
(defn non-thread-safe-form-should-end-with-exclamation
"Used to ensure defn and defmacro in test namespace to have name ending with `!` if it's non-thread-safe.
A function or a macro can be defined as 'not thread safe' when their funciton name ends with a `!`.
Only used in tests to identify thread-safe/non-thread-safe test helpers. See #37126"
[{:keys [node cljc lang]}]
(when (or (not cljc)
(= lang :clj))
(non-thread-safe-form-should-end-with-exclamation* node))
{:node node})
(comment
(require '[clj-kondo.core :as clj-kondo])
(def form (str '(defmacro a
[x]
`(fun-call x))))
(def form "(defmacro a
[x]
`(some! ~x))")
(def form "(defun f
[x]
(let [g! (fn [] 1)]
(g!)))")
(str (hooks/parse-string form))
(hooks/sexpr (hooks/parse-string form))
(binding [hooks/*reload* true]
(-> form
(with-in-str (clj-kondo/run! {:lint ["-"]}))
:findings))
(do (non-thread-safe-form-should-end-with-exclamation* (hooks/parse-string form)) nil))

View File

@@ -1,20 +1,143 @@
(ns hooks.clojure.test
(:require [clj-kondo.hooks-api :as hooks]))
(:require [clj-kondo.hooks-api :as hooks]
[clojure.string :as str]))
(def disallowed-parallel-forms
'#{with-redefs
(def ^:private disallowed-parallel-forms
"Things you should not be allowed to use inside parallel tests. Besides these, anything ending in `!` not whitelisted
in [[allowed-parallel-forms]] is not allowed."
'#{clojure.core/alter-var-root
clojure.core/with-redefs
clojure.core/with-redefs-fn
metabase-enterprise.sandbox.test-util/with-gtaps
metabase-enterprise.sandbox.test-util/with-gtaps-for-user
metabase-enterprise.sandbox.test-util/with-user-attributes
metabase-enterprise.test/with-gtaps
metabase-enterprise.test/with-gtaps-for-user
metabase-enterprise.test/with-user-attributes
metabase.actions.test-util/with-actions
metabase.actions.test-util/with-actions-disabled
metabase.actions.test-util/with-actions-enabled
metabase.actions.test-util/with-actions-test-data
metabase.actions.test-util/with-actions-test-data-and-actions-enabled
metabase.actions.test-util/with-actions-test-data-tables
metabase.email-test/with-expected-messages
metabase.email-test/with-fake-inbox
metabase.test.data.users/with-group
metabase.test.data.users/with-group-for-user
metabase.test.persistence/with-persistence-enabled
metabase.test.util.log/with-log-level
metabase.test.util.log/with-log-messages-for-level
metabase.test.util.misc/with-single-admin-user
metabase.test.util.timezone/with-system-timezone-id
metabase.test.util/with-all-users-permission
metabase.test.util/with-column-remappings
metabase.test.util/with-discarded-collections-perms-changes
metabase.test.util/with-env-keys-renamed-by
metabase.test.util/with-locale
metabase.test.util/with-non-admin-groups-no-root-collection-for-namespace-perms
metabase.test.util/with-non-admin-groups-no-root-collection-perms
metabase.test.util/with-temp-env-var-value
metabase.test.util/with-temp-vals-in-db
metabase.test.util/with-temporary-raw-setting-values
metabase.test.util/with-temporary-setting-values
metabase.test.util/with-user-in-groups
metabase.test/with-actions
metabase.test/with-actions-disabled
metabase.test/with-actions-enabled
metabase.test/with-actions-test-data
metabase.test/with-actions-test-data-and-actions-enabled
metabase.test/with-actions-test-data-tables
metabase.test/with-all-users-permission
metabase.test/with-column-remappings
metabase.test/with-discarded-collections-perms-changes
metabase.test/with-env-keys-renamed-by
metabase.test/with-expected-messages
metabase.test/with-fake-inbox
metabase.test/with-group
metabase.test/with-group-for-user
metabase.test/with-locale
metabase.test/with-log-level
metabase.test/with-log-messages-for-level
metabase.test/with-non-admin-groups-no-root-collection-for-namespace-perms
metabase.test/with-non-admin-groups-no-root-collection-perms
metabase.test/with-persistence-enabled
metabase.test/with-single-admin-user
metabase.test/with-system-timezone-id
metabase.test/with-temp-env-var-value
metabase.test/with-temp-vals-in-db
metabase.test/with-temporary-raw-setting-values
metabase.test/with-temporary-setting-values
mt/with-temporary-setting-values})
metabase.test/with-user-in-groups})
;;; TODO -- we should disallow `metabase.test/user-http-request` with any method other than `:get`
(def ^:private allowed-parallel-forms
"These fns are destructive, but are probably fine inside ^:parallel tests because it usually means you're doing
something to an atom or something like that."
'#{clojure.core/assoc!
clojure.core/compare-and-set!
clojure.core/conj!
clojure.core/disj!
clojure.core/dissoc!
clojure.core/persistent!
clojure.core/pop!
clojure.core/reset!
clojure.core/reset-vals!
clojure.core/run!
clojure.core/swap!
clojure.core/swap-vals!
clojure.core/volatile!
clojure.core/vreset!
clojure.core/vswap!
clojure.core.async/<!
clojure.core.async/<!!
clojure.core.async/>!
clojure.core.async/>!!
clojure.core.async/alt!
clojure.core.async/alt!!
clojure.core.async/alts!
clojure.core.async/alts!!
clojure.core.async/close!
clojure.core.async/ioc-alts!
clojure.core.async/offer!
clojure.core.async/onto-chan!
clojure.core.async/onto-chan!!
clojure.core.async/poll!
clojure.core.async/put!
clojure.core.async/take!
clojure.core.async/to-chan!
clojure.core.async/to-chan!!
metabase.driver.sql-jdbc.execute/execute-prepared-statement!
metabase.query-processor/process-query-and-save-execution!
metabase.query-processor/process-query-and-save-with-max-results-constraints!
metabase.query-processor.store/store-database!})
(defn- node->qualified-symbol [node]
(try
(when (hooks/token-node? node)
(let [sexpr (hooks/sexpr node)]
(when (symbol? sexpr)
(when-let [resolved (hooks/resolve {:name sexpr})]
(symbol (name (:ns resolved)) (name (:name resolved)))))))
;; some symbols like `*count/Integer` aren't resolvable.
(catch Exception _
nil)))
(defn- warn-about-disallowed-parallel-forms [form]
(letfn [(f [form]
(when-let [sexpr (when (hooks/token-node? form)
(hooks/sexpr form))]
(when (disallowed-parallel-forms sexpr)
(hooks/reg-finding! (assoc (meta form)
:message (format "%s is not allowed inside a ^:parallel test" sexpr)
:type :metabase/validate-deftest)))))
(letfn [(error! [form message]
(hooks/reg-finding! (assoc (meta form)
:message message
:type :metabase/validate-deftest)))
(f [form]
(when-let [qualified-symbol (node->qualified-symbol form)]
(cond
(disallowed-parallel-forms qualified-symbol)
(error! form (format "%s is not allowed inside a ^:parallel test or test fixture" qualified-symbol))
(and (not (allowed-parallel-forms qualified-symbol))
(str/ends-with? (name qualified-symbol) "!"))
(error! form (format "destructive functions like %s are not allowed inside a ^:parallel test or test fixture. If this should be allowed, add it to the whitelist in .clj-kondo/hooks/clojure/test.clj"
qualified-symbol)))))
(walk [form]
(f form)
(doseq [child (:children form)]
@@ -53,12 +176,28 @@
(doseq [form body]
(warn-about-disallowed-parallel-forms form)))))
(def ^:private number-of-lines-for-a-test-to-be-considered-horrifically-long
200)
(defn- deftest-check-not-horrifically-long
[node]
(let [{:keys [row end-row]} (meta node)]
(when (and row end-row)
(let [num-lines (- end-row row)]
(when (>= num-lines number-of-lines-for-a-test-to-be-considered-horrifically-long)
(hooks/reg-finding! (assoc (meta node)
:message (str (format "This test is horrifically long, it's %d lines! 😱 " num-lines)
"Do you really want to try to debug it if it fails? 💀 "
"Split it up into smaller tests! 🥰")
:type :metabase/i-like-making-cams-eyes-bleed-with-horrifically-long-tests)))))))
(defn deftest [{:keys [node cljc lang]}]
;; run [[deftest-check-parallel]] only once... if this is a `.cljc` file only run it for the `:clj` analysis, no point
;; in running it twice.
(when (or (not cljc)
(= lang :clj))
(deftest-check-parallel node))
(deftest-check-not-horrifically-long node)
{:node node})
;;; this is a hacky way to determine whether these namespaces are required in the `ns` form or not... basically `:ns`
@@ -95,7 +234,20 @@
nil)))))))
(defn- warn-about-schema= [{[_is assertion-node] :children, :as _is-node}]
(let [{[assertion-symb-node] :children} assertion-node]
(when (and (hooks/token-node? assertion-symb-node)
(= (hooks/sexpr assertion-symb-node) 'schema=))
(hooks/reg-finding! (assoc (meta assertion-symb-node)
:message "Use =? or malli= instead of schema="
:type :metabase/warn-about-schema=)))))
(defn is [{:keys [node lang]}]
(when (= lang :cljs)
(warn-about-missing-test-expr-requires-in-cljs node))
(warn-about-schema= node)
{:node node})
(defn use-fixtures [{:keys [node]}]
(warn-about-disallowed-parallel-forms node)
{:node node})

View File

@@ -0,0 +1,28 @@
(ns hooks.metabase.api.automagic-dashboards-test
(:require [clj-kondo.hooks-api :as hooks]))
(comment
(def input (hooks/parse-string
"(with-indexed-model [{:keys [model model-index model-index-value]}
{:query :some-query}]
:foo :bar :body)"))
(println (hooks/sexpr input))
(let [f (load-file ".clj-kondo/hooks/metabase/api/automagic_dashboards_test.clj")]
(f {:node input})))
(defn with-indexed-model
[{node :node}]
(let [[_macro-call binding-and-query-info & body] (:children node)
[binding query-info] (:children binding-and-query-info)
node* (hooks/list-node
[(hooks/token-node 'do-with-testing-model)
query-info
(hooks/list-node
(list* (hooks/token-node 'fn)
(hooks/vector-node [binding])
body))])]
#_(println (hooks/sexpr node*))
{:node node*}))

View File

@@ -8,7 +8,7 @@
(hooks/token-node `let)
(hooks/vector-node
[binding (hooks/list-node (list (hooks/token-node `fn)
(hooks/vector-node [])))])
(hooks/vector-node [(hooks/token-node '&) (hooks/token-node '_args)])))])
migration-range
body))]
{:node node*}))

View File

@@ -0,0 +1,12 @@
(ns hooks.metabase.lib.test-util.macros
(:require [clj-kondo.hooks-api :as hooks]))
(defn with-testing-against-standard-queries [{{[_ & args] :children} :node}]
(let [[query-sym & body] args
node* (hooks/list-node
(list*
(hooks/token-node 'let)
(hooks/vector-node
[query-sym (hooks/token-node 'nil)])
body))]
{:node node*}))

View File

@@ -3,6 +3,208 @@
[clj-kondo.hooks-api :as hooks]
[hooks.common :as common]))
(def ^:private ignored-implicit-export?
'#{active-users-count
admin-email
analytics-uuid
anon-tracking-enabled
api-key
attachment-table-row-limit
audit-max-retention-days
bcc-enabled?
breakout-bin-width
check-for-updates
cloud-gateway-ips
config-from-file-sync-databases
custom-homepage
custom-homepage-dashboard
database-enable-actions
deprecation-notice-version
dismissed-custom-dashboard-toast
email-configured?
email-from-address
email-from-name
email-reply-to
email-smtp-host
email-smtp-password
email-smtp-port
email-smtp-security
email-smtp-username
embedding-app-origin
embedding-secret-key
enable-password-login
enable-public-sharing
enable-query-caching
engines
enum-cardinality-threshold
follow-up-email-sent
ga-code
ga-enabled
google-auth-auto-create-accounts-domain
google-auth-client-id
google-auth-configured
google-auth-enabled
has-sample-database?
has-user-setup
help-link
help-link-custom-destination
instance-creation
is-hosted?
is-metabot-enabled
jdbc-data-warehouse-max-connection-pool-size
jdbc-data-warehouse-unreturned-connection-timeout-seconds
jwt-attribute-email
jwt-attribute-firstname
jwt-attribute-groups
jwt-attribute-lastname
jwt-configured
jwt-enabled
jwt-group-mappings
jwt-group-sync
jwt-identity-provider-uri
jwt-user-provisioning-enabled?
jwt-shared-secret
last-acknowledged-version
ldap-attribute-email
ldap-attribute-firstname
ldap-attribute-lastname
ldap-bind-dn
ldap-configured?
ldap-enabled
ldap-group-base
ldap-group-mappings
ldap-group-membership-filter
ldap-group-sync
ldap-host
ldap-password
ldap-port
ldap-user-provisioning-enabled?
ldap-security
ldap-sync-user-attributes
ldap-sync-user-attributes-blacklist
ldap-user-base
ldap-user-filter
load-analytics-content
map-tile-server-url
metabot-default-embedding-model
metabot-feedback-url
metabot-get-prompt-templates-url
metabot-prompt-generator-token-limit
multi-setting-read-only
notification-link-base-url
num-metabot-choices
openai-api-key
openai-available-models
openai-model
openai-organization
other-sso-enabled?
password-complexity
persist-models-enabled
persisted-model-refresh-cron-schedule
premium-embedding-token
prometheus-server-port
query-caching-max-kb
query-caching-max-ttl
query-caching-min-ttl
query-caching-ttl-ratio
redirect-all-requests-to-https
reset-token-ttl-hours
retired-setting
retry-initial-interval
retry-max-attempts
retry-max-interval-millis
retry-multiplier
retry-randomization-factor
saml-application-name
saml-attribute-email
saml-attribute-firstname
saml-attribute-group
saml-attribute-lastname
saml-configured
saml-enabled
saml-group-mappings
saml-group-sync
saml-identity-provider-certificate
saml-identity-provider-issuer
saml-identity-provider-uri
saml-keystore-alias
saml-keystore-password
saml-keystore-path
saml-user-provisioning-enabled?
send-email-on-first-login-from-new-device
send-new-sso-user-admin-email?
session-cookie-samesite
session-cookies
session-timeout
setup-token
show-database-syncing-modal
show-metabase-links
site-url
site-uuid
site-uuid-for-premium-features-token-checks
site-uuid-for-unsubscribing-url
site-uuid-for-version-info-fetching
slack-app-token
slack-cached-channels-and-usernames
slack-channels-and-usernames-last-updated
slack-files-channel
slack-token
slack-token-valid?
snowplow-available
snowplow-enabled
snowplow-url
sql-jdbc-fetch-size
ssh-heartbeat-interval-sec
ssl-certificate-public-key
startup-time-millis
token-features
token-status
toucan-name
uncached-setting
uploads-table-prefix
user-visibility
version
version-info
version-info-last-checked})
(defn- defsetting-lint [node setting-name docstring options-list]
(let [anon-binding (common/with-macro-meta (hooks/token-node '_) node)
;; (defn my-setting [] ...)
getter-node (-> (list
(hooks/token-node 'defn)
setting-name
(hooks/string-node "Docstring.")
(hooks/vector-node []))
hooks/list-node
(with-meta (meta node)))
;; (defn my-setting! [_x] ...)
setter-node (-> (list
(hooks/token-node 'defn)
(with-meta
(hooks/token-node (symbol (str (hooks/sexpr setting-name) \!)))
(meta setting-name))
(hooks/string-node "Docstring.")
(hooks/vector-node [(hooks/token-node '_value-or-nil)]))
hooks/list-node
(with-meta (update (meta node) :clj-kondo/ignore #(hooks/vector-node (cons :clojure-lsp/unused-public-var (:children %))))))]
(when (nil? (second (drop-while (comp not #{[:k :export?]} first) options-list)))
(when-not (contains? ignored-implicit-export? (:value setting-name))
(hooks/reg-finding! (assoc (meta node)
:message "Setting definition must provide an explicit value for :export? indicating whether the setting should be exported or not with serialization."
:type :metabase/defsetting-must-specify-export))))
{:node (-> (list
(hooks/token-node 'let)
;; include description and the options map so they can get validated as well.
(hooks/vector-node
[anon-binding docstring
anon-binding (hooks/map-node options-list)])
getter-node
setter-node)
hooks/list-node
(with-meta (meta node)))}))
(defn defsetting
"Rewrite a [[metabase.models.defsetting]] form like
@@ -11,54 +213,45 @@
as
(let [_ \"Description\"
_ :type
_ :boolean]
_ {:type :boolean}]
(defn my-setting \"Docstring.\" [])
(defn my-setting! \"Docstring.\" [_value-or-nil]))
for linting purposes."
[{:keys [node]}]
(let [[setting-name & args] (rest (:children node))
;; (defn my-setting [] ...)
getter-node (-> (list
(hooks/token-node 'defn)
setting-name
(hooks/string-node "Docstring.")
(hooks/vector-node []))
hooks/list-node
(with-meta (meta node)))
;; (defn my-setting! [_x] ...)
setter-node (-> (list
(hooks/token-node 'defn)
(with-meta
(hooks/token-node (symbol (str (hooks/sexpr setting-name) \!)))
(meta setting-name))
(hooks/string-node "Docstring.")
(hooks/vector-node [(hooks/token-node '_value-or-nil)]))
hooks/list-node
(with-meta (update (meta node) :clj-kondo/ignore #(hooks/vector-node (cons :clojure-lsp/unused-public-var (:children %))))))]
{:node (-> (list
(hooks/token-node 'let)
;; include description and the options map so they can get validated as well.
(hooks/vector-node (vec (interleave (repeat (common/with-macro-meta (hooks/token-node '_) node))
args)))
getter-node
setter-node)
hooks/list-node
(with-meta (meta node)))}))
(let [[setting-name docstring & options] (rest (:children node))]
(defsetting-lint node setting-name docstring options)))
(defn define-multi-setting
"Rewrite a [[metabase.models.define-multi-setting]] form like
(defsetting my-setting \"Description\" :key :type :boolean)
as
(let [_ \"Description\"
_ {:type :boolean, :multi-thunk :key}]
(defn my-setting \"Docstring.\" [])
(defn my-setting! \"Docstring.\" [_value-or-nil]))
for linting purposes."
[{:keys [node]}]
(let [[setting-name docstring thunk & options] (rest (:children node))]
(defsetting-lint node setting-name docstring (concat options [(hooks/token-node :multi-thunk) thunk]))))
(comment
(defn- defsetting* [form]
(hooks/sexpr
(:node
(defsetting
{:node
(hooks/parse-string
(with-out-str
(clojure.pprint/pprint
form)))}))))
(:node
(defsetting
{:node
(hooks/parse-string
(with-out-str
#_{:clj-kondo/ignore [:unresolved-namespace]}
(clojure.pprint/pprint
form)))}))))
(defn- x []
(defn x []
(defsetting*
'(defsetting active-users-count
(deferred-tru "Cached number of active users. Refresh every 5 minutes.")

View File

@@ -0,0 +1,20 @@
(ns hooks.metabase.util.malli.registry
(:refer-clojure :exclude [def])
(:require
[clj-kondo.hooks-api :as api]))
(defn def
"Register the schema keyword so LSP can jump to it."
[x]
(letfn [(update-def-keyword [k]
(api/reg-keyword! k 'metabase.util.malli.registry/def))
(update-children [[_def k :as children]]
(if (api/keyword-node? k)
(update (vec children) 1 update-def-keyword)
children))
(update-node [node]
(if (api/list-node? node)
(-> (api/list-node (update-children (:children node)))
(with-meta (meta node)))
node))]
(update x :node update-node)))

View File

@@ -1,11 +1,11 @@
(ns macros.metabase.test.util)
(defmacro with-temp-env-var-value [bindings & body]
(defmacro with-temp-env-var-value! [bindings & body]
`((constantly nil)
~@(map second (partition-all 2 bindings))
~@body))
(defmacro with-temporary-raw-setting-values [bindings & body]
`((constantly nil)
~@(map second (partition-all 2 bindings))
~@(map second (partition-all 2 bindings))
~@body))

View File

@@ -1,14 +0,0 @@
{:config-paths ["macros"]
:lint-as
{}
:hooks
{:analyze-call
{methodical.core/defmethod hooks.methodical.macros/defmethod
methodical.core/defmulti hooks.methodical.macros/defmulti
methodical.macros/defmethod hooks.methodical.macros/defmethod
methodical.macros/defmulti hooks.methodical.macros/defmulti}
:macroexpand
{methodical.impl.combo.operator/defoperator macros.methodical.impl.combo.operator/defoperator}}}

View File

@@ -1,68 +0,0 @@
(ns hooks.methodical.core
(:require [clj-kondo.hooks-api :as hooks]))
(defn add-next-method [fn-tail]
(if (hooks/vector-node? (first fn-tail))
(let [[args & body] fn-tail]
(list*
(-> (hooks/vector-node
(cons (hooks/token-node 'next-method)
(:children args)))
(with-meta (meta args)))
;; so Kondo stops complaining about it being unused.
(hooks/token-node 'next-method)
body))
(for [list-node fn-tail]
(hooks/list-node (add-next-method (:children list-node))))))
(defn defmethod
[{{[_ multimethod & [first-arg :as args]] :children, :as node} :node}]
#_(clojure.pprint/pprint (hooks/sexpr node))
(let [[aux-qualifier dispatch-value & fn-tail] (if (#{:before :after :around} (hooks/sexpr first-arg))
(cons (hooks/sexpr first-arg) (rest args))
(cons nil args))
fn-tail (if (contains? #{:around nil} aux-qualifier)
(add-next-method fn-tail)
fn-tail)
result (hooks/list-node
(list* (hooks/token-node 'clojure.core/defmethod)
multimethod
dispatch-value
fn-tail))]
#_(println "=>")
#_(clojure.pprint/pprint (hooks/sexpr result))
{:node result}))
(defn defmulti
[{{[_ multimethod-name & args] :children, :as node} :node}]
#_(clojure.pprint/pprint (hooks/sexpr node))
(let [[docstring & args] (if (hooks/string-node? (first args))
args
(cons nil args))
[attribute-map & args] (if (hooks/map-node? (first args))
args
(cons nil args))
;; if there wasn't a positional dispatch function arg passed just use (constantly nil) so Kondo won't complain
[dispatch-fn & kv-options] (if (odd? (count args))
args
(cons (hooks/list-node
(list
(hooks/token-node 'clojure.core/constantly)
(hooks/token-node 'nil)))
args))]
(let [defmulti-form (hooks/list-node
(filter
some?
[(hooks/token-node 'clojure.core/defmulti)
multimethod-name
docstring
attribute-map
dispatch-fn]))
result (hooks/list-node
(list*
(hooks/token-node 'do)
defmulti-form
kv-options))]
#_(println "=>")
#_(clojure.pprint/pprint (hooks/sexpr result))
{:node result})))

View File

@@ -1,185 +0,0 @@
(ns hooks.methodical.macros
(:refer-clojure :exclude [defmulti defmethod])
(:require
[clj-kondo.hooks-api :as hooks]))
;;; The code below is basically simulating the spec for parsing defmethod args without using spec. It uses a basic
;;; backtracking algorithm to achieve a similar result. Parsing defmethod args is kinda complicated.
;;;
;;; Unfortunately this is hardcoded to `:before`, `:after`, and `:around` as the only allowed qualifiers for now... at
;;; some point in the future we'll have to figure out how to fix this and support other qualifiers too.
(defn- bindings-vector? [x]
(and (hooks/vector-node? x)
(every? (some-fn hooks/token-node?
hooks/map-node?
hooks/vector-node?)
(:children x))))
(defn- single-arity-fn-tail? [args]
(bindings-vector? (first args)))
(defn- n-arity-fn-tail? [args]
(and (seq args)
(every? (fn [x]
(and (hooks/list-node? x)
(single-arity-fn-tail? (:children x))))
args)))
(defn- fn-tail? [args]
(or (single-arity-fn-tail? args)
(n-arity-fn-tail? args)))
(defn- qualifier? [x]
(and (hooks/keyword-node? x)
(#{:before :after :around} (hooks/sexpr x))))
(defn- dispatch-value?
"A dispatch value can be anything except for qualifier keyword or a list that looks like part of a n-arity function tail
e.g. `([x] x)`."
[x]
(and (not (qualifier? x))
(or (not (hooks/list-node? x))
(not (single-arity-fn-tail? (:children x))))))
(defonce ^:private backtrack (Exception.))
(defn- parse-defmethod-args
([unparsed]
(let [parses (atom [])]
(try
(parse-defmethod-args parses {} unparsed)
(catch Exception _
(when (zero? (count @parses))
(throw (ex-info (format "Unable to parse defmethod args: %s" (pr-str (mapv hooks/sexpr unparsed)))
{:args (mapv hooks/sexpr unparsed)})))
(when (> (count @parses) 1)
(throw (ex-info (format "Ambiguous defmethod args: %s" (pr-str (mapv hooks/sexpr unparsed)))
{:args (mapv hooks/sexpr unparsed)
:parses @parses})))
(first @parses)))))
([parses parsed unparsed]
(cond
(and (not (contains? parsed :qualifier))
(qualifier? (first unparsed)))
(try
(parse-defmethod-args parses (assoc parsed :qualifier (first unparsed)) (rest unparsed))
(catch Exception _
(parse-defmethod-args parses (assoc parsed :qualifier nil) unparsed)))
(and (not (contains? parsed :dispatch-value))
(dispatch-value? (first unparsed)))
(parse-defmethod-args parses (assoc parsed :dispatch-value (first unparsed)) (rest unparsed))
(not (contains? parsed :dispatch-value))
(throw backtrack)
(and (not (contains? parsed :unique-key))
(:qualifier parsed) ; can only have unique keys for aux methods
(not (hooks/string-node? (first unparsed)))
(not (hooks/list-node? (first unparsed)))
(not (hooks/vector-node? (first unparsed))))
(try
(parse-defmethod-args parses (assoc parsed :unique-key (first unparsed)) (rest unparsed))
(catch Exception _
(parse-defmethod-args parses (assoc parsed :unique-key nil) unparsed)))
(and (not (contains? parsed :docstring))
(hooks/string-node? (first unparsed)))
(try
(parse-defmethod-args parses (assoc parsed :docstring (first unparsed)) (rest unparsed))
(catch Exception _
(parse-defmethod-args parses (assoc parsed :docstring nil) unparsed)))
(fn-tail? unparsed)
(do
(swap! parses conj (assoc parsed :fn-tail unparsed))
(throw backtrack))
:else
(throw backtrack))))
(defn defmethod
[{{[_ multimethod & args] :children, :as node} :node}]
(#_println)
#_(clojure.pprint/pprint (hooks/sexpr node))
(let [parsed (parse-defmethod-args args)]
#_(doseq [[k v] parsed]
(println \newline k '=> (pr-str (some-> v hooks/sexpr))))
(let [fn-tail (:fn-tail parsed)
other-stuff (dissoc parsed :fn-tail)
result (hooks/list-node
(concat
[(hooks/token-node 'do)
multimethod]
(filter some? (vals other-stuff))
[(-> (hooks/list-node
(list*
(hooks/token-node 'fn)
(hooks/token-node (if (contains? #{nil :around} (some-> (:qualifier parsed) hooks/sexpr))
'next-method
'__FN__NAME__THAT__YOU__CANNOT__REFER__TO__))
fn-tail))
(vary-meta update :clj-kondo/ignore conj :redundant-fn-wrapper))]))]
#_(println "=>")
#_(clojure.pprint/pprint (hooks/sexpr result))
{:node result})))
;;; this stuff is for debugging things to make sure we didn't do something dumb
(comment
(defn defmethod* [form]
(binding [*print-meta* true]
(clojure.pprint/pprint
(hooks/sexpr (:node (defmethod {:node (hooks/parse-string (str form))}))))))
(defmethod* '(defmethod mf :second [& _] 2))
(defmethod* '(m/defmethod multi-arity :k
([x]
{:x x})
([x y]
{:x x, :y y})))
(defmethod* '(m/defmethod mf1 :docstring
"Docstring"
[_x]))
(defmethod* '(m/defmethod mf1 :around :dispatch-value
"Docstring"
[x]
(next-method x))))
(defn defmulti
[{{[_ multimethod-name & args] :children, :as node} :node}]
#_(clojure.pprint/pprint (hooks/sexpr node))
(let [[docstring & args] (if (hooks/string-node? (first args))
args
(cons nil args))
[attribute-map & args] (if (hooks/map-node? (first args))
args
(cons nil args))
;; if there wasn't a positional dispatch function arg passed just use (constantly nil) so Kondo won't complain
[dispatch-fn & kv-options] (if (odd? (count args))
args
(cons (hooks/list-node
(list
(hooks/token-node 'clojure.core/constantly)
(hooks/token-node 'nil)))
args))]
(let [defmulti-form (hooks/list-node
(filter
some?
[(hooks/token-node 'clojure.core/defmulti)
multimethod-name
docstring
attribute-map
dispatch-fn]))
result (hooks/list-node
(list*
(hooks/token-node 'do)
defmulti-form
kv-options))]
#_(println "=>")
#_(clojure.pprint/pprint (hooks/sexpr result))
{:node result})))

View File

@@ -1,7 +0,0 @@
(ns macros.methodical.impl.combo.operator)
;; not exactly what actually happens but this is close enough to be able to lint it
(defmacro defoperator [operator-name [methods-binding invoke-binding] & body]
`(defmethod methodical.impl.combo.operator/operator ~(keyword operator-name)
[~methods-binding ~invoke-binding]
~@body))

View File

@@ -1,2 +0,0 @@
{:lint-as {malli.experimental/defn schema.core/defn}
:linters {:unresolved-symbol {:exclude [(malli.core/=>)]}}}

View File

@@ -1,62 +0,0 @@
{:lint-as {potemkin.collections/compile-if clojure.core/if
potemkin.collections/reify-map-type clojure.core/reify
potemkin.collections/def-map-type clj-kondo.lint-as/def-catch-all
potemkin.collections/def-derived-map clj-kondo.lint-as/def-catch-all
potemkin.types/reify+ clojure.core/reify
potemkin.types/defprotocol+ clojure.core/defprotocol
potemkin.types/deftype+ clojure.core/deftype
potemkin.types/defrecord+ clojure.core/defrecord
potemkin.types/definterface+ clojure.core/defprotocol
potemkin.types/extend-protocol+ clojure.core/extend-protocol
potemkin.types/def-abstract-type clj-kondo.lint-as/def-catch-all
potemkin.utils/doit clojure.core/doseq
potemkin.utils/doary clojure.core/doseq
potemkin.utils/condp-case clojure.core/condp
potemkin.utils/fast-bound-fn clojure.core/bound-fn
potemkin.walk/prewalk clojure.walk/prewalk
potemkin.walk/postwalk clojure.walk/postwalk
potemkin.walk/walk clojure.walk/walk
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; top-level from import-vars
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Have hooks
;;potemkin/import-fn potemkin.namespaces/import-fn
;;potemkin/import-macro potemkin.namespaces/import-macro
;;potemkin/import-def potemkin.namespaces/import-def
;; Internal, not transitive
;;potemkin/unify-gensyms potemkin.macros/unify-gensyms
;;potemkin/normalize-gensyms potemkin.macros/normalize-gensyms
;;potemkin/equivalent? potemkin.macros/equivalent?
potemkin/condp-case clojure.core/condp
potemkin/doit potemkin.utils/doit
potemkin/doary potemkin.utils/doary
potemkin/def-abstract-type clj-kondo.lint-as/def-catch-all
potemkin/reify+ clojure.core/reify
potemkin/defprotocol+ clojure.core/defprotocol
potemkin/deftype+ clojure.core/deftype
potemkin/defrecord+ clojure.core/defrecord
potemkin/definterface+ clojure.core/defprotocol
potemkin/extend-protocol+ clojure.core/extend-protocol
potemkin/reify-map-type clojure.core/reify
potemkin/def-derived-map clj-kondo.lint-as/def-catch-all
potemkin/def-map-type clj-kondo.lint-as/def-catch-all}
;; leave import-vars alone, kondo special-cases it
:hooks {:macroexpand {#_#_potemkin.namespaces/import-vars potemkin.namespaces/import-vars
potemkin.namespaces/import-fn potemkin.namespaces/import-fn
potemkin.namespaces/import-macro potemkin.namespaces/import-macro
potemkin.namespaces/import-def potemkin.namespaces/import-def
#_#_potemkin/import-vars potemkin.namespaces/import-vars
potemkin/import-fn potemkin.namespaces/import-fn
potemkin/import-macro potemkin.namespaces/import-macro
potemkin/import-def potemkin.namespaces/import-def}}}

View File

@@ -1,56 +0,0 @@
(ns potemkin.namespaces
(:require [clj-kondo.hooks-api :as api]))
(defn import-macro*
([sym]
`(def ~(-> sym name symbol) ~sym))
([sym name]
`(def ~name ~sym)))
(defmacro import-fn
([sym]
(import-macro* sym))
([sym name]
(import-macro* sym name)))
(defmacro import-macro
([sym]
(import-macro* sym))
([sym name]
(import-macro* sym name)))
(defmacro import-def
([sym]
(import-macro* sym))
([sym name]
(import-macro* sym name)))
#_
(defmacro import-vars
"Imports a list of vars from other namespaces."
[& syms]
(let [unravel (fn unravel [x]
(if (sequential? x)
(->> x
rest
(mapcat unravel)
(map
#(symbol
(str (first x)
(when-let [n (namespace %)]
(str "." n)))
(name %))))
[x]))
syms (mapcat unravel syms)
result `(do
~@(map
(fn [sym]
(let [vr (resolve sym)
m (meta vr)]
(cond
(nil? vr) `(throw (ex-info (format "`%s` does not exist" '~sym) {}))
(:macro m) `(def ~(-> sym name symbol) ~sym)
(:arglists m) `(def ~(-> sym name symbol) ~sym)
:else `(def ~(-> sym name symbol) ~sym))))
syms))]
result))

View File

@@ -1 +0,0 @@
{:lint-as {schema.test/deftest clojure.test/deftest}}

View File

@@ -1,10 +0,0 @@
(ns test
(:require [metabase.query-processor.streaming :as streaming]
[toucan.models :as models]))
(models/defmodel Card :foo)
(map->Card {:foo 1})
(map->CardInstance {:foo 1})
(streaming/streaming-response [x 1 (inc x)])

31
.cljfmt.edn Normal file
View File

@@ -0,0 +1,31 @@
;; https://github.com/weavejester/cljfmt/blob/master/cljfmt/resources/cljfmt/indents/clojure.clj
{:extra-indents
{auto-parse [[:inner 0]]
cond-> [[:inner 0]]
check [[:inner 0]]
deferred-tru [[:inner 0]]
defprotocol+ [[:block 1] [:inner 1]]
potemkin/defprotocol+ [[:block 1] [:inner 1]]
let-404 [[:block 1]]
metabase.mbql.util/match-one [[:inner 0]]
merge-with [[:inner 0]]
metabase.test/dataset [[:inner 0]]
metabase.test/formatted-rows [[:inner 0]]
metabase.test/mbql-query [[:inner 0]]
metabase.test/test-drivers [[:inner 0]]
metabase.test/with-temporary-setting-values [[:block 1]]
;; If we just treat these as functions we can ignore this, despite some files not being consistent
;metabase.models.permissions/set-has-full-permissions-for-set? [[:inner 0]]
;metabase.models.permissions/set-has-full-permissions? [[:inner 0]]
;metabase.models.permissions/set-has-partial-permissions? [[:inner 0]]
metabase.models.permissions/set-has-partial-permissions-for-set? [[:inner 0]]
publish-event! [[:block 1]]
metabase.query-processor.streaming/streaming-response [[:inner 0]]
metabase.util/prog1 [[:inner 0]]
metabase.util/select-keys-when [[:inner 0]]
;; This supports a lot of existing formatting, but these are functions so the
;; existing formatting is probably wrong.
;toucan2.core/select [[:inner 0]]
;toucan2.core/update! [[:inner 0]]
}
:sort-ns-references? true}

View File

@@ -1,2 +0,0 @@
{metabase.api.collection/foo [[:inner 0]]
toucan.db/insert! [[:block 1]]}

View File

@@ -2,10 +2,10 @@ FROM mcr.microsoft.com/vscode/devcontainers/java:11
# Set up nodesource, install node, yarn, fontconfig for static viz, rlwrap for dev ergonomics
RUN ( curl -fsSL https://deb.nodesource.com/setup_14.x | bash ) \
RUN ( curl -fsSL https://deb.nodesource.com/setup_18.x | bash ) \
&& export DEBIAN_FRONTEND=noninteractive \
&& apt-key adv --refresh-keys --keyserver keyserver.ubuntu.com \
&& apt-get update && apt-get -y install --no-install-recommends nodejs yarn rlwrap fontconfig
# install Clojure
RUN curl https://download.clojure.org/install/linux-install-1.11.0.1100.sh | bash
RUN curl https://download.clojure.org/install/linux-install-1.11.1.1262.sh | bash

View File

@@ -6,6 +6,7 @@
;; prefer keeping source width about ~118, GitHub seems to cut off stuff at either 119 or 120 and it's nicer
;; to look at code in GH when you don't have to scroll back and forth
(fill-column . 118)
(whitespace-line-column . 118)
;; tell find-things-fast to always use this directory as project root regardless of presence of other
;; deps.edn files
(ftf-project-finders . (ftf-get-top-git-dir)))
@@ -81,14 +82,11 @@
(cider-clojure-cli-aliases . "dev:drivers:drivers-dev:ee:ee-dev:user")
(clojure-indent-style . always-align)
(cljr-favor-prefix-notation . nil)
(cljr-insert-newline-after-require . t)
(clojure-docstring-fill-column . 118)
(cider-preferred-build-tool . clojure-cli)
(cider-default-cljs-repl . shadow-select)
(cider-shadow-default-options . "node-repl"))
("shared"
(clojure-mode
(cider-preferred-build-tool . shadow-cljs)))
(cider-shadow-default-options . "app"))
("bin"
(clojure-mode

View File

@@ -1 +1,2 @@
frontend/src/cljs
frontend/src/cljs_release

View File

@@ -8,14 +8,30 @@
{
"vars": "all",
"args": "none",
"varsIgnorePattern": "^_.+",
"varsIgnorePattern": "^_",
"ignoreRestSiblings": true
}
],
"no-empty": [1, { "allowEmptyCatch": true }],
"no-restricted-imports": [
"error",
{
"paths": [
{
"name": "moment",
"message": "Moment is deprecated, please use dayjs"
},
{
"name": "moment-timezone",
"message": "Moment is deprecated, please use dayjs"
}
]
}
],
"curly": [1, "all"],
"eqeqeq": [1, "smart"],
"import/no-default-export": 2,
"import/no-named-as-default": 0,
"import/no-commonjs": 1,
"import/order": [
"error",
@@ -121,11 +137,16 @@
"plugin:react/jsx-runtime",
"plugin:react-hooks/recommended",
"plugin:import/errors",
"plugin:import/warnings"
"plugin:import/warnings",
"plugin:import/typescript"
],
"settings": {
"import/internal-regex": "^metabase/|^metabase-lib/",
"import/resolver": "webpack",
"import/resolver": {
"webpack": {
"typescript": true
}
},
"import/ignore": ["\\.css$"],
"react": {
"version": "detect"
@@ -137,6 +158,18 @@
}
},
"overrides": [
{
"files": ["*.js", "*.jsx", "*.ts", "*.tsx"],
"rules": {
"no-unconditional-metabase-links-render": "error"
}
},
{
"files": ["*.unit.spec.*", "frontend/src/metabase/admin/**/*"],
"rules": {
"no-unconditional-metabase-links-render": "off"
}
},
{
"extends": ["plugin:@typescript-eslint/recommended"],
"files": ["*.ts", "*.tsx"],
@@ -148,17 +181,18 @@
"@typescript-eslint/no-inferrable-types": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-this-alias": "off",
"no-unused-vars": "off",
"@typescript-eslint/consistent-type-imports": "error",
"@typescript-eslint/no-unused-vars": [
"error",
{
"vars": "all",
"args": "none",
"varsIgnorePattern": "^_.+",
"argsIgnorePattern": "^_",
"varsIgnorePattern": "^_",
"ignoreRestSiblings": true,
"destructuredArrayIgnorePattern": "^_"
}
]
],
// This was introduced in 6.0.0
"@typescript-eslint/no-unsafe-declaration-merging": "off"
}
},
{

3
.github/CODEOWNERS vendored Normal file
View File

@@ -0,0 +1,3 @@
src/metabase @camsaul
modules @camsaul
enterprise/backend @camsaul

View File

@@ -1,3 +1,6 @@
> [!IMPORTANT]
> If you are merging into master, please add either a `backport` or a `no-backport` label to this PR. You will not be able to merge until you do this step. Refer to the section [Do I need to backport this PR?](https://www.notion.so/metabase/Metabase-Branching-Strategy-6eb577d5f61142aa960a626d6bbdfeb3?pvs=4#89f80d6f17714a0198aeb66c0efd1b71) in the Metabase Branching Strategy document for more details.
> **Warning**
>
> If that is your first contribution to Metabase, please sign the [Contributor License Agreement](https://docs.google.com/a/metabase.com/forms/d/1oV38o7b9ONFSwuzwmERRMi9SYrhYeOrkbmNaq9pOJ_E/viewform) (unless it's a tiny documentation change). Also, if you're attempting to fix a translation issue, please submit your changes to our [POEditor project](https://poeditor.com/join/project/ynjQmwSsGh) instead of opening a PR.

View File

@@ -0,0 +1,66 @@
name: Build E2E Matrix
description: Build and output a custom matrix for E2E tests.
outputs:
matrix:
description: Parameterized matrix in JSON format
value: ${{ steps.matrix.outputs.result }}
runs:
using: "composite"
steps:
- uses: actions/github-script@v7
id: matrix
with:
script: | # js
const java = 11;
const defaultRunner = "ubuntu-22.04";
const beefierRunner = "buildjet-2vcpu-ubuntu-2204";
const defaultOptions = {
"java-version": java,
runner: defaultRunner,
edition: "ee",
context: "folder"
};
const testSets = [
["actions", {} ],
["admin", {} ],
["admin-2", {} ],
["binning", {} ],
["collections", {} ],
["custom-column", {} ],
["dashboard", {} ],
["dashboard-cards", {} ],
["dashboard-filters", {} ],
["embedding", {} ],
["filters", {} ],
["joins", {} ],
["models", {} ],
["native", {} ],
["native-filters", {} ],
["onboarding", {} ],
["organization", {} ],
["permissions", {} ],
["question", {} ],
["sharing", {} ],
["visualizations-charts", {} ],
["visualizations-tabular", {} ],
["oss-subset", { edition: 'oss', context: "special" } ],
["slow", { runner: beefierRunner, context: "special" } ],
["flaky", { runner: beefierRunner, context: "special" } ],
["mongo", { context: "qa-database" } ],
];
const config = testSets.map(([name, specialOptions]) => {
return {
...defaultOptions,
...specialOptions,
name,
}
});
const matrix = { include: config };
return matrix;

View File

@@ -0,0 +1,77 @@
name: Find and download uberjar for E2E tests
description: Download previously built artifact from one of the previous commits.
inputs:
edition:
description: Metabase edition.
required: true
runs:
using: "composite"
steps:
- name: Download previously stored uberjar
uses: actions/github-script@v7
with:
script: | # js
const fs = require('fs');
const execSync = require("child_process").execSync;
const getCommit = (ref = "HEAD") => {
const [commit] = execSync(`git rev-parse ${ref}`, { encoding: "utf8" }).split(
"\n",
);
return commit;
};
const baseConfig = {
owner: context.repo.owner,
repo: context.repo.repo,
};
async function getArtifact(commit, depth = 0) {
if (depth > 20) {
throw new Error("Couldn't find the artifact!");
}
const artifactName = `metabase-${{ inputs.edition }}-${commit}-uberjar`;
const {
data: { artifacts },
} = await github.rest.actions.listArtifactsForRepo({
...baseConfig,
name: artifactName,
per_page: 1,
});
const [artifact] = artifacts;
if (!artifact) {
const parentCommit = getCommit(`${commit}^`);
console.log(`Didn't find ${artifactName}.\n`);
console.log(`Switching to the parent commit: ${parentCommit}`);
return getArtifact(parentCommit, depth + 1);
} else {
return artifact;
}
}
const currentCommit = "${{ github.event.pull_request.head.sha || github.sha }}";
const { id } = await getArtifact(currentCommit);
const download = await github.rest.actions.downloadArtifact({
...baseConfig,
artifact_id: id,
archive_format: 'zip',
});
fs.writeFileSync(`${process.env.GITHUB_WORKSPACE}/mb.zip`, Buffer.from(download.data));
- name: Unzip Metabase artifact containing an uberjar
run: unzip mb.zip
shell: bash
- name: Get the version info
run: |
jar xf target/uberjar/metabase.jar version.properties
cat version.properties
mv version.properties resources/
shell: bash

View File

@@ -0,0 +1,87 @@
name: Prepare Docker containers
description: Prepare Docker containers for E2E tests.
inputs:
username:
description: DockerHub username
required: true
password:
description: DockerHub password/token
required: true
maildev:
description: Maildev
required: true
default: 'false'
openldap:
description: Maildev
required: true
default: 'false'
postgres:
description: Maildev
required: true
default: 'false'
mysql:
description: Maildev
required: true
default: 'false'
mongo:
description: Maildev
required: true
default: 'false'
runs:
using: "composite"
steps:
- name: Authenticate to prevent API rate limit
uses: docker/login-action@v3
with:
username: ${{ inputs.username }}
password: ${{ inputs.password }}
- name: Start Containers
run: |
Y='\033[33m'
G='\033[1;32m'
if ${{ inputs.maildev }}; then
echo -e "${Y}Starting maildev container..." &&
docker run -d -p 1080:1080 -p 1025:1025 maildev/maildev:2.0.5 &&
while ! nc -z localhost 1080; do sleep 1; done &&
while ! nc -z localhost 1025; do sleep 1; done &&
echo -e "${G}Maildev is up and running!"
fi
if ${{ inputs.openldap }}; then
echo -e "${Y}Starting openldap container..." &&
docker run -d -p 389:389 \
--env LDAP_ADMIN_PASSWORD=adminpass \
--env LDAP_USERS=user01@example.org,user02@example.org \
--env LDAP_PASSWORDS=123456,123465 \
--env LDAP_ROOT=dc=example,dc=org \
--env LDAP_PORT_NUMBER=389 \
bitnami/openldap:2.6.4 &&
while ! nc -z localhost 389; do sleep 1; done &&
echo -e "${G}Openldap is up and running!"
fi
if ${{ inputs.postgres }}; then
echo -e "${Y}Starting postgres container..." &&
docker run -d -p 5404:5432 -e TZ='US/Pacific' metabase/qa-databases:postgres-sample-12 &&
while ! nc -z localhost 5404; do sleep 1; done &&
echo -e "${G}Postgres is up and running!"
fi
if ${{ inputs.mysql }}; then
echo -e "${Y}Starting mysql container..." &&
docker run -d -p 3304:3306 -e TZ='US/Pacific' metabase/qa-databases:mysql-sample-8 &&
while ! nc -z localhost 3304; do sleep 1; done &&
echo -e "${G}MySQL is up and running!"
fi
if ${{ inputs.mongo }}; then
echo -e "${Y}Starting mongo container..." &&
docker run -d -p 27004:27017 metabase/qa-databases:mongo-sample-4.4 &&
while ! nc -z localhost 27004; do sleep 1; done &&
echo -e "${G}Mongo is up and running!"
fi
shell: bash

View File

@@ -7,7 +7,7 @@ outputs:
runs:
using: "composite"
steps:
- uses: actions/github-script@v6
- uses: actions/github-script@v7
id: get-latest-release-branch
with:
result-encoding: string

View File

@@ -9,7 +9,7 @@ inputs:
runs:
using: "composite"
steps:
- uses: actions/github-script@v6
- uses: actions/github-script@v7
id: get-latest-release-branch
with:
result-encoding: string
@@ -27,7 +27,7 @@ runs:
}
github.rest.issues.createComment({
issue_number: context.payload.number,
issue_number: context.payload.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body,

View File

@@ -15,7 +15,7 @@ runs:
using: "composite"
steps:
- name: Prepare JDK ${{ inputs.java-version }}
uses: actions/setup-java@v3
uses: actions/setup-java@v4
with:
java-version: ${{ inputs.java-version }}
distribution: 'temurin'
@@ -29,7 +29,7 @@ runs:
run: echo "Commit message includes [ci nocache]; dependencies will NOT be cached"
shell: bash
- name: Get M2 cache
uses: actions/cache@v3
uses: actions/cache@v4
if: ${{ !contains(github.event.head_commit.message, '[ci nocache]') }}
with:
path: |

View File

@@ -1,13 +1,19 @@
name: Prepare cypress environment
description: Cypress preparation steps
runs:
using: "composite"
steps:
- name: Install Replay.io browser
run: npx @replayio/cypress install
shell: bash
- name: Check to see if dependencies should be cached
if: ${{ contains(github.event.head_commit.message, '[ci nocache]') }}
run: echo "Commit message includes [ci nocache]; dependencies will NOT be cached"
shell: bash
- name: Get Cypress cache
uses: actions/cache@v3
uses: actions/cache@v4
if: ${{ !contains(github.event.head_commit.message, '[ci nocache]') }}
with:
path: ~/.cache/Cypress

View File

@@ -3,10 +3,9 @@ runs:
using: "composite"
steps:
- name: Prepare Node.js
uses: actions/setup-node@v3
uses: actions/setup-node@v4
with:
node-version-file: '.nvmrc'
cache: 'yarn'
node-version-file: ".nvmrc"
- name: Check to see if dependencies should be cached
if: ${{ contains(github.event.head_commit.message, '[ci nocache]') }}
run: |
@@ -14,13 +13,13 @@ runs:
yarn cache clean
shell: bash
- name: Get M2 cache
uses: actions/cache@v3
uses: actions/cache@v4
if: ${{ !contains(github.event.head_commit.message, '[ci nocache]') }}
with:
path: ~/.m2
key: ${{ runner.os }}-cljs-${{ hashFiles('**/shadow-cljs.edn') }}
- name: Get node_modules cache
uses: actions/cache@v3
uses: actions/cache@v4
if: ${{ !contains(github.event.head_commit.message, '[ci nocache]') }}
with:
path: node_modules

View File

@@ -1,4 +1,11 @@
name: Prepare Uberjar Artifact
description: Prepare and upload Metabase JAR as a GitHub artifact.
inputs:
name:
required: true
description: Artifact name
runs:
using: "composite"
steps:
@@ -9,9 +16,9 @@ runs:
run: sha256sum ./target/uberjar/metabase.jar > SHA256.sum
shell: bash
- name: Upload JARs as artifact
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
with:
name: metabase-${{ matrix.edition }}-uberjar
name: ${{ inputs.name }}
path: |
./target/uberjar/metabase.jar
./COMMIT-ID

View File

@@ -0,0 +1,54 @@
name: Upload Test Results to s3
description: Uploads test results files to s3
inputs:
input-path:
required: true
output-name:
required: true
default: test
aws-access-key-id:
required: true
aws-secret-access-key:
required: true
aws-region:
required: true
default: us-east-1
bucket:
required: true
trunk-api-token:
required: true
runs:
using: "composite"
steps:
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v4
with:
aws-access-key-id: ${{ inputs.aws-access-key-id }}
aws-secret-access-key: ${{ inputs.aws-secret-access-key }}
aws-region: ${{ inputs.aws-region }}
- name: zip test results
env:
INPUT_DIR: ${{ inputs.input-path }}
OUTPUT_FILE: ${{ inputs.output-name }}
shell: bash
run: | # sh
zip ${OUTPUT_FILE}.zip $INPUT_DIR/*.xml
- name: Upload test results to S3
env:
BUCKET: ${{ inputs.bucket }}
OUTPUT_FILE: ${{ inputs.output-name }}
shell: bash
run: | # sh
DATE=$(date '+%Y-%m-%d')
aws s3 cp ${OUTPUT_FILE}.zip s3://$BUCKET/$DATE/$GITHUB_RUN_ID/$GITHUB_RUN_ATTEMPT/
- name: Upload results to Trunk
if: ${{ always() }}
uses: trunk-io/analytics-uploader@main
with:
junit-paths: ${{ inputs.input-path }}
org-slug: metabase
token: ${{ inputs.trunk-api-token }}
continue-on-error: true

View File

@@ -0,0 +1,22 @@
name: 'Verify Organization Membership'
description: 'Check if a user is a member of a GitHub organization'
inputs:
github_token:
description: 'Token with access to the organization'
required: true
organization_name:
description: 'Organization name'
required: true
username:
description: 'Username'
required: true
outputs:
is_member:
value: ${{ steps.verify-membership.outputs.is_member }}
description: "Is the user a member of the organization"
runs:
using: "composite"
steps:
- run: bash ${{ github.action_path }}/verify_membership.sh ${{ inputs.github_token }} ${{ inputs.organization_name }} ${{ inputs.username }}
id: verify-membership
shell: bash

View File

@@ -0,0 +1,25 @@
#!/bin/bash
TOKEN=$1
ORG_NAME=$2
USERNAME=$3
response=$(curl -L -o /dev/null -w "%{http_code}" \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $TOKEN" \
-H "X-GitHub-Api-Version: 2022-11-28" \
"https://api.github.com/orgs/$ORG_NAME/members/$USERNAME")
# Github returns an empty response with 204 status if user is a member and 404 status otherwise
# See: https://docs.github.com/en/rest/orgs/members?apiVersion=2022-11-28#check-organization-membership-for-a-user
if [ "$response" == "204" ]; then
echo "The user $USERNAME is a member of $ORG_NAME"
echo "is_member=true" >> $GITHUB_OUTPUT
elif [ "$response" == "404" ]; then
echo "The user $USERNAME is not a member of $ORG_NAME"
echo "is_member=false" >> $GITHUB_OUTPUT
else
echo "Failed to determine the membership status for $USERNAME in $ORG_NAME"
echo "is_member=false" >> $GITHUB_OUTPUT
exit 1
fi

View File

@@ -1,16 +1,19 @@
default: &default
- "locales/**"
- "bin/**"
ci: &ci
- ".github/**/!(*.md)"
- "bin/**/!(*.md)"
shared_sources: &shared_sources
- "shared/src/**"
- "src/metabase/lib/**"
- "src/**/*.cljc"
- "src/**/*.cljs"
shared_specs: &shared_specs
- "shared/test/**"
- "test/**/*.cljc"
- "test/**/*.cljs"
frontend_ci: &frontend_ci
- ".github/actions/prepare-frontend/**"
- ".github/actions/prepare-backend/**"
- ".github/workflows/frontend.yml"
frontend_sources: &frontend_sources
- *shared_sources
@@ -20,6 +23,7 @@ frontend_sources: &frontend_sources
- "**/tsconfig*.json"
- "package.json"
- "babel.config.json"
- ".eslintrc"
- "postcss.config.js"
- "webpack.config.js"
- "webpack.static-viz.config.js"
@@ -29,14 +33,21 @@ frontend_specs: &frontend_specs
- "frontend/test/**"
- "frontend/**/tests/**"
- "frontend/**/*.unit.*"
- "jest.unit.conf.json"
- "jest.config.json"
- "jest.tz.unit.conf.json"
frontend_all: &frontend_all
- *ci
- *frontend_ci
- *frontend_sources
- *frontend_specs
backend_ci: &backend_ci
- ".github/actions/prepare-frontend/**"
- ".github/actions/prepare-backend/**"
- ".github/actions/test-driver/**"
- ".github/workflows/backend.yml"
- ".github/workflows/drivers.yml"
backend_presto_kerberos:
- "**/presto_jdbc/**"
- "**/presto_jdbc.clj"
@@ -61,16 +72,25 @@ backend_specs: &backend_specs
backend_all: &backend_all
- *default
- *ci
- *backend_ci
- *backend_sources
- *backend_specs
- *frontend_sources # keep it here until we detect static viz changes
sources: &sources
- *shared_sources
- *frontend_sources
- *backend_sources
e2e_ci: &e2e_ci
- ".github/actions/build-e2e-matrix/**"
- ".github/actions/prepare-frontend/**"
- ".github/actions/prepare-backend/**"
- ".github/actions/prepare-uberjar-artifact/**"
- ".github/actions/e2e-prepare-containers/**"
- ".github/actions/prepare-cypress/**"
- ".github/actions/run-snowplow-micro/**"
- ".github/workflows/e2e-tests.yml"
e2e_specs: &e2e_specs
- "**/*.cy.*.js"
- "e2e/runner/**"
@@ -79,12 +99,12 @@ e2e_specs: &e2e_specs
e2e_all:
- *default
- *ci
- *e2e_specs
- *e2e_ci
- *sources
- *e2e_specs
snowplow:
- *ci
- ".github/workflows/snowplow.yml"
- "snowplow/**"
documentation:
@@ -101,10 +121,18 @@ codeql:
i18n:
- *default
- *ci
- ".github/actions/prepare-frontend/**"
- ".github/actions/prepare-backend/**"
- ".github/workflows/i18n.yml"
- *sources
visualizations:
- "frontend/src/metabase/visualizations/**"
- "frontend/src/metabase/static-viz/**"
- "src/metabase/pulse/**"
cljs:
- *shared_sources
- *shared_specs
- ".github/workflows/cljs.yml"
- "shadow-cljs.edn"

15
.github/scripts/write-poms.sh vendored Executable file
View File

@@ -0,0 +1,15 @@
#!/usr/bin/env bash
set -euo pipefail
function pom() {
path=$1
echo "Writing ${path}/pom.xml"
(cd "$path" && clojure -X:deps mvn-pom)
}
pom .
for k in $(ls modules/drivers/); do
test -d "modules/drivers/$k" && pom "modules/drivers/$k"
done

67
.github/team.json vendored
View File

@@ -1,47 +1,74 @@
{
"teams": [
{
"name": "Team 42",
"label": ".Team/42 :milky_way:",
"name": "Querying Components",
"label": ".Team/QueryingComponents",
"members": [
"ranquild",
"uladzimirdev",
"kamilmielnik",
"oleggromov",
"nemanjaglumac",
"romeovs"
]
},
{
"name": "Embedding",
"label": ".Team/Embedding",
"members": [
"WiNloSt",
"deniskaber",
"oisincoveney",
"uladzimirdev",
"tsmacdonald",
"qnkhuat",
"calherries",
"kamilmielnik",
"npretto"
]
},
{
"name": "Query Processor",
"label": ".Team/QueryProcessor :hammer_and_wrench:",
"name": "BEC",
"label": ".Team/BackendComponents",
"members": [
"camsaul",
"kulyk",
"snoe",
"bshepherdson",
"john-metabase",
"metamben"
"tsmacdonald",
"qnkhuat",
"calherries",
"piranha",
"crisptrutski"
]
},
{
"name": "Pixel Police",
"label": ".Team/PixelPolice :police_officer:",
"name": "Query Processor",
"label": ".Team/QueryProcessor",
"members": [
"camsaul",
"snoe",
"bshepherdson",
"metamben",
"lbrdnk"
]
},
{
"name": "Admin Webapp",
"label": ".Team/AdminWebapp",
"members": [
"noahmoss",
"escherize",
"adam-james-v",
"qwef",
"alxnddr",
"iethree",
"npfitz",
"shaunlebron",
"johnswanson",
"rafpaf",
"sloansparger"
]
},
{
"name": "DashViz",
"label": ".Team/DashViz",
"members": [
"alxnddr",
"EmmadUsmani",
"JesseSDevaney",
"shaunlebron"
"kulyk",
"markbastian",
"adam-james-v"
]
}
]

View File

@@ -10,17 +10,17 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: tibdex/github-app-token@v1.6.0
- uses: tibdex/github-app-token@v2.1.0
id: generate-token
with:
app_id: ${{ secrets.METABASE_BOT_APP_ID }}
private_key: ${{ secrets.METABASE_BOT_APP_PRIVATE_KEY }}
- name: Checkout repository
uses: actions/checkout@v3
uses: actions/checkout@v4
- name: Assign author and their team. Returns true if team exists.
id: auto-assign
uses: actions/github-script@v6
uses: actions/github-script@v7
with:
github-token: ${{ steps.generate-token.outputs.token }}
script: |

View File

@@ -8,10 +8,10 @@ jobs:
if: github.event.pull_request.merged == true && (contains(github.event.pull_request.labels.*.name, 'backport') && github.event.action == 'closed' || github.event.label.name == 'backport')
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: tibdex/github-app-token@v1.6.0
- uses: tibdex/github-app-token@v2.1.0
id: generate-token
with:
app_id: ${{ secrets.METABASE_BOT_APP_ID }}
@@ -35,6 +35,7 @@ jobs:
BACKPORT_BRANCH="backport-$COMMIT"
# Checkout the target branch and create a new backport branch
git checkout ${TARGET_BRANCH}
git fetch --all
git checkout -b ${BACKPORT_BRANCH}
@@ -42,25 +43,41 @@ jobs:
CONFLICTS=$(git ls-files -u | wc -l)
if [ "$CONFLICTS" -gt 0 ]; then
git cherry-pick --abort
echo "Could not cherry pick because of a conflict"
echo "has-conflicts=true" >> $GITHUB_OUTPUT
git cherry-pick --abort
git checkout master
exit 0
# Add a shell script for resolving conflicts
echo "git reset HEAD~1" > ./backport.sh
echo "rm ./backport.sh" >> ./backport.sh
echo "git cherry-pick ${COMMIT}" >> ./backport.sh
echo "echo 'Resolve conflicts and force push this branch'" >> ./backport.sh
chmod +x ./backport.sh
git add ./backport.sh
git commit -m "Add backport resolution script"
PR_BODY=$(cat <<-END
#${ORIGINAL_PULL_REQUEST_NUMBER}
> [!IMPORTANT]
> Manual conflict resolution is required.
Checkout the branch and run \`./backport.sh\` script. Force push your changes after cherry-picking.
END
)
else
echo "has-conflicts=false" >> $GITHUB_OUTPUT
PR_BODY="#${ORIGINAL_PULL_REQUEST_NUMBER}"
fi
echo "has-conflicts=false" >> $GITHUB_OUTPUT
git checkout master
git push -u origin ${BACKPORT_BRANCH}
BACKPORT_PR_URL=$(hub pull-request -b "${TARGET_BRANCH}" -h "${BACKPORT_BRANCH}" -l "was-backported" -a "${GITHUB_ACTOR}" -F- <<<"🤖 backported \"${ORIGINAL_TITLE}\"
#${ORIGINAL_PULL_REQUEST_NUMBER}")
BACKPORT_PR_URL=$(gh pr create --base "${TARGET_BRANCH}" --head "${BACKPORT_BRANCH}" --label "was-backported" --assignee "${GITHUB_ACTOR}" --title "🤖 backported \"${ORIGINAL_TITLE}\"" --body "${PR_BODY}")
BACKPORT_PR_NUMBER=${BACKPORT_PR_URL##*/}
echo "backport_pr_number=$BACKPORT_PR_NUMBER" >> $GITHUB_OUTPUT
echo "New PR has been created"
git checkout master
env:
TARGET_BRANCH: ${{ steps.get_latest_release_branch.outputs.branch-name }}
ORIGINAL_PULL_REQUEST_NUMBER: ${{ github.event.pull_request.number }}
@@ -87,10 +104,10 @@ jobs:
if: ${{ steps.create_backport_pull_request.outputs.has-conflicts == 'true' }}
with:
include-log: false
message: could not create a backport due to conflicts
message: Manual conflict resolution is required
- uses: ./.github/actions/notify-pull-request
if: ${{ failure() }}
with:
include-log: true
message: something went wrong while creating a backport
message: Something went wrong while creating a backport

View File

@@ -3,8 +3,8 @@ name: Backend
on:
push:
branches:
- 'master'
- 'release-**'
- "master"
- "release-**"
pull_request:
types: [opened, synchronize, reopened, ready_for_review]
@@ -13,158 +13,166 @@ concurrency:
cancel-in-progress: true
env:
CLJ_KONDO_VERSION: "2023.07.13"
CLJ_KONDO_VERSION: "2023.09.07"
jobs:
files-changed:
name: Check which files changed
runs-on: ubuntu-22.04
timeout-minutes: 3
timeout-minutes: 5
outputs:
backend_all: ${{ steps.changes.outputs.backend_all }}
frontend_sources: ${{ steps.changes.outputs.frontend_sources }}
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Test which files changed
uses: dorny/paths-filter@v2.11.1
uses: dorny/paths-filter@v3.0.0
id: changes
with:
token: ${{ github.token }}
filters: .github/file-paths.yaml
static-viz-files-changed:
needs: files-changed
if: needs.files-changed.outputs.backend_all != 'true' && needs.files-changed.outputs.frontend_sources == 'true'
name: Check whether static-viz files changed
runs-on: ubuntu-22.04
timeout-minutes: 10
outputs:
static_viz: ${{ steps.static_viz.outputs.static_viz }}
steps:
- uses: actions/checkout@v4
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- name: Prepare back-end environment
uses: ./.github/actions/prepare-backend
with:
m2-cache-key: "files-changed"
- name: Build static-viz frontend
run: yarn build-static-viz
- name: Upload Static Viz Bundle Artifact
uses: actions/upload-artifact@v4
with:
name: static-viz-bundle-${{ github.sha }}
path: resources/frontend_client/app/dist
- name: Check for static viz changes
uses: dorny/paths-filter@v3.0.0
id: static_viz
with:
token: ${{ github.token }}
filters: .github/static-viz-sources.yaml
be-linter-cloverage:
needs: files-changed
if: github.event.pull_request.draft == false && needs.files-changed.outputs.backend_all == 'true'
if: github.ref_name == 'master' && needs.files-changed.outputs.backend_all == 'true'
runs-on: ubuntu-22.04
timeout-minutes: 90
steps:
- uses: actions/checkout@v3
- name: Prepare back-end environment
uses: ./.github/actions/prepare-backend
with:
m2-cache-key: 'cloverage'
- name: Build static viz frontend
run: yarn build-static-viz
- name: Collect the test coverage
run: clojure -X:dev:ci:ee:ee-dev:test:cloverage
- name: Upload coverage to codecov.io
uses: codecov/codecov-action@v3
with:
files: ./target/coverage/codecov.json
flags: back-end
- uses: actions/checkout@v4
- name: Prepare back-end environment
uses: ./.github/actions/prepare-backend
with:
m2-cache-key: "cloverage"
- name: Build static viz frontend
run: yarn build-static-viz
- name: Collect the test coverage
run: clojure -X:dev:ci:ee:ee-dev:test:cloverage
- name: Upload coverage to codecov.io
uses: codecov/codecov-action@v3
with:
files: ./target/coverage/codecov.json
flags: back-end
be-linter-clj-kondo:
needs: files-changed
if: needs.files-changed.outputs.backend_all == 'true'
needs: [files-changed, static-viz-files-changed]
if: |
!cancelled() &&
(needs.files-changed.outputs.backend_all == 'true' || needs.static-viz-files-changed.outputs.static_viz == 'true')
runs-on: ubuntu-22.04
timeout-minutes: 10
env:
DOWNLOAD_URL: https://github.com/clj-kondo/clj-kondo/releases/download
steps:
- uses: actions/checkout@v3
- name: Install clj-kondo
run: |
curl -OL ${DOWNLOAD_URL}/v${CLJ_KONDO_VERSION}/clj-kondo-${CLJ_KONDO_VERSION}-linux-static-amd64.zip
curl -OL ${DOWNLOAD_URL}/v${CLJ_KONDO_VERSION}/clj-kondo-${CLJ_KONDO_VERSION}-linux-static-amd64.zip.sha256
cat clj-kondo-${CLJ_KONDO_VERSION}-linux-static-amd64.zip.sha256 >> SHA256sum.txt
echo " clj-kondo-${CLJ_KONDO_VERSION}-linux-static-amd64.zip" >> SHA256sum.txt
sha256sum -c SHA256sum.txt
unzip clj-kondo-${CLJ_KONDO_VERSION}-linux-static-amd64.zip
- run: ./clj-kondo --version
- name: Run clj-kondo
run: >-
./clj-kondo
--config ./.clj-kondo/config.edn
--config-dir ./.clj-kondo
--parallel
--lint
./src
./test
./enterprise/backend/src
./enterprise/backend/test
./shared/src
./shared/test
./modules/drivers/athena/src
./modules/drivers/athena/test
./modules/drivers/bigquery-cloud-sdk/src
./modules/drivers/bigquery-cloud-sdk/test
./modules/drivers/druid/src
./modules/drivers/druid/test
./modules/drivers/googleanalytics/src
./modules/drivers/googleanalytics/test
./modules/drivers/mongo/src
./modules/drivers/mongo/test
./modules/drivers/oracle/src
./modules/drivers/oracle/test
./modules/drivers/presto-jdbc/src
./modules/drivers/presto-jdbc/test
./modules/drivers/redshift/src
./modules/drivers/redshift/test
./modules/drivers/snowflake/src
./modules/drivers/snowflake/test
./modules/drivers/sparksql/src
./modules/drivers/sparksql/test
./modules/drivers/sqlite/src
./modules/drivers/sqlite/test
./modules/drivers/sqlserver/src
./modules/drivers/sqlserver/test
./modules/drivers/vertica/src
./modules/drivers/vertica/test
- uses: actions/checkout@v4
- name: Prepare back-end environment
uses: ./.github/actions/prepare-backend
with:
m2-cache-key: 'kondo'
- name: Install clj-kondo
run: |
curl -OL ${DOWNLOAD_URL}/v${CLJ_KONDO_VERSION}/clj-kondo-${CLJ_KONDO_VERSION}-linux-static-amd64.zip
curl -OL ${DOWNLOAD_URL}/v${CLJ_KONDO_VERSION}/clj-kondo-${CLJ_KONDO_VERSION}-linux-static-amd64.zip.sha256
cat clj-kondo-${CLJ_KONDO_VERSION}-linux-static-amd64.zip.sha256 >> SHA256sum.txt
echo " clj-kondo-${CLJ_KONDO_VERSION}-linux-static-amd64.zip" >> SHA256sum.txt
sha256sum -c SHA256sum.txt
unzip -d /usr/local/bin clj-kondo-${CLJ_KONDO_VERSION}-linux-static-amd64.zip
- run: clj-kondo --version
- name: Run clj-kondo
run: ./bin/kondo.sh
be-linter-eastwood:
needs: files-changed
if: github.event.pull_request.draft == false && needs.files-changed.outputs.backend_all == 'true'
needs: [files-changed, static-viz-files-changed]
if: |
!cancelled() &&
github.event.pull_request.draft == false &&
(needs.files-changed.outputs.backend_all == 'true' || needs.static-viz-files-changed.outputs.static_viz == 'true')
runs-on: ubuntu-22.04
timeout-minutes: 20
steps:
- uses: actions/checkout@v3
- name: Prepare back-end environment
uses: ./.github/actions/prepare-backend
with:
m2-cache-key: 'eastwood'
- run: clojure -X:dev:ee:ee-dev:drivers:drivers-dev:test:eastwood
name: Run Eastwood linter
- uses: actions/checkout@v4
- name: Prepare back-end environment
uses: ./.github/actions/prepare-backend
with:
m2-cache-key: "eastwood"
- run: clojure -X:dev:ee:ee-dev:drivers:drivers-dev:test:eastwood
name: Run Eastwood linter
# Because it's not possible to conditionally run only `java-11-ee` test in the draft mode,
# we have to extract that job manually here. Backend developers have requested that this
# test runs at all times to give them an early warning sign is something is broken.
be-tests-java-11-ee-pre-check:
needs: files-changed
if: github.event.pull_request.draft == true && needs.files-changed.outputs.backend_all == 'true'
needs: [files-changed, static-viz-files-changed]
if: |
!cancelled() &&
github.event.pull_request.draft == true &&
(needs.files-changed.outputs.backend_all == 'true' || needs.static-viz-files-changed.outputs.static_viz == 'true')
runs-on: ubuntu-22.04
name: be-tests-java-11-ee-pre-check
timeout-minutes: 60
steps:
- uses: actions/checkout@v3
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- name: Prepare back-end environment
uses: ./.github/actions/prepare-backend
with:
m2-cache-key: java-11-ee-pre-check
- uses: actions/checkout@v4
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- name: Prepare back-end environment
uses: ./.github/actions/prepare-backend
with:
m2-cache-key: java-11-ee-pre-check
- run: yarn install --frozen-lockfile --prefer-offline
- name: Build static viz frontend
run: yarn build-static-viz
- run: yarn install --frozen-lockfile --prefer-offline
- name: Build static viz frontend
run: yarn build-static-viz
- name: Run tests
run: clojure -X:dev:ci:test:ee:ee-dev
- name: Run tests
run: clojure -X:dev:ci:test:ee:ee-dev
- name: Publish Test Report (JUnit)
uses: dorny/test-reporter@v1
if: failure()
with:
path: 'target/junit/**/*_test.xml'
name: JUnit Test Report be-tests-java-11-ee-pre-check
reporter: java-junit
list-suites: failed
list-tests: failed
fail-on-error: false
- name: Publish Test Report (JUnit)
uses: dorny/test-reporter@v1
if: failure()
with:
path: "target/junit/**/*_test.xml"
name: JUnit Test Report be-tests-java-11-ee-pre-check
reporter: java-junit
list-suites: failed
list-tests: failed
fail-on-error: false
be-tests:
needs: files-changed
if: github.event.pull_request.draft == false && needs.files-changed.outputs.backend_all == 'true'
needs: [files-changed, static-viz-files-changed]
if: |
!cancelled() &&
github.event.pull_request.draft == false &&
(needs.files-changed.outputs.backend_all == 'true' || needs.static-viz-files-changed.outputs.static_viz == 'true')
runs-on: ubuntu-22.04
name: be-tests-java-${{ matrix.java-version }}-${{ matrix.edition }}
timeout-minutes: 60
@@ -172,40 +180,65 @@ jobs:
fail-fast: false
matrix:
edition: [oss, ee]
java-version: [11, 17]
java-version: [11, 17, 21]
steps:
- uses: actions/checkout@v3
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- name: Prepare back-end environment
uses: ./.github/actions/prepare-backend
with:
m2-cache-key: be-tests
- uses: actions/checkout@v4
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- name: Prepare back-end environment
uses: ./.github/actions/prepare-backend
with:
m2-cache-key: be-tests
# Depending on which files changed, we might either have to build static-viz
# from scratch or download the previously built artifact
- name: Build static-viz frontend
if: needs.files-changed.outputs.backend_all == 'true'
run: yarn build-static-viz
- name: Download Static Viz Bundle Artifact
if: needs.static-viz-files-changed.outputs.static_viz == 'true'
uses: actions/download-artifact@v4
with:
name: static-viz-bundle-${{ github.sha }}
path: resources/frontend_client/app/dist
- run: yarn install --frozen-lockfile --prefer-offline
- name: Build static viz frontend
run: yarn build-static-viz
- name: Run tests
id: run-java-tests
if: matrix.java-version != 21
run: clojure -X:dev:ci:test:${{ matrix.edition }}:${{ matrix.edition }}-dev
- name: Run tests
run: clojure -X:dev:ci:test:${{ matrix.edition }}:${{ matrix.edition }}-dev
- name: Run tests using Java 21 on `master` only
id: run-java-tests-21
if: matrix.java-version == 21 && github.ref_name == 'master'
run: clojure -X:dev:ci:test:${{ matrix.edition }}:${{ matrix.edition }}-dev
- name: Publish Test Report (JUnit)
uses: dorny/test-reporter@v1
if: failure()
with:
path: 'target/junit/**/*_test.xml'
name: JUnit Test Report be-tests-java-${{ matrix.java-version }}-${{ matrix.edition }}
reporter: java-junit
list-suites: failed
list-tests: failed
fail-on-error: false
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always() && (steps.run-java-tests.conclusion != 'skipped' || steps.run-java-tests-21.conclusion != 'skipped')
with:
input-path: ./target/junit/
output-name: be-tests-java-${{ matrix.java-version }}-${{ matrix.edition }}
bucket: ${{ vars.AWS_S3_TEST_RESULTS_BUCKET }}
aws-access-key-id: ${{ secrets.AWS_TEST_RESULTS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_TEST_RESULTS_SECRET_ACCESS_KEY }}
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
- name: Publish Test Report (JUnit)
uses: dorny/test-reporter@v1
if: failure()
with:
path: "target/junit/**/*_test.xml"
name: JUnit Test Report be-tests-java-${{ matrix.java-version }}-${{ matrix.edition }}
reporter: java-junit
list-suites: failed
list-tests: failed
fail-on-error: false
be-tests-stub:
needs: files-changed
needs: [be-tests]
if: |
always() &&
github.event.pull_request.draft == false &&
needs.files-changed.outputs.backend_all == 'false'
!cancelled() &&
github.event.pull_request.draft == false && needs.be-tests.result == 'skipped'
runs-on: ubuntu-22.04
name: be-tests-java-${{ matrix.java-version }}-${{ matrix.edition }}
timeout-minutes: 5
@@ -213,7 +246,7 @@ jobs:
fail-fast: false
matrix:
edition: [oss, ee]
java-version: [11, 17]
java-version: [11, 17, 21]
steps:
- run: |
echo "Didn't run due to conditional filtering"
@@ -221,16 +254,19 @@ jobs:
# checks that all the namespaces we actually ship can be compiled, without any dependencies that we don't ship (such
# as `:dev` dependencies). See #27009 for more context.
be-check:
needs: files-changed
if: github.event.pull_request.draft == false && needs.files-changed.outputs.backend_all == 'true'
needs: [files-changed, static-viz-files-changed]
if: |
!cancelled() &&
github.event.pull_request.draft == false &&
(needs.files-changed.outputs.backend_all == 'true' || needs.static-viz-files-changed.outputs.static_viz == 'true')
runs-on: ubuntu-22.04
name: be-check-java-${{ matrix.java-version }}
timeout-minutes: 10
strategy:
matrix:
java-version: [11, 17, 19]
java-version: [11, 17, 21]
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Prepare backend
uses: ./.github/actions/prepare-backend
with:
@@ -239,17 +275,17 @@ jobs:
run: clojure -M:ee:drivers:check
be-check-stub:
needs: files-changed
needs: [files-changed, static-viz-files-changed, be-check]
if: |
always() &&
github.event.pull_request.draft == false &&
needs.files-changed.outputs.backend_all == 'false'
needs.be-check.result == 'skipped'
runs-on: ubuntu-22.04
name: be-check-java-${{ matrix.java-version }}
timeout-minutes: 10
strategy:
matrix:
java-version: [11, 17, 19]
java-version: [11, 17, 21]
steps:
- run: |
echo "Didn't run due to conditional filtering"

18
.github/workflows/backport-reminder.yml vendored Normal file
View File

@@ -0,0 +1,18 @@
name: Backport Reminder
on:
pull_request:
types: [auto_merge_enabled, review_requested, labeled, unlabeled, synchronize]
branches:
- "master"
jobs:
backport-reminder:
name: Decide whether to backport or not
runs-on: ubuntu-22.04
steps:
- uses: jesusvasquez333/verify-pr-label-action@v1.4.0
with:
github-token: '${{ secrets.GITHUB_TOKEN }}'
valid-labels: 'backport, no-backport'
disable-reviews: true

View File

@@ -11,27 +11,39 @@ jobs:
if: contains(github.event.comment.body, '@metabase-bot backport')
runs-on: ubuntu-22.04
steps:
- uses: tibdex/github-app-token@v1.6.0
- uses: tibdex/github-app-token@v2.1.0
id: generate-token
with:
app_id: ${{ secrets.METABASE_BOT_APP_ID }}
private_key: ${{ secrets.METABASE_BOT_APP_PRIVATE_KEY }}
- id: is_organization_member
uses: JamesSingleton/is-organization-member@1.0.0
- uses: actions/checkout@v4
name: Cherry-pick commits and create PR
with:
organization: metabase
username: ${{ github.event.issue.user.login }}
token: ${{ steps.generate-token.outputs.token }}
fetch-depth: 0
- name: Verify Membership
id: verify-membership
uses: ./.github/actions/verify-membership
with:
github_token: ${{ steps.generate-token.outputs.token }}
organization_name: metabase
username: ${{ github.event.comment.user.login }}
- run: |
result=${{ steps.is_organization_member.outputs.result }}
result=${{ steps.verify-membership.outputs.is_member }}
if [ $result == false ]; then
echo User ${{ github.event.comment.user.login }} is not a member of Metabase organization
exit 1
fi
- uses: actions/github-script@v6
- uses: actions/github-script@v7
id: branch_info
with:
script: |
await github.rest.reactions.createForIssueComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: context.payload.comment.id,
content: 'eyes',
});
// Example: @metabase-bot backport release-x.40.x
const [_botName, _command, targetBranch] = context.payload.comment.body.split(" ");
console.log(`Target branch is ${targetBranch}`);
@@ -54,7 +66,7 @@ jobs:
ref: `heads/${targetBranch}`,
});
const backportBranch = `backport-${originalPullRequest.head.ref}`
const backportBranch = `backport-${originalPullRequest.head.ref}-${targetBranch}`
try {
await github.rest.git.getRef({
@@ -80,10 +92,6 @@ jobs:
startSha: commits[0].sha,
endSha: commits[commits.length - 1].sha
}
- uses: actions/checkout@v3
name: Cherry-pick commits and create PR
with:
fetch-depth: 0
- id: create_backport_pull_request
name: Create backport pull request
run: |
@@ -108,13 +116,10 @@ jobs:
git push origin "${BACKPORT_BRANCH}" --force-with-lease
if [[ $(hub pr list -b "${TARGET_BRANCH}" -h "${BACKPORT_BRANCH}" -s "open") ]]; then
if [[ $(gh pr list --base "${TARGET_BRANCH}" --head "${BACKPORT_BRANCH}" -s "open") ]]; then
echo "PR already exists"
else
BACKPORT_PR_URL=$(hub pull-request -b "${TARGET_BRANCH}" -h "${BACKPORT_BRANCH}" -l "was-backported" -a "${GITHUB_ACTOR}" -F- <<<"🤖 backported \"${ORIGINAL_TITLE}\"
#${ORIGINAL_PULL_REQUEST_NUMBER}")
BACKPORT_PR_URL=$(gh pr create --base "${TARGET_BRANCH}" --head "${BACKPORT_BRANCH}" --label "was-backported" --assignee "${GITHUB_ACTOR}" --title "🤖 backported \"${ORIGINAL_TITLE}\"" --body "#${ORIGINAL_PULL_REQUEST_NUMBER}")
BACKPORT_PR_NUMBER=${BACKPORT_PR_URL##*/}
echo "backport_pr_number=$BACKPORT_PR_NUMBER" >> $GITHUB_OUTPUT
@@ -150,7 +155,7 @@ jobs:
needs: create_pull_request
if: ${{ failure() }}
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- uses: ./.github/actions/notify-pull-request
with:
include-log: true

View File

@@ -0,0 +1,53 @@
name: Bugs Slack Notification
on:
issues:
types:
- opened
jobs:
on-issue-opened:
runs-on: ubuntu-22.04
timeout-minutes: 5
if: |
contains(github.event.issue.labels.*.name, '.Needs Triage') &&
contains(github.event.issue.labels.*.name, 'Type:Bug')
steps:
- name: Setting title
uses: actions/github-script@v7
id: vars
with:
script: |
core.setOutput('issue_title', ${{ toJson(github.event.issue.title) }}.replaceAll(/"/g, '\\"'));
- name: Check for labels containing team name
id: check_labels
run: |
labels_json=$(sed 's/&/\$/g' <<< '${{ toJson(github.event.issue.labels) }}')
echo "has_team_label=false" >> "$GITHUB_OUTPUT"
for label in "$labels_json"
do
if [[ $label == *".Team"* ]]; then
echo "Label contains the team name."
echo "has_team_label=true" >> "$GITHUB_OUTPUT"
break
fi
done
- name: Send the issue ${{ github.event.issue.number }} to Slack
id: slack
if: steps.check_labels.outputs.has_team_label == 'false'
uses: slackapi/slack-github-action@v1.23.0
with:
payload: |
{
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "${{ steps.vars.outputs.issue_title }}\n${{ github.event.issue.html_url }}"
}
}
]
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_BUG_TRIAGE_WEBHOOK_URL }}
SLACK_WEBHOOK_TYPE: INCOMING_WEBHOOK

216
.github/workflows/build-for-release.yml vendored Normal file
View File

@@ -0,0 +1,216 @@
name: Release 1 - Build Release Artifact
run-name: Build ${{ inputs.version }}
on:
workflow_dispatch:
inputs:
version:
description: 'Metabase version (e.g. v0.46.3)'
type: string
required: true
commit:
description: 'A full-length commit SHA-1 hash'
required: true
jobs:
check-version:
runs-on: ubuntu-22.04
timeout-minutes: 10
outputs:
ee: ${{ fromJson(steps.canonical_version.outputs.result).ee }}
oss: ${{ fromJson(steps.canonical_version.outputs.result).oss }}
steps:
- name: Fail early on the incorrect version format
if: ${{ !(startsWith(inputs.version,'v0.') || startsWith(inputs.version,'v1.')) }}
run: |
echo "The version format is invalid!"
echo "It must start with either 'v0.' or 'v1.'."
echo "Please, try again."
exit 1
- uses: actions/checkout@v4
with:
sparse-checkout: release
- name: Prepare build scripts
run: cd ${{ github.workspace }}/release && yarn && yarn build
- name: Get Release Version
uses: actions/github-script@v7
id: canonical_version
with:
script: | # js
const { isValidVersionString, getCanonicalVersion, hasBeenReleased } = require('${{ github.workspace }}/release/dist/index.cjs');
const version = '${{ inputs.version }}';
if (!isValidVersionString(version)) {
throw new Error("The version format is invalid! It must start with either 'v0.' or 'v1.'.");
}
const versions = {
ee: getCanonicalVersion(version, 'ee'),
oss: getCanonicalVersion(version, 'oss'),
};
const ossReleased = await hasBeenReleased({
github,
owner: context.repo.owner,
repo: context.repo.repo,
version: versions.oss,
});
const eeReleased = await hasBeenReleased({
github,
owner: context.repo.owner,
repo: context.repo.repo,
version: versions.ee,
});
if (ossReleased || eeReleased) {
throw new Error("This version has already been released!", version);
}
return versions;
check-commit:
runs-on: ubuntu-22.04
timeout-minutes: 10
steps:
- name: Check out the code to verify the release branch
uses: actions/checkout@v4
with:
fetch-depth: 0 # IMPORTANT! to get all the branches
sparse-checkout: release
- name: Prepare build scripts
run: cd ${{ github.workspace }}/release && yarn && yarn build
- name: Get Release Branch
uses: actions/github-script@v7
id: release_branch
with:
result_encoding: string
script: | # js
const { getReleaseBranch } = require('${{ github.workspace }}/release/dist/index.cjs');
const version = '${{ inputs.version }}';
const releaseBranch = getReleaseBranch(version);
return releaseBranch;
- name: Ensure that the specified commit exists in the ${{ steps.release_branch.outputs.result }} release branch
run: |
RELEASE_BRANCH=${{ steps.release_branch.outputs.result }}
git checkout $RELEASE_BRANCH
git branch --contains ${{ inputs.commit }} | grep -q $RELEASE_BRANCH \
&& echo "Commit found in correct release branch" \
|| (echo "Commit not found in correct release branch" && exit 1)
get-build-requirements:
runs-on: ubuntu-22.04
timeout-minutes: 10
outputs:
java_version: ${{ fromJson(steps.dependencies.outputs.result).java_version }}
node_version: ${{ fromJson(steps.dependencies.outputs.result).node_version }}
build_process: ${{ fromJson(steps.dependencies.outputs.result).build_process }}
steps:
- uses: actions/checkout@v4
with:
sparse-checkout: release
- name: Prepare build scripts
run: cd ${{ github.workspace }}/release && yarn && yarn build
- name: Get build dependencies
uses: actions/github-script@v7
id: dependencies
with:
script: | # js
const { getBuildRequirements, getMajorVersion } = require('${{ github.workspace }}/release/dist/index.cjs');
const version = '${{ inputs.version }}';
const requirements = getBuildRequirements(version);
const build_process = getMajorVersion(version) < 46 ? 'legacy' : 'new';
console.log('Build process:', build_process);
return {
java_version: requirements.java,
node_version: requirements.node,
build_process,
};
build-uberjar-for-release:
needs: [check-version, check-commit, get-build-requirements]
runs-on: ubuntu-22.04
timeout-minutes: 50
strategy:
matrix:
edition: [oss, ee]
env:
INTERACTIVE: false
steps:
- name: Get correct version number
run: | # bash
if [ '${{matrix.edition}}' == 'ee' ]; then
version='${{ needs.check-version.outputs.ee }}'
else
version='${{ needs.check-version.outputs.oss }}'
fi
echo "VERSION=$version" >> $GITHUB_ENV
- name: Setup Java ${{ needs.get-build-requirements.outputs.java_version }}
uses: actions/setup-java@v4
with:
distribution: 'temurin'
java-version: ${{ needs.get-build-requirements.outputs.java_version }}
- name: Setup Node.js ${{ needs.get-build-requirements.outputs.node_version }}
uses: actions/setup-node@v4
with:
node-version: ${{ needs.get-build-requirements.outputs.node_version }}.x
- name: Check out the code
uses: actions/checkout@v4
with:
ref: ${{ github.event.inputs.commit }}
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- name: Prepare back-end environment
uses: ./.github/actions/prepare-backend
- name: Build Metabase
if: ${{ needs.get-build-requirements.outputs.build_process != 'legacy' }}
run: ./bin/build.sh :edition :${{ matrix.edition }} :version $VERSION
- name: Build Metabase (legacy)
if: ${{ needs.get-build-requirements.outputs.build_process == 'legacy' }}
run: cd ./bin/build-mb && clojure -X build/build! :edition :${{ matrix.edition }} :version $VERSION
- name: Store commit's SHA-1 hash
run: echo ${{ inputs.commit }} > COMMIT-ID
shell: bash
- run: mv ./target/uberjar/metabase.jar ./metabase.jar
- name: Calculate SHA256 checksum
run: sha256sum ./metabase.jar > SHA256.sum
shell: bash
- name: Upload JARs as artifact
uses: actions/upload-artifact@v4
with:
name: metabase-release-${{ matrix.edition }}-${{ inputs.commit }}-uberjar
path: |
./metabase.jar
./COMMIT-ID
./SHA256.sum
trigger-tests:
needs: [build-uberjar-for-release]
permissions:
actions: write
runs-on: ubuntu-22.04
timeout-minutes: 5
steps:
- name: trigger pre-release testing
uses: actions/github-script@v7
with:
script: | # js
github.rest.actions.createWorkflowDispatch({
owner: context.repo.owner,
repo: context.repo.repo,
workflow_id: 'pre-release.yml',
ref: '${{ github.ref }}',
inputs: {
commit: '${{ inputs.commit }}',
version: '${{ inputs.version }}',
}
});

View File

@@ -12,7 +12,7 @@ jobs:
test-build-scripts:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Prepare back-end environment
timeout-minutes: 5
uses: ./.github/actions/prepare-backend

View File

@@ -0,0 +1,20 @@
name: Prevent backport.sh from being merged
on:
pull_request:
types: [opened, synchronize, reopened]
jobs:
check-backport-script:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v4
- name: Check for backport.sh file
run: |
if [ -f "./backport.sh" ]; then
echo "backport.sh file exists. Please remove it before merging."
exit 1
else
echo "All good."
fi

80
.github/workflows/check-milestone.yml vendored Normal file
View File

@@ -0,0 +1,80 @@
name: Milestone Reminder
on:
pull_request:
types: [closed]
branches:
- "master"
jobs:
milestone-reminder:
if: github.event.pull_request.merged == true
name: Remind to set milestone
runs-on: ubuntu-22.04
timeout-minutes: 5
permissions:
pull-requests: write
issues: read
steps:
- uses: actions/github-script@v7
with:
script: | # js
const owner = context.repo.owner;
const repo = context.repo.repo;
const pullNumber = '${{ github.event.pull_request.number }}';
// the github API doesn't expose linked issues, so we have to parse the body ourselves
function getLinkedIssueId(pull) {
// https://regexr.com/7mjnp
const match = pull.data.body.match(/(\/issues\/|#)(\d+)/);
return match && match?.[2];
}
function getMilestone(pullOrIssue) {
// pull has pull.data.milestone, issue has issue.milestone
return pullOrIssue?.data?.milestone || pullOrIssue?.milestone;
}
const pull = await github.rest.pulls.get({
owner,
repo,
pull_number: pullNumber,
});
if (getMilestone(pull)) {
console.log("Pull request has milestone", pull.data.milestone?.title);
process.exit(0);
}
const issueId = getLinkedIssueId(pull);
if (issueId) {
console.log('linked issue found', issueId);
const issue = await github.rest.issues.get({
owner,
repo,
issue_number: issueId,
});
const milestone = getMilestone(issue);
if (milestone) {
console.log("Linked issue has milestone", milestone.title);
process.exit(0);
}
}
console.log("No milestone found");
const author = pull.data.user.login;
const guideLink = "https://www.notion.so/metabase/Metabase-Branching-Strategy-6eb577d5f61142aa960a626d6bbdfeb3?pvs=4#3dea255ffa3b4f74942a227844e889fa";
const message = `@${author} Did you forget to add a milestone to the issue for this PR? _[When and where should I add a milestone?](${guideLink})_`;
await github.rest.issues.createComment({
owner,
repo,
issue_number: pullNumber,
body: message,
});

54
.github/workflows/chromatic.yml vendored Normal file
View File

@@ -0,0 +1,54 @@
name: Chromatic Storybook deployment
on:
push:
branches:
- "master"
pull_request:
types: [synchronize, labeled, unlabeled]
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref && github.ref || github.run_id }}
cancel-in-progress: true
jobs:
files-changed:
name: Check which files changed
runs-on: ubuntu-22.04
timeout-minutes: 3
outputs:
frontend_all: ${{ steps.changes.outputs.frontend_all }}
e2e_specs: ${{ steps.changes.outputs.e2e_specs }}
steps:
- uses: actions/checkout@v4
- name: Test which files changed
uses: dorny/paths-filter@v3.0.0
id: changes
with:
token: ${{ github.token }}
filters: .github/file-paths.yaml
fe-chromatic:
needs: files-changed
if: contains(github.event.pull_request.labels.*.name, 'chromatic') || (github.ref_name == 'master' && needs.files-changed.outputs.frontend_all == 'true')
runs-on: ubuntu-22.04
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- name: Prepare back-end environment
uses: ./.github/actions/prepare-backend
with:
m2-cache-key: "cljs"
- name: Publish to Chromatic
uses: chromaui/action@v10.2.0
env:
PUBLISH_CHROMATIC: ${{ secrets.CHROMATIC_PROJECT_TOKEN }}
STORYBOOK_BUILD_TIMEOUT: 900000
if: env.PUBLISH_CHROMATIC != null
with:
token: ${{ secrets.GITHUB_TOKEN }}
projectToken: ${{ secrets.CHROMATIC_PROJECT_TOKEN }}

View File

@@ -9,7 +9,7 @@ jobs:
runs-on: ubuntu-22.04
steps:
- name: Check out code
uses: actions/checkout@v3
uses: actions/checkout@v4
- name: Cleanup
run: |

View File

@@ -12,12 +12,28 @@ concurrency:
cancel-in-progress: true
jobs:
files-changed:
name: Check which files changed
runs-on: ubuntu-22.04
timeout-minutes: 3
outputs:
cljs: ${{ steps.changes.outputs.cljs }}
steps:
- uses: actions/checkout@v4
- name: Test which files changed
uses: dorny/paths-filter@v3.0.0
id: changes
with:
token: ${{ github.token }}
filters: .github/file-paths.yaml
shared-tests-cljs:
needs: files-changed
if: needs.files-changed.outputs.cljs == 'true'
runs-on: ubuntu-22.04
timeout-minutes: 10
timeout-minutes: 15
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- name: Prepare back-end environment

View File

@@ -14,7 +14,7 @@ jobs:
runs-on: ubuntu-22.04
name: Codenotify
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
- uses: sourcegraph/codenotify@v0.6.4

View File

@@ -15,19 +15,20 @@ jobs:
outputs:
codeql: ${{ steps.changes.outputs.codeql }}
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Test which files changed
uses: dorny/paths-filter@v2.11.1
uses: dorny/paths-filter@v3.0.0
id: changes
with:
token: ${{ github.token }}
filters: .github/file-paths.yaml
analyze:
needs: files-changed
if: needs.files-changed.outputs.codeql == 'true'
runs-on: ubuntu-22.04
steps:
- name: Checkout repository
uses: actions/checkout@v3
uses: actions/checkout@v4
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
with:

View File

@@ -11,7 +11,7 @@ jobs:
markdown-link-check:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- name: Lint doc links

View File

@@ -0,0 +1,723 @@
name: Driver Stress Test
on:
workflow_dispatch:
inputs:
test:
description: 'The exact test name with its namespace.'
type: string
required: true
times:
description: 'How many times do you want to run this test?'
type: number
required: true
default: 1
driver:
description: 'The driver against which you want to run this test.'
required: true
default: 'Postgres'
type: choice
options:
- Athena
- BigQuery
- Druid
- Google Analytics
- Google Classpath Test
- Maria DB
- Maria DB (latest)
- Mongo 4
- Mongo 4 (SSL)
- Mongo 5
- Mongo 5 (SSL)
- Mongo (latest)
- MySQL
- MySQL (latest)
- Oracle 18
- Oracle 21
- Postgres
- Postgres (latest)
- Presto JDBC
- Redshift
- Snowflake
- SparkSQL
- SQLite
- SQL Server 2017
- SQL Server 2022
- Vertica
jobs:
be-tests-athena-ee:
if: inputs.driver == 'Athena'
runs-on: ubuntu-22.04
timeout-minutes: 90
env:
CI: 'true'
DRIVERS: athena
MB_ATHENA_TEST_REGION: us-east-1
MB_ATHENA_TEST_ACCESS_KEY: ${{ secrets.MB_ATHENA_TEST_ACCESS_KEY }}
MB_ATHENA_TEST_SECRET_KEY: ${{ secrets.MB_ATHENA_TEST_SECRET_KEY }}
MB_ATHENA_TEST_S3_STAGING_DIR: ${{ secrets.MB_ATHENA_TEST_S3_STAGING_DIR }}
steps:
- uses: actions/checkout@v4
- name: Test Athena driver
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-athena-ee'
test-args: ":only ${{ inputs.test }} :times ${{ inputs.times }}"
be-tests-bigquery-cloud-sdk-ee:
if: inputs.driver == 'BigQuery'
runs-on: ubuntu-22.04
timeout-minutes: 90
env:
CI: 'true'
DRIVERS: bigquery-cloud-sdk
MB_BIGQUERY_TEST_PROJECT_ID: ${{ secrets.BIGQUERY_TEST_PROJECT_ID }}
MB_BIGQUERY_TEST_CLIENT_ID: ${{ secrets.MB_BIGQUERY_TEST_CLIENT_ID }}
MB_BIGQUERY_TEST_CLIENT_SECRET: ${{ secrets.MB_BIGQUERY_TEST_CLIENT_SECRET }}
MB_BIGQUERY_TEST_ACCESS_TOKEN: ${{ secrets.MB_BIGQUERY_TEST_ACCESS_TOKEN }}
MB_BIGQUERY_TEST_REFRESH_TOKEN: ${{ secrets.MB_BIGQUERY_TEST_REFRESH_TOKEN }}
MB_BIGQUERY_CLOUD_SDK_TEST_SERVICE_ACCOUNT_JSON: ${{ secrets.MB_BIGQUERY_CLOUD_SDK_TEST_SERVICE_ACCOUNT_JSON }}
steps:
- uses: actions/checkout@v4
- name: Test BigQuery Cloud SDK driver
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-bigquery-cloud-sdk-ee'
test-args: ":only ${{ inputs.test }} :times ${{ inputs.times }}"
be-tests-druid-ee:
if: inputs.driver == 'Druid'
runs-on: ubuntu-22.04
timeout-minutes: 90
env:
CI: 'true'
DRIVERS: druid
services:
druid:
image: metabase/druid:0.20.2
ports:
- "8082:8082"
env:
CLUSTER_SIZE: nano-quickstart
steps:
- uses: actions/checkout@v4
- name: Test Druid driver
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-druid-ee'
test-args: ":only ${{ inputs.test }} :times ${{ inputs.times }}"
be-tests-googleanalytics-ee:
if: inputs.driver == 'Google Analytics'
runs-on: ubuntu-22.04
timeout-minutes: 90
env:
CI: 'true'
DRIVERS: googleanalytics
steps:
- uses: actions/checkout@v4
- name: Test Google Analytics driver
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-googleanalytics-ee'
test-args: ":only ${{ inputs.test }} :times ${{ inputs.times }}"
be-google-related-drivers-classpath-test:
if: inputs.driver == 'Google Classpath Test'
runs-on: ubuntu-22.04
timeout-minutes: 90
env:
CI: 'true'
DRIVERS: 'googleanalytics,bigquery-cloud-sdk'
MB_BIGQUERY_TEST_PROJECT_ID: ${{ secrets.BIGQUERY_TEST_PROJECT_ID }}
MB_BIGQUERY_TEST_CLIENT_ID: ${{ secrets.MB_BIGQUERY_TEST_CLIENT_ID }}
MB_BIGQUERY_TEST_CLIENT_SECRET: ${{ secrets.MB_BIGQUERY_TEST_CLIENT_SECRET }}
MB_BIGQUERY_TEST_ACCESS_TOKEN: ${{ secrets.MB_BIGQUERY_TEST_ACCESS_TOKEN }}
MB_BIGQUERY_TEST_REFRESH_TOKEN: ${{ secrets.MB_BIGQUERY_TEST_REFRESH_TOKEN }}
MB_BIGQUERY_CLOUD_SDK_TEST_SERVICE_ACCOUNT_JSON: ${{ secrets.MB_BIGQUERY_CLOUD_SDK_TEST_SERVICE_ACCOUNT_JSON }}
steps:
- uses: actions/checkout@v4
- name: Test Google Related Drivers Classpath
uses: ./.github/actions/test-driver
with:
junit-name: 'be-google-related-drivers-classpath-test'
test-args: ':only "[metabase.query-processor-test.expressions-test metabase.driver.google-test metabase.driver.googleanalytics-test ${{ inputs.test }}] :times ${{ inputs.times }}"'
be-tests-mariadb-10-2-ee:
if: inputs.driver == 'Maria DB'
runs-on: ubuntu-22.04
timeout-minutes: 90
env:
CI: 'true'
DRIVERS: mysql
MB_DB_TYPE: mysql
MB_DB_HOST: localhost
MB_DB_PORT: 3306
MB_DB_DBNAME: circle_test
MB_DB_USER: root
MB_MYSQL_TEST_USER: root
services:
mariadb:
image: circleci/mariadb:10.2.23
ports:
- "3306:3306"
steps:
- uses: actions/checkout@v4
- name: Test MariaDB driver (10.2)
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-mariadb-10-2-ee'
test-args: ":only ${{ inputs.test }} :times ${{ inputs.times }}"
be-tests-mariadb-latest-ee:
if: inputs.driver == 'Maria DB (latest)'
runs-on: ubuntu-22.04
timeout-minutes: 90
env:
CI: 'true'
DRIVERS: mysql
MB_DB_TYPE: mysql
MB_DB_HOST: localhost
MB_DB_PORT: 3306
MB_DB_DBNAME: circle_test
MB_DB_USER: root
MB_MYSQL_TEST_USER: root
services:
mariadb:
image: circleci/mariadb:latest
ports:
- "3306:3306"
steps:
- uses: actions/checkout@v4
- name: Test MariaDB driver (latest)
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-mariadb-latest-ee'
test-args: ":only ${{ inputs.test }} :times ${{ inputs.times }}"
be-tests-mongo-4-4-ee:
if: inputs.driver == 'Mongo 4'
runs-on: ubuntu-22.04
timeout-minutes: 90
env:
CI: 'true'
DRIVERS: mongo
MB_MONGO_TEST_USER: metabase
MB_MONGO_TEST_PASSWORD: metasample123
services:
mongodb:
image: metabase/qa-databases:mongo-sample-4.4
ports:
- "27017:27017"
steps:
- uses: actions/checkout@v4
- name: Test MongoDB driver (4.4)
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-mongo-4-4-ee'
test-args: ":only ${{ inputs.test }} :times ${{ inputs.times }}"
be-tests-mongo-4-4-ssl-ee:
if: inputs.driver == 'Mongo 4 (SSL)'
runs-on: ubuntu-22.04
timeout-minutes: 90
env:
CI: 'true'
DRIVERS: mongo
MB_MONGO_TEST_USER: metabase
MB_MONGO_TEST_PASSWORD: metasample123
MB_TEST_MONGO_REQUIRES_SSL: true
steps:
- uses: actions/checkout@v4
- name: Spin up Mongo docker container
run: docker run -d -p 27017:27017 --name metamongo metabase/qa-databases:mongo-sample-4.4 mongod --dbpath /data/db2/ --tlsMode requireTLS --tlsCertificateKeyFile /etc/mongo/metamongo.pem --tlsCAFile /etc/mongo/metaca.crt
- name: Wait until the port 27017 is ready
run: while ! nc -z localhost 27017; do sleep 1; done
timeout-minutes: 5
- name: Make SSL certificates for Mongo available
run: |
curl https://raw.githubusercontent.com/metabase/metabase-qa/master/dbs/mongo/certificates/metabase.crt \
-o ./test_resources/ssl/mongo/metabase.crt
curl https://raw.githubusercontent.com/metabase/metabase-qa/master/dbs/mongo/certificates/metabase.key \
-o ./test_resources/ssl/mongo/metabase.key
curl https://raw.githubusercontent.com/metabase/metabase-qa/master/dbs/mongo/certificates/metaca.crt \
-o ./test_resources/ssl/mongo/metaca.crt
- name: Test MongoDB SSL driver (4.4)
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-mongo-4-4-ee'
test-args: ":only ${{ inputs.test }} :times ${{ inputs.times }}"
be-tests-mongo-5-0-ee:
if: inputs.driver == 'Mongo 5'
runs-on: ubuntu-22.04
timeout-minutes: 90
env:
CI: 'true'
DRIVERS: mongo
MB_MONGO_TEST_USER: metabase
MB_MONGO_TEST_PASSWORD: metasample123
services:
mongodb:
image: metabase/qa-databases:mongo-sample-5.0
ports:
- "27017:27017"
steps:
- uses: actions/checkout@v4
- name: Test MongoDB driver (5.0)
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-mongo-5-0-ee'
test-args: ":only ${{ inputs.test }} :times ${{ inputs.times }}"
be-tests-mongo-5-0-ssl-ee:
if: inputs.driver == 'Mongo 5 (SSL)'
runs-on: ubuntu-22.04
timeout-minutes: 90
env:
CI: 'true'
DRIVERS: mongo
MB_MONGO_TEST_USER: metabase
MB_MONGO_TEST_PASSWORD: metasample123
MB_TEST_MONGO_REQUIRES_SSL: true
steps:
- uses: actions/checkout@v4
- name: Spin up Mongo docker container
run: docker run -d -p 27017:27017 --name metamongo metabase/qa-databases:mongo-sample-5.0 mongod --dbpath /data/db2/ --tlsMode requireTLS --tlsCertificateKeyFile /etc/mongo/metamongo.pem --tlsCAFile /etc/mongo/metaca.crt
- name: Wait until the port 27017 is ready
run: while ! nc -z localhost 27017; do sleep 1; done
timeout-minutes: 5
- name: Make SSL certificates for Mongo available
run: |
curl https://raw.githubusercontent.com/metabase/metabase-qa/master/dbs/mongo/certificates/metabase.crt \
-o ./test_resources/ssl/mongo/metabase.crt
curl https://raw.githubusercontent.com/metabase/metabase-qa/master/dbs/mongo/certificates/metabase.key \
-o ./test_resources/ssl/mongo/metabase.key
curl https://raw.githubusercontent.com/metabase/metabase-qa/master/dbs/mongo/certificates/metaca.crt \
-o ./test_resources/ssl/mongo/metaca.crt
- name: Test MongoDB SSL driver (5.0)
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-mongo-5-0-ee'
test-args: ":only ${{ inputs.test }} :times ${{ inputs.times }}"
be-tests-mongo-latest-ee:
if: inputs.driver == 'Mongo (latest)'
runs-on: ubuntu-22.04
timeout-minutes: 90
env:
CI: 'true'
DRIVERS: mongo
MB_MONGO_TEST_USER: metabase
MB_MONGO_TEST_PASSWORD: metasample123
services:
mongodb:
image: circleci/mongo:latest
ports:
- "27017:27017"
env:
MONGO_INITDB_ROOT_USERNAME: metabase
MONGO_INITDB_ROOT_PASSWORD: metasample123
steps:
- uses: actions/checkout@v4
- name: Test MongoDB driver (latest)
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-mongo-latest-ee'
test-args: ":only ${{ inputs.test }} :times ${{ inputs.times }}"
be-tests-mysql-8-0-ee:
if: inputs.driver == 'MySQL'
runs-on: ubuntu-22.04
timeout-minutes: 90
env:
CI: 'true'
DRIVERS: mysql
MB_DB_TYPE: mysql
MB_DB_HOST: localhost
MB_DB_PORT: 3306
MB_DB_DBNAME: circle_test
MB_DB_USER: root
MB_MYSQL_TEST_USER: root
services:
mysql:
image: cimg/mysql:8.0
ports:
- "3306:3306"
steps:
- uses: actions/checkout@v4
- name: Test MySQL driver (8.0)
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-mysql-8-0-ee'
test-args: ":only ${{ inputs.test }} :times ${{ inputs.times }}"
be-tests-mysql-latest-ee:
if: inputs.driver == 'MySQL (latest)'
runs-on: ubuntu-22.04
timeout-minutes: 90
env:
CI: 'true'
DRIVERS: mysql
MB_DB_TYPE: mysql
MB_DB_HOST: localhost
MB_DB_PORT: 3306
MB_DB_DBNAME: circle_test
MB_DB_USER: root
MB_MYSQL_TEST_USER: root
# set up env vars for something named "MYSQL_SSL" to run MySQL SSL tests verifying connectivity with PEM cert
# they are deliberately given a different name to prevent them from affecting the regular test run against
# the configured MySQL instance, but there is one particular test (mysql-connect-with-ssl-and-pem-cert-test)
# that overrides the MB_MYSQL_TEST_* values with them
# the MYSQL_RDS_SSL_INSTANCE vars are defined as secrets and can be altered
MB_MYSQL_SSL_TEST_HOST: ${{ secrets.MYSQL_RDS_SSL_INSTANCE_HOST }}
MB_MYSQL_SSL_TEST_SSL: true
MB_MYSQL_SSL_TEST_ADDITIONAL_OPTIONS: 'verifyServerCertificate=true'
# the contents of the ./resources/certificates/rds-combined-ca-bundle.pem file
MB_MYSQL_SSL_TEST_SSL_CERT: ${{ secrets.MB_MYSQL_SSL_TEST_SSL_CERT }}
MB_MYSQL_SSL_TEST_USER: metabase
MB_MYSQL_SSL_TEST_PASSWORD: ${{ secrets.MYSQL_RDS_SSL_INSTANCE_PASSWORD }}
services:
mysql:
image: mysql:latest
ports:
- "3306:3306"
steps:
- uses: actions/checkout@v4
- name: Test MySQL driver (latest)
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-mysql-latest-ee'
test-args: ":only ${{ inputs.test }} :times ${{ inputs.times }}"
be-tests-oracle-18-4-ee:
if: inputs.driver == 'Oracle 18'
runs-on: ubuntu-22.04
timeout-minutes: 90
env:
CI: 'true'
DRIVERS: oracle
MB_ORACLE_TEST_HOST: localhost
MB_ORACLE_TEST_USER: system
MB_ORACLE_TEST_PASSWORD: password
MB_ORACLE_TEST_SERVICE_NAME: XEPDB1
services:
oracle:
image: gvenzl/oracle-xe:18.4.0-slim
env:
ORACLE_PASSWORD: password
ports:
- "1521:1521"
steps:
- uses: actions/checkout@v4
- name: Test Oracle driver (18.4)
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-oracle-18-4-ee'
test-args: ":only ${{ inputs.test }} :times ${{ inputs.times }}"
be-tests-oracle-21-3-ee:
if: inputs.driver == 'Oracle 21'
runs-on: ubuntu-22.04
timeout-minutes: 90
env:
CI: 'true'
DRIVERS: oracle
MB_ORACLE_TEST_HOST: localhost
MB_ORACLE_TEST_PORT: 2484
MB_ORACLE_TEST_SERVICE_NAME: XEPDB1
MB_ORACLE_TEST_SSL: true
MB_ORACLE_TEST_SSL_USE_TRUSTSTORE: true
MB_ORACLE_TEST_SSL_TRUSTSTORE_PATH: './test_resources/ssl/oracle/truststore.p12'
MB_ORACLE_TEST_SSL_TRUSTSTORE_OPTIONS: local
MB_ORACLE_TEST_SSL_TRUSTSTORE_PASSWORD_VALUE: 'PassworD_#1234'
MB_ORACLE_TEST_SSL_USE_KEYSTORE: true
MB_ORACLE_TEST_SSL_KEYSTORE_PATH: './test_resources/ssl/oracle/keystore.p12'
MB_ORACLE_TEST_SSL_KEYSTORE_OPTIONS: local
MB_ORACLE_TEST_SSL_KEYSTORE_PASSWORD_VALUE: 'PassworD_#1234'
MB_ORACLE_SSL_TEST_SSL: true
services:
oracle:
image: metabase/qa-databases:oracle-xe-21.3
env:
ORACLE_PASSWORD: password
ports:
- "2484:2484"
steps:
- uses: actions/checkout@v4
- name: Test Oracle driver (21.3)
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-oracle-21-3-ee'
test-args: ":only ${{ inputs.test }} :times ${{ inputs.times }}"
be-tests-postgres-ee:
if: inputs.driver == 'Postgres'
runs-on: ubuntu-22.04
timeout-minutes: 90
env:
CI: 'true'
DRIVERS: postgres
MB_DB_TYPE: postgres
MB_DB_PORT: 5432
MB_DB_HOST: localhost
MB_DB_DBNAME: mb_test
MB_DB_USER: mb_test
MB_POSTGRESQL_TEST_USER: mb_test
services:
postgres:
image: postgres:12-alpine
ports:
- "5432:5432"
env:
POSTGRES_USER: mb_test
POSTGRES_DB: mb_test
POSTGRES_HOST_AUTH_METHOD: trust
steps:
- uses: actions/checkout@v4
- name: Test Postgres driver (12)
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-postgres-ee'
test-args: ":only ${{ inputs.test }} :times ${{ inputs.times }}"
be-tests-postgres-latest-ee:
if: inputs.driver == 'Postgres (latest)'
runs-on: ubuntu-22.04
timeout-minutes: 90
env:
CI: 'true'
DRIVERS: postgres
MB_DB_TYPE: postgres
MB_DB_PORT: 5432
MB_DB_HOST: localhost
MB_DB_DBNAME: circle_test
MB_DB_USER: circle_test
MB_POSTGRESQL_TEST_USER: circle_test
MB_POSTGRES_SSL_TEST_SSL: true
MB_POSTGRES_SSL_TEST_SSL_MODE: verify-full
MB_POSTGRES_SSL_TEST_SSL_ROOT_CERT_PATH: 'test-resources/certificates/us-east-2-bundle.pem'
services:
postgres:
image: circleci/postgres:latest
ports:
- "5432:5432"
env:
POSTGRES_USER: circle_test
POSTGRES_DB: circle_test
POSTGRES_HOST_AUTH_METHOD: trust
steps:
- uses: actions/checkout@v4
- name: Test Postgres driver (latest)
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-postgres-latest-ee'
test-args: ":only ${{ inputs.test }} :times ${{ inputs.times }}"
be-tests-presto-jdbc-ee:
if: inputs.driver == 'Presto JDBC'
runs-on: ubuntu-22.04
timeout-minutes: 90
env:
CI: 'true'
DRIVERS: presto-jdbc
MB_PRESTO_JDBC_TEST_CATALOG: test_data
MB_PRESTO_JDBC_TEST_HOST: localhost
MB_PRESTO_JDBC_TEST_PORT: 8443
MB_PRESTO_JDBC_TEST_SSL: true
MB_PRESTO_JDBC_TEST_USER: metabase
MB_PRESTO_JDBC_TEST_PASSWORD: metabase
MB_ENABLE_PRESTO_JDBC_DRIVER: true
MB_PRESTO_JDBC_TEST_ADDITIONAL_OPTIONS: 'SSLTrustStorePath=/tmp/cacerts-with-presto-ssl.jks&SSLTrustStorePassword=changeit'
services:
presto:
image: metabase/presto-mb-ci:latest # version 0.254
ports:
- "8443:8443"
env:
JAVA_TOOL_OPTIONS: "-Xmx2g"
steps:
- uses: actions/checkout@v4
- name: Wait for port ${{ env.MB_PRESTO_JDBC_TEST_PORT }} to be ready
run: while ! nc -z localhost ${{ env.MB_PRESTO_JDBC_TEST_PORT }}; do sleep 0.1; done
timeout-minutes: 15
- name: Create temp cacerts file based on bundled JDK one
run: cp $JAVA_HOME/lib/security/cacerts /tmp/cacerts-with-presto-ssl.jks
- name: Capture Presto server self signed CA
run: |
while [[ ! -s /tmp/presto-ssl-ca.pem ]];
do echo "Waiting to capture SSL CA" \
&& openssl s_client -connect localhost:8443 2>/dev/null </dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > /tmp/presto-ssl-ca.pem \
&& sleep 1; done
- name: Convert Presto CA from PEM to DER
run: openssl x509 -outform der -in /tmp/presto-ssl-ca.pem -out /tmp/presto-ssl-ca.der
- name: Add write permission on cacerts file
run: chmod u+w /tmp/cacerts-with-presto-ssl.jks
- name: Import Presto CA into temp cacerts file
run: |
keytool -noprompt -import -alias presto -keystore /tmp/cacerts-with-presto-ssl.jks \
-storepass changeit -file /tmp/presto-ssl-ca.der -trustcacerts
- name: Test Presto JDBC driver
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-presto-jdbc-ee'
test-args: ":only ${{ inputs.test }} :times ${{ inputs.times }}"
be-tests-redshift-ee:
if: inputs.driver == 'Redshift'
runs-on: ubuntu-22.04
timeout-minutes: 90
env:
CI: 'true'
DRIVERS: redshift
MB_REDSHIFT_TEST_USER: metabase_ci
MB_REDSHIFT_TEST_DB: testdb
MB_REDSHIFT_TEST_HOST: ${{ secrets.MB_REDSHIFT_TEST_HOST }}
MB_REDSHIFT_TEST_PASSWORD: ${{ secrets.MB_REDSHIFT_TEST_PASSWORD }}
steps:
- uses: actions/checkout@v4
- name: Test Redshift driver
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-redshift-ee'
test-args: ":only ${{ inputs.test }} :times ${{ inputs.times }}"
be-tests-snowflake-ee:
if: inputs.driver == 'Snowflake'
runs-on: ubuntu-22.04
timeout-minutes: 90
env:
CI: 'true'
DRIVERS: snowflake
MB_SNOWFLAKE_TEST_USER: METABASE CI
MB_SNOWFLAKE_TEST_ACCOUNT: ${{ secrets.MB_SNOWFLAKE_TEST_ACCOUNT }}
MB_SNOWFLAKE_TEST_PASSWORD: ${{ secrets.MB_SNOWFLAKE_TEST_PASSWORD }}
MB_SNOWFLAKE_TEST_WAREHOUSE: ${{ secrets.MB_SNOWFLAKE_TEST_WAREHOUSE }}
MB_SNOWFLAKE_TEST_PK_USER: METABASE PK
MB_SNOWFLAKE_TEST_PK_PRIVATE_KEY: ${{ secrets.MB_SNOWFLAKE_TEST_PK_PRIVATE_KEY }}
steps:
- uses: actions/checkout@v4
- name: Test Snowflake driver
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-snowflake-ee'
test-args: ":only ${{ inputs.test }} :times ${{ inputs.times }}"
be-tests-sparksql-ee:
if: inputs.driver == 'SparkSQL'
runs-on: ubuntu-22.04
timeout-minutes: 90
env:
CI: 'true'
DRIVERS: sparksql
services:
sparksql:
image: metabase/spark:3.2.1
ports:
- "10000:10000"
steps:
- uses: actions/checkout@v4
- name: Test Spark driver
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-sparksql-ee'
test-args: ":only ${{ inputs.test }} :times ${{ inputs.times }}"
be-tests-sqlite-ee:
if: inputs.driver == 'SQLite'
runs-on: ubuntu-22.04
timeout-minutes: 90
env:
CI: 'true'
DRIVERS: sqlite
steps:
- uses: actions/checkout@v4
- name: Test SQLite driver
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-sqlite-ee'
test-args: ":only ${{ inputs.test }} :times ${{ inputs.times }}"
be-tests-sqlserver-2017-ee:
if: inputs.driver == 'SQL Server 2017'
runs-on: ubuntu-22.04
timeout-minutes: 90
env:
CI: 'true'
DRIVERS: sqlserver
MB_SQLSERVER_TEST_HOST: localhost
MB_SQLSERVER_TEST_PASSWORD: 'P@ssw0rd'
MB_SQLSERVER_TEST_USER: SA
services:
sqlserver:
image: mcr.microsoft.com/mssql/server:2017-latest
ports:
- "1433:1433"
env:
ACCEPT_EULA: Y
SA_PASSWORD: 'P@ssw0rd'
MSSQL_MEMORY_LIMIT_MB: 1024
steps:
- uses: actions/checkout@v4
- name: Test MS SQL Server 2017 driver
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-sqlserver-ee'
test-args: ":only ${{ inputs.test }} :times ${{ inputs.times }}"
be-tests-sqlserver-2022-ee:
if: inputs.driver == 'SQL Server 2022'
runs-on: ubuntu-22.04
timeout-minutes: 90
env:
CI: 'true'
DRIVERS: sqlserver
MB_SQLSERVER_TEST_HOST: localhost
MB_SQLSERVER_TEST_PASSWORD: 'P@ssw0rd'
MB_SQLSERVER_TEST_USER: SA
services:
sqlserver:
image: mcr.microsoft.com/mssql/server:2022-latest
ports:
- "1433:1433"
env:
ACCEPT_EULA: Y
SA_PASSWORD: 'P@ssw0rd'
MSSQL_MEMORY_LIMIT_MB: 1024
steps:
- uses: actions/checkout@v4
- name: Test MS SQL Server 2022 driver
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-sqlserver-2022-ee'
test-args: ":only ${{ inputs.test }} :times ${{ inputs.times }}"
be-tests-vertica-ee:
if: inputs.driver == 'Vertica'
runs-on: ubuntu-22.04
timeout-minutes: 90
env:
CI: 'true'
DRIVERS: vertica
services:
vertica:
image: vertica/vertica-ce:12.0.2-0
ports:
- "5433:5433"
steps:
- uses: actions/checkout@v4
- name: Make plugins directory
run: mkdir plugins
- name: Test Vertica driver
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-vertica-ee'
test-args: ":only ${{ inputs.test }} :times ${{ inputs.times }}"

View File

@@ -20,9 +20,9 @@ jobs:
outputs:
backend_all: ${{ steps.changes.outputs.backend_all }}
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Test which files changed
uses: dorny/paths-filter@v2.11.1
uses: dorny/paths-filter@v3.0.0
id: changes
with:
token: ${{ github.token }}
@@ -41,12 +41,23 @@ jobs:
MB_ATHENA_TEST_SECRET_KEY: ${{ secrets.MB_ATHENA_TEST_SECRET_KEY }}
MB_ATHENA_TEST_S3_STAGING_DIR: ${{ secrets.MB_ATHENA_TEST_S3_STAGING_DIR }}
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Test Athena driver
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-athena-ee'
test-args: ":exclude-tags '[:mb/once]'"
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
with:
input-path: ./target/junit/
output-name: ${{ github.job }}
bucket: ${{ vars.AWS_S3_TEST_RESULTS_BUCKET }}
aws-access-key-id: ${{ secrets.AWS_TEST_RESULTS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_TEST_RESULTS_SECRET_ACCESS_KEY }}
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
be-tests-bigquery-cloud-sdk-ee:
needs: files-changed
@@ -63,12 +74,23 @@ jobs:
MB_BIGQUERY_TEST_REFRESH_TOKEN: ${{ secrets.MB_BIGQUERY_TEST_REFRESH_TOKEN }}
MB_BIGQUERY_CLOUD_SDK_TEST_SERVICE_ACCOUNT_JSON: ${{ secrets.MB_BIGQUERY_CLOUD_SDK_TEST_SERVICE_ACCOUNT_JSON }}
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Test BigQuery Cloud SDK driver
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-bigquery-cloud-sdk-ee'
test-args: ":exclude-tags '[:mb/once]'"
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
with:
input-path: ./target/junit/
output-name: ${{ github.job }}
bucket: ${{ vars.AWS_S3_TEST_RESULTS_BUCKET }}
aws-access-key-id: ${{ secrets.AWS_TEST_RESULTS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_TEST_RESULTS_SECRET_ACCESS_KEY }}
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
be-tests-druid-ee:
needs: files-changed
@@ -86,12 +108,23 @@ jobs:
env:
CLUSTER_SIZE: nano-quickstart
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Test Druid driver
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-druid-ee'
test-args: ":exclude-tags '[:mb/once]'"
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
with:
input-path: ./target/junit/
output-name: ${{ github.job }}
bucket: ${{ vars.AWS_S3_TEST_RESULTS_BUCKET }}
aws-access-key-id: ${{ secrets.AWS_TEST_RESULTS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_TEST_RESULTS_SECRET_ACCESS_KEY }}
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
be-tests-googleanalytics-ee:
needs: files-changed
@@ -102,12 +135,23 @@ jobs:
CI: 'true'
DRIVERS: googleanalytics
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Test Google Analytics driver
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-googleanalytics-ee'
test-args: ":exclude-tags '[:mb/once]'"
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
with:
input-path: ./target/junit/
output-name: ${{ github.job }}
bucket: ${{ vars.AWS_S3_TEST_RESULTS_BUCKET }}
aws-access-key-id: ${{ secrets.AWS_TEST_RESULTS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_TEST_RESULTS_SECRET_ACCESS_KEY }}
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
be-google-related-drivers-classpath-test:
needs: files-changed
@@ -124,12 +168,23 @@ jobs:
MB_BIGQUERY_TEST_REFRESH_TOKEN: ${{ secrets.MB_BIGQUERY_TEST_REFRESH_TOKEN }}
MB_BIGQUERY_CLOUD_SDK_TEST_SERVICE_ACCOUNT_JSON: ${{ secrets.MB_BIGQUERY_CLOUD_SDK_TEST_SERVICE_ACCOUNT_JSON }}
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Test Google Related Drivers Classpath
uses: ./.github/actions/test-driver
with:
junit-name: 'be-google-related-drivers-classpath-test'
test-args: ':only "[metabase.query-processor-test.expressions-test metabase.driver.google-test metabase.driver.googleanalytics-test]"'
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
with:
input-path: ./target/junit/
output-name: ${{ github.job }}
bucket: ${{ vars.AWS_S3_TEST_RESULTS_BUCKET }}
aws-access-key-id: ${{ secrets.AWS_TEST_RESULTS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_TEST_RESULTS_SECRET_ACCESS_KEY }}
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
be-tests-mariadb-10-2-ee:
needs: files-changed
@@ -151,11 +206,22 @@ jobs:
ports:
- "3306:3306"
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Test MariaDB driver (10.2)
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-mariadb-10-2-ee'
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
with:
input-path: ./target/junit/
output-name: ${{ github.job }}
bucket: ${{ vars.AWS_S3_TEST_RESULTS_BUCKET }}
aws-access-key-id: ${{ secrets.AWS_TEST_RESULTS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_TEST_RESULTS_SECRET_ACCESS_KEY }}
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
be-tests-mariadb-latest-ee:
needs: files-changed
@@ -177,13 +243,24 @@ jobs:
ports:
- "3306:3306"
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Test MariaDB driver (latest)
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-mariadb-latest-ee'
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
with:
input-path: ./target/junit/
output-name: ${{ github.job }}
bucket: ${{ vars.AWS_S3_TEST_RESULTS_BUCKET }}
aws-access-key-id: ${{ secrets.AWS_TEST_RESULTS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_TEST_RESULTS_SECRET_ACCESS_KEY }}
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
be-tests-mongo-4-2-ee:
be-tests-mongo-4-4-ee:
needs: files-changed
if: github.event.pull_request.draft == false && needs.files-changed.outputs.backend_all == 'true'
runs-on: ubuntu-22.04
@@ -195,18 +272,29 @@ jobs:
MB_MONGO_TEST_PASSWORD: metasample123
services:
mongodb:
image: metabase/qa-databases:mongo-sample-4.2
image: metabase/qa-databases:mongo-sample-4.4
ports:
- "27017:27017"
steps:
- uses: actions/checkout@v3
- name: Test MongoDB driver (4.2)
- uses: actions/checkout@v4
- name: Test MongoDB driver (4.4)
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-mongo-4-2-ee'
junit-name: 'be-tests-mongo-4-4-ee'
test-args: ":exclude-tags '[:mb/once]'"
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
with:
input-path: ./target/junit/
output-name: ${{ github.job }}
bucket: ${{ vars.AWS_S3_TEST_RESULTS_BUCKET }}
aws-access-key-id: ${{ secrets.AWS_TEST_RESULTS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_TEST_RESULTS_SECRET_ACCESS_KEY }}
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
be-tests-mongo-4-2-ssl-ee:
be-tests-mongo-4-4-ssl-ee:
needs: files-changed
if: github.event.pull_request.draft == false && needs.files-changed.outputs.backend_all == 'true'
runs-on: ubuntu-22.04
@@ -218,9 +306,9 @@ jobs:
MB_MONGO_TEST_PASSWORD: metasample123
MB_TEST_MONGO_REQUIRES_SSL: true
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Spin up Mongo docker container
run: docker run -d -p 27017:27017 --name metamongo metabase/qa-databases:mongo-sample-4.2 mongod --dbpath /data/db2/ --tlsMode requireTLS --tlsCertificateKeyFile /etc/mongo/metamongo.pem --tlsCAFile /etc/mongo/metaca.crt
run: docker run -d -p 27017:27017 --name metamongo metabase/qa-databases:mongo-sample-4.4 mongod --dbpath /data/db2/ --tlsMode requireTLS --tlsCertificateKeyFile /etc/mongo/metamongo.pem --tlsCAFile /etc/mongo/metaca.crt
- name: Wait until the port 27017 is ready
run: while ! nc -z localhost 27017; do sleep 1; done
timeout-minutes: 5
@@ -235,11 +323,22 @@ jobs:
curl https://raw.githubusercontent.com/metabase/metabase-qa/master/dbs/mongo/certificates/metaca.crt \
-o ./test_resources/ssl/mongo/metaca.crt
- name: Test MongoDB SSL driver (4.2)
- name: Test MongoDB SSL driver (4.4)
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-mongo-4-2-ee'
junit-name: 'be-tests-mongo-4-4-ee'
test-args: ":exclude-tags '[:mb/once]'"
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
with:
input-path: ./target/junit/
output-name: ${{ github.job }}
bucket: ${{ vars.AWS_S3_TEST_RESULTS_BUCKET }}
aws-access-key-id: ${{ secrets.AWS_TEST_RESULTS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_TEST_RESULTS_SECRET_ACCESS_KEY }}
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
be-tests-mongo-5-0-ee:
needs: files-changed
@@ -257,12 +356,23 @@ jobs:
ports:
- "27017:27017"
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Test MongoDB driver (5.0)
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-mongo-5-0-ee'
test-args: ":exclude-tags '[:mb/once]'"
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
with:
input-path: ./target/junit/
output-name: ${{ github.job }}
bucket: ${{ vars.AWS_S3_TEST_RESULTS_BUCKET }}
aws-access-key-id: ${{ secrets.AWS_TEST_RESULTS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_TEST_RESULTS_SECRET_ACCESS_KEY }}
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
be-tests-mongo-5-0-ssl-ee:
needs: files-changed
@@ -276,7 +386,7 @@ jobs:
MB_MONGO_TEST_PASSWORD: metasample123
MB_TEST_MONGO_REQUIRES_SSL: true
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Spin up Mongo docker container
run: docker run -d -p 27017:27017 --name metamongo metabase/qa-databases:mongo-sample-5.0 mongod --dbpath /data/db2/ --tlsMode requireTLS --tlsCertificateKeyFile /etc/mongo/metamongo.pem --tlsCAFile /etc/mongo/metaca.crt
- name: Wait until the port 27017 is ready
@@ -298,6 +408,17 @@ jobs:
with:
junit-name: 'be-tests-mongo-5-0-ee'
test-args: ":exclude-tags '[:mb/once]'"
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
with:
input-path: ./target/junit/
output-name: ${{ github.job }}
bucket: ${{ vars.AWS_S3_TEST_RESULTS_BUCKET }}
aws-access-key-id: ${{ secrets.AWS_TEST_RESULTS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_TEST_RESULTS_SECRET_ACCESS_KEY }}
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
be-tests-mongo-latest-ee:
needs: files-changed
@@ -318,14 +439,25 @@ jobs:
MONGO_INITDB_ROOT_USERNAME: metabase
MONGO_INITDB_ROOT_PASSWORD: metasample123
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Test MongoDB driver (latest)
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-mongo-latest-ee'
test-args: ":exclude-tags '[:mb/once]'"
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
with:
input-path: ./target/junit/
output-name: ${{ github.job }}
bucket: ${{ vars.AWS_S3_TEST_RESULTS_BUCKET }}
aws-access-key-id: ${{ secrets.AWS_TEST_RESULTS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_TEST_RESULTS_SECRET_ACCESS_KEY }}
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
be-tests-mysql-5-7-ee:
be-tests-mysql-8-0-ee:
needs: files-changed
if: github.event.pull_request.draft == false && needs.files-changed.outputs.backend_all == 'true'
runs-on: ubuntu-22.04
@@ -341,15 +473,15 @@ jobs:
MB_MYSQL_TEST_USER: root
services:
mysql:
image: circleci/mysql:5.7.23
image: cimg/mysql:8.0
ports:
- "3306:3306"
steps:
- uses: actions/checkout@v3
- name: Test MySQL driver (5.7)
- uses: actions/checkout@v4
- name: Test MySQL driver (8.0)
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-mysql-5-7-ee'
junit-name: 'be-tests-mysql-8-0-ee'
be-tests-mysql-latest-ee:
needs: files-changed
@@ -379,15 +511,29 @@ jobs:
MB_MYSQL_SSL_TEST_PASSWORD: ${{ secrets.MYSQL_RDS_SSL_INSTANCE_PASSWORD }}
services:
mysql:
image: circleci/mysql:latest
image: mysql:latest
env:
MYSQL_ALLOW_EMPTY_PASSWORD: true
MYSQL_DATABASE: circle_test
ports:
- "3306:3306"
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Test MySQL driver (latest)
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-mysql-latest-ee'
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
with:
input-path: ./target/junit/
output-name: ${{ github.job }}
bucket: ${{ vars.AWS_S3_TEST_RESULTS_BUCKET }}
aws-access-key-id: ${{ secrets.AWS_TEST_RESULTS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_TEST_RESULTS_SECRET_ACCESS_KEY }}
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
be-tests-oracle-18-4-ee:
needs: files-changed
@@ -409,12 +555,23 @@ jobs:
ports:
- "1521:1521"
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Test Oracle driver (18.4)
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-oracle-18-4-ee'
test-args: ":exclude-tags '[:mb/once]'"
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
with:
input-path: ./target/junit/
output-name: ${{ github.job }}
bucket: ${{ vars.AWS_S3_TEST_RESULTS_BUCKET }}
aws-access-key-id: ${{ secrets.AWS_TEST_RESULTS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_TEST_RESULTS_SECRET_ACCESS_KEY }}
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
be-tests-oracle-21-3-ee:
needs: files-changed
@@ -445,12 +602,23 @@ jobs:
ports:
- "2484:2484"
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Test Oracle driver (21.3)
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-oracle-21-3-ee'
test-args: ":exclude-tags '[:mb/once]'"
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
with:
input-path: ./target/junit/
output-name: ${{ github.job }}
bucket: ${{ vars.AWS_S3_TEST_RESULTS_BUCKET }}
aws-access-key-id: ${{ secrets.AWS_TEST_RESULTS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_TEST_RESULTS_SECRET_ACCESS_KEY }}
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
be-tests-postgres-ee:
needs: files-changed
@@ -463,20 +631,21 @@ jobs:
MB_DB_TYPE: postgres
MB_DB_PORT: 5432
MB_DB_HOST: localhost
MB_DB_DBNAME: circle_test
MB_DB_USER: circle_test
MB_POSTGRESQL_TEST_USER: circle_test
MB_DB_DBNAME: mb_test
MB_DB_USER: mb_test
MB_POSTGRESQL_TEST_USER: mb_test
services:
postgres:
image: circleci/postgres:9.6-alpine
image: postgres:12-alpine
ports:
- "5432:5432"
env:
POSTGRES_USER: circle_test
POSTGRES_DB: circle_test
POSTGRES_USER: mb_test
POSTGRES_DB: mb_test
POSTGRES_HOST_AUTH_METHOD: trust
steps:
- uses: actions/checkout@v3
- name: Test Postgres driver (9.6)
- uses: actions/checkout@v4
- name: Test Postgres driver (12)
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-postgres-ee'
@@ -508,11 +677,22 @@ jobs:
POSTGRES_DB: circle_test
POSTGRES_HOST_AUTH_METHOD: trust
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Test Postgres driver (latest)
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-postgres-latest-ee'
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
with:
input-path: ./target/junit/
output-name: ${{ github.job }}
bucket: ${{ vars.AWS_S3_TEST_RESULTS_BUCKET }}
aws-access-key-id: ${{ secrets.AWS_TEST_RESULTS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_TEST_RESULTS_SECRET_ACCESS_KEY }}
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
be-tests-presto-jdbc-ee:
needs: files-changed
@@ -538,7 +718,7 @@ jobs:
env:
JAVA_TOOL_OPTIONS: "-Xmx2g"
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Wait for port ${{ env.MB_PRESTO_JDBC_TEST_PORT }} to be ready
run: while ! nc -z localhost ${{ env.MB_PRESTO_JDBC_TEST_PORT }}; do sleep 0.1; done
timeout-minutes: 15
@@ -563,6 +743,17 @@ jobs:
with:
junit-name: 'be-tests-presto-jdbc-ee'
test-args: ":exclude-tags '[:mb/once]'"
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
with:
input-path: ./target/junit/
output-name: ${{ github.job }}
bucket: ${{ vars.AWS_S3_TEST_RESULTS_BUCKET }}
aws-access-key-id: ${{ secrets.AWS_TEST_RESULTS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_TEST_RESULTS_SECRET_ACCESS_KEY }}
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
be-tests-redshift-ee:
needs: files-changed
@@ -577,12 +768,23 @@ jobs:
MB_REDSHIFT_TEST_HOST: ${{ secrets.MB_REDSHIFT_TEST_HOST }}
MB_REDSHIFT_TEST_PASSWORD: ${{ secrets.MB_REDSHIFT_TEST_PASSWORD }}
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Test Redshift driver
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-redshift-ee'
test-args: ":exclude-tags '[:mb/once]'"
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
with:
input-path: ./target/junit/
output-name: ${{ github.job }}
bucket: ${{ vars.AWS_S3_TEST_RESULTS_BUCKET }}
aws-access-key-id: ${{ secrets.AWS_TEST_RESULTS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_TEST_RESULTS_SECRET_ACCESS_KEY }}
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
be-tests-snowflake-ee:
needs: files-changed
@@ -599,12 +801,23 @@ jobs:
MB_SNOWFLAKE_TEST_PK_USER: METABASE PK
MB_SNOWFLAKE_TEST_PK_PRIVATE_KEY: ${{ secrets.MB_SNOWFLAKE_TEST_PK_PRIVATE_KEY }}
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Test Snowflake driver
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-snowflake-ee'
test-args: ":exclude-tags '[:mb/once]'"
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
with:
input-path: ./target/junit/
output-name: ${{ github.job }}
bucket: ${{ vars.AWS_S3_TEST_RESULTS_BUCKET }}
aws-access-key-id: ${{ secrets.AWS_TEST_RESULTS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_TEST_RESULTS_SECRET_ACCESS_KEY }}
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
be-tests-sparksql-ee:
needs: files-changed
@@ -620,12 +833,23 @@ jobs:
ports:
- "10000:10000"
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Test Spark driver
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-sparksql-ee'
test-args: ":exclude-tags '[:mb/once]'"
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
with:
input-path: ./target/junit/
output-name: ${{ github.job }}
bucket: ${{ vars.AWS_S3_TEST_RESULTS_BUCKET }}
aws-access-key-id: ${{ secrets.AWS_TEST_RESULTS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_TEST_RESULTS_SECRET_ACCESS_KEY }}
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
be-tests-sqlite-ee:
needs: files-changed
@@ -636,14 +860,25 @@ jobs:
CI: 'true'
DRIVERS: sqlite
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Test SQLite driver
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-sqlite-ee'
test-args: ":exclude-tags '[:mb/once]'"
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
with:
input-path: ./target/junit/
output-name: ${{ github.job }}
bucket: ${{ vars.AWS_S3_TEST_RESULTS_BUCKET }}
aws-access-key-id: ${{ secrets.AWS_TEST_RESULTS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_TEST_RESULTS_SECRET_ACCESS_KEY }}
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
be-tests-sqlserver-ee:
be-tests-sqlserver-2017-ee:
needs: files-changed
if: github.event.pull_request.draft == false && needs.files-changed.outputs.backend_all == 'true'
runs-on: ubuntu-22.04
@@ -664,12 +899,62 @@ jobs:
SA_PASSWORD: 'P@ssw0rd'
MSSQL_MEMORY_LIMIT_MB: 1024
steps:
- uses: actions/checkout@v3
- name: Test MS SQL Server driver
- uses: actions/checkout@v4
- name: Test MS SQL Server 2017 driver
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-sqlserver-ee'
test-args: ":exclude-tags '[:mb/once]'"
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
with:
input-path: ./target/junit/
output-name: ${{ github.job }}
bucket: ${{ vars.AWS_S3_TEST_RESULTS_BUCKET }}
aws-access-key-id: ${{ secrets.AWS_TEST_RESULTS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_TEST_RESULTS_SECRET_ACCESS_KEY }}
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
be-tests-sqlserver-2022-ee:
needs: files-changed
if: github.event.pull_request.draft == false && needs.files-changed.outputs.backend_all == 'true'
runs-on: ubuntu-22.04
timeout-minutes: 90
env:
CI: 'true'
DRIVERS: sqlserver
MB_SQLSERVER_TEST_HOST: localhost
MB_SQLSERVER_TEST_PASSWORD: 'P@ssw0rd'
MB_SQLSERVER_TEST_USER: SA
services:
sqlserver:
image: mcr.microsoft.com/mssql/server:2022-latest
ports:
- "1433:1433"
env:
ACCEPT_EULA: Y
SA_PASSWORD: 'P@ssw0rd'
MSSQL_MEMORY_LIMIT_MB: 1024
steps:
- uses: actions/checkout@v4
- name: Test MS SQL Server 2022 driver
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-sqlserver-2022-ee'
test-args: ":exclude-tags '[:mb/once]'"
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
with:
input-path: ./target/junit/
output-name: ${{ github.job }}
bucket: ${{ vars.AWS_S3_TEST_RESULTS_BUCKET }}
aws-access-key-id: ${{ secrets.AWS_TEST_RESULTS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_TEST_RESULTS_SECRET_ACCESS_KEY }}
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
be-tests-vertica-ee:
needs: files-changed
@@ -685,7 +970,7 @@ jobs:
ports:
- "5433:5433"
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Make plugins directory
run: mkdir plugins
- name: Test Vertica driver
@@ -693,3 +978,14 @@ jobs:
with:
junit-name: 'be-tests-vertica-ee'
test-args: ":exclude-tags '[:mb/once]'"
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
with:
input-path: ./target/junit/
output-name: ${{ github.job }}
bucket: ${{ vars.AWS_S3_TEST_RESULTS_BUCKET }}
aws-access-key-id: ${{ secrets.AWS_TEST_RESULTS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_TEST_RESULTS_SECRET_ACCESS_KEY }}
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}

View File

@@ -27,7 +27,7 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v3
uses: actions/checkout@v4
- name: Set source Docker image to OSS
run: |
echo "DOCKER_SOURCE_IMAGE=metabase/metabase:${{ matrix.version.source }}" >> $GITHUB_ENV
@@ -86,7 +86,7 @@ jobs:
--config-file e2e/test/scenarios/cross-version/target/shared/cross-version-target.config.js \
--spec e2e/test/scenarios/cross-version/target/**/*.cy.spec.js
- name: Upload Cypress Artifacts upon failure
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
if: failure()
with:
name: cypress-artifacts-${{ matrix.version.source}}-to-${{ matrix.version.target }}

View File

@@ -3,10 +3,6 @@ name: E2E Stress Test Flake Fix
on:
workflow_dispatch:
inputs:
artifact:
description: 'Artifact ID'
type: string
required: true
spec:
description: 'Relative path of the target spec'
type: string
@@ -15,8 +11,33 @@ on:
description: 'Number of times to run the test (e.g. 20)'
type: string
required: true
grep:
description: 'Grep and filter tests to run in isolation'
type: string
required: false
mb_edition:
description: 'Set MB_EDITION env var to "ee" (enteprise) or "oss" (open-source)'
type: string
required: false
default: "ee"
jobs:
workflow-summary:
name: Stress test inputs
runs-on: ubuntu-22.04
timeout-minutes: 5
steps:
- name: Generate workflow summary
run: |
echo '**Inputs:**' >> $GITHUB_STEP_SUMMARY
echo '' >> $GITHUB_STEP_SUMMARY
echo '- `branch`: ${{ github.ref_name }}' >> $GITHUB_STEP_SUMMARY
echo '- `spec`: ${{ inputs.spec }}' >> $GITHUB_STEP_SUMMARY
echo '- `burn_in`: ${{ inputs.burn_in }}' >> $GITHUB_STEP_SUMMARY
echo '- `grep`: "${{ inputs.grep }}"' >> $GITHUB_STEP_SUMMARY
echo '' >> $GITHUB_STEP_SUMMARY
echo 'triggered by: @${{ github.event.sender.login }}' >> $GITHUB_STEP_SUMMARY
stress-test-flake-fix:
runs-on: ubuntu-22.04
timeout-minutes: 60
@@ -24,73 +45,40 @@ jobs:
env:
DISPLAY: ""
QA_DB_ENABLED: true
CYPRESS_REPLAYIO_ENABLED: 1
CYPRESS_ALL_FEATURES_TOKEN: ${{ secrets.ENTERPRISE_TOKEN }}
CYPRESS_NO_FEATURES_TOKEN: ${{ secrets.E2E_STARTER_TOKEN }}
MB_SNOWPLOW_AVAILABLE: true
MB_SNOWPLOW_URL: "http://localhost:9090" # Snowplow micro
MB_EDITION: ${{ inputs.mb_edition }}
TERM: xterm
TZ: US/Pacific # to make node match the instance tz
services:
maildev:
image: maildev/maildev:2.0.5
ports:
- "1080:1080"
- "1025:1025"
credentials:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
openldap:
image: bitnami/openldap:2.6.4
ports:
- 389:389
env:
LDAP_ADMIN_PASSWORD: adminpass
LDAP_USERS: user01@example.org,user02@example.org
LDAP_PASSWORDS: 123456,123465
LDAP_ROOT: dc=example,dc=org
LDAP_PORT_NUMBER: 389
credentials:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
postgres-sample:
image: metabase/qa-databases:postgres-sample-12
ports:
- "5404:5432"
credentials:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
mongo-sample:
image: metabase/qa-databases:mongo-sample-4.4
ports:
- 27004:27017
credentials:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
mysql-sample:
image: metabase/qa-databases:mysql-sample-8
ports:
- 3304:3306
credentials:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
steps:
- uses: actions/checkout@v3
- name: Download Metabase uberjar from a previously stored artifact
run: |
curl -L \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer $GITHUB_TOKEN" \
-H "X-GitHub-Api-Version: 2022-11-28" \
https://api.github.com/repos/metabase/metabase/actions/artifacts/$ARTIFACT_ID/zip \
-o mb.zip
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
ARTIFACT_ID: ${{ github.event.inputs.artifact }}
- name: Unzip Metabase artifact containing an uberjar
run: unzip mb.zip
- uses: actions/checkout@v4
with:
# Important because we need previous commits hashes to find and download the uberjar!
fetch-depth: 20
- name: Prepare Docker containers
uses: ./.github/actions/e2e-prepare-containers
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
maildev: true
openldap: true
postgres: true
mysql: true
mongo: true
- name: Download Metabase ${{ matrix.edition }} uberjar
uses: ./.github/actions/e2e-download-uberjar
with:
edition: 'ee'
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- name: Prepare JDK 11
uses: actions/setup-java@v3
uses: actions/setup-java@v4
with:
java-version: 11
distribution: "temurin"
@@ -98,20 +86,19 @@ jobs:
uses: ./.github/actions/prepare-cypress
- name: Run Snowplow micro
uses: ./.github/actions/run-snowplow-micro
- name: Get Metabase version info
run: |
jar xf target/uberjar/metabase.jar version.properties
mv version.properties resources/
# For all options and fine-grained control, take a look at the documentation
# https://github.com/cypress-io/cypress/tree/develop/npm/grep
- name: Stress-test ${{ github.event.inputs.spec }} ${{ github.event.inputs.burn_in }} times
run: |
yarn run test-cypress-run \
--spec '${{ github.event.inputs.spec }}' \
--env burn=${{ github.event.inputs.burn_in }} \
--config-file e2e/support/cypress-stress-test.config.js
env:
TERM: xterm
--env burn=${{ github.event.inputs.burn_in }},grep='${{ github.event.inputs.grep }}' \
--config-file e2e/support/cypress-stress-test.config.js \
--browser 'replay-chromium'
- name: Upload Cypress Artifacts upon failure
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
if: failure()
with:
name: cypress-failed-tests-recording

View File

@@ -1,9 +1,6 @@
name: E2E Tests
on:
# We'll record runs using Replay.io and their browser on a schedule as an experiment
schedule:
- cron: '0 22 * * 0'
push:
branches:
- "master"
@@ -16,13 +13,6 @@ concurrency:
cancel-in-progress: true
jobs:
test-run-id:
runs-on: ubuntu-22.04
outputs:
testRunId: ${{ steps.testRunId.outputs.testRunId }}
steps:
- id: testRunId
run: echo testRunId=$(npx uuid) >> "$GITHUB_OUTPUT"
files-changed:
name: Check which files changed
runs-on: ubuntu-22.04
@@ -30,17 +20,32 @@ jobs:
outputs:
e2e_all: ${{ steps.changes.outputs.e2e_all }}
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Test which files changed
uses: dorny/paths-filter@v2.11.1
uses: dorny/paths-filter@v3.0.0
id: changes
with:
token: ${{ github.token }}
filters: .github/file-paths.yaml
e2e-matrix-builder:
runs-on: ubuntu-22.04
timeout-minutes: 5
outputs:
matrix: ${{ steps.e2e-matrix.outputs.matrix }}
steps:
- uses: actions/checkout@v4
- name: Generate matrix for E2E tests
id: e2e-matrix
uses: ./.github/actions/build-e2e-matrix
build:
needs: files-changed
if: github.event.pull_request.draft == false && needs.files-changed.outputs.e2e_all == 'true'
needs: [files-changed, e2e-matrix-builder]
if: |
!cancelled() &&
github.event.pull_request.draft == false &&
needs.e2e-matrix-builder.result == 'success' &&
needs.files-changed.outputs.e2e_all == 'true'
runs-on: ubuntu-22.04
timeout-minutes: 25
strategy:
@@ -50,7 +55,7 @@ jobs:
MB_EDITION: ${{ matrix.edition }}
INTERACTIVE: false
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- name: Prepare back-end environment
@@ -63,16 +68,16 @@ jobs:
- name: Prepare uberjar artifact
uses: ./.github/actions/prepare-uberjar-artifact
with:
name: metabase-${{ matrix.edition }}-${{ github.event.pull_request.head.sha || github.sha }}-uberjar
e2e-tests:
needs: [build, files-changed, test-run-id]
needs: [build, e2e-matrix-builder]
if: |
always() &&
needs.files-changed.outputs.e2e_all == 'true' &&
needs.build.result == 'success'
runs-on: ubuntu-22.04
timeout-minutes: 90
name: e2e-tests-${{ matrix.folder }}${{ matrix.context }}-${{ matrix.edition }}
!cancelled() && needs.build.result == 'success'
runs-on: ${{ matrix.runner }}
timeout-minutes: 45
name: e2e-tests-${{ matrix.name }}-${{ matrix.edition }}
env:
MB_EDITION: ${{ matrix.edition }}
DISPLAY: ""
@@ -81,228 +86,133 @@ jobs:
# Example: you can get `CYPRESS_FOO` with `Cypress.env("FOO")`
CYPRESS_ALL_FEATURES_TOKEN: ${{ secrets.ENTERPRISE_TOKEN }}
CYPRESS_NO_FEATURES_TOKEN: ${{ secrets.E2E_STARTER_TOKEN }}
CYPRESS_PULL_REQUEST_ID: ${{ github.event.pull_request.number || '' }}
COMMIT_INFO_MESSAGE : ${{ github.event.pull_request.title || github.event.head_commit.message || github.even.head.sha }}
MB_SNOWPLOW_AVAILABLE: true
MB_SNOWPLOW_URL: "http://localhost:9090" # Snowplow micro
ELECTRON_EXTRA_LAUNCH_ARGS: "--remote-debugging-port=40500" # deploysentinel
CYPRESS_REPLAYIO_ENABLED: 1
RECORD_REPLAY_METADATA_FILE: /tmp/replay-metadata.json
RECORD_REPLAY_METADATA_TEST_RUN_ID: ${{ github.run_id }}
REPLAY_API_KEY: ${{ secrets.REPLAY_IO_TOKEN }}
TZ: US/Pacific # to make node match the instance tz
strategy:
fail-fast: false
matrix:
java-version: [11]
edition: [ee]
folder:
- "auditing"
- "actions"
- "admin"
- "binning"
- "collections"
- "custom-column"
- "dashboard"
- "dashboard-filters"
- "embedding"
- "filters"
- "joins"
- "models"
- "native"
- "native-filters"
- "onboarding"
- "organization"
- "permissions"
- "question"
- "sharing"
- "visualizations"
include:
- edition: oss
context: grep
java-version: 11
services:
maildev:
image: maildev/maildev:2.0.5
ports:
- "1080:1080"
- "1025:1025"
credentials:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
openldap:
image: bitnami/openldap:2.6.4
ports:
- 389:389
env:
LDAP_ADMIN_PASSWORD: adminpass
LDAP_USERS: user01@example.org,user02@example.org
LDAP_PASSWORDS: 123456,123465
LDAP_ROOT: dc=example,dc=org
LDAP_PORT_NUMBER: 389
credentials:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
postgres-sample:
image: metabase/qa-databases:postgres-sample-12
ports:
- "5404:5432"
credentials:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
mongo-sample:
image: metabase/qa-databases:mongo-sample-4.4
ports:
- 27004:27017
credentials:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
mysql-sample:
image: metabase/qa-databases:mysql-sample-8
ports:
- 3304:3306
credentials:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
matrix: ${{ fromJSON(needs.e2e-matrix-builder.outputs.matrix) }}
steps:
- uses: actions/checkout@v3
- name: Record runs using Deploysentinel except for the release branch
if: ${{ github.ref == 'refs/heads/master' || !(startsWith(github.event.pull_request.base.ref, 'release')) }}
run: |
echo "CYPRESS_DEPLOYSENTINEL_KEY=${{ secrets.CYPRESS_DEPLOYSENTINEL_KEY }}" >> $GITHUB_ENV
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- name: Prepare JDK ${{ matrix.java-version }}
uses: actions/setup-java@v3
with:
java-version: ${{ matrix.java-version }}
distribution: "temurin"
- name: Prepare Cypress environment
uses: ./.github/actions/prepare-cypress
- name: Run Snowplow micro
uses: ./.github/actions/run-snowplow-micro
- uses: actions/checkout@v4
- name: Install Chrome v114
uses: browser-actions/setup-chrome@v1
- name: Prepare Docker containers
uses: ./.github/actions/e2e-prepare-containers
with:
# https://chromium.cypress.io/linux/stable/114.0.5735.133
# https://www.googleapis.com/download/storage/v1/b/chromium-browser-snapshots/o/Linux_x64%2F1135580%2Fchrome-linux.zip
chrome-version: 1135580
id: setup-chrome
- run: |
echo Installed chromium version: ${{ steps.setup-chrome.outputs.chrome-version }}
${{ steps.setup-chrome.outputs.chrome-path }} --version
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
maildev: true
openldap: ${{ startsWith(matrix.name, 'admin') }}
postgres: ${{ matrix.name != 'mongo'}}
mysql: ${{ matrix.name != 'mongo'}}
mongo: ${{ matrix.name == 'mongo'}}
- uses: actions/download-artifact@v3
name: Retrieve uberjar artifact for ${{ matrix.edition }}
- name: Retrieve uberjar artifact for ${{ matrix.edition }}
uses: actions/download-artifact@v4
with:
name: metabase-${{ matrix.edition }}-uberjar
name: metabase-${{ matrix.edition }}-${{ github.event.pull_request.head.sha || github.sha }}-uberjar
- name: Get the version info
run: |
jar xf target/uberjar/metabase.jar version.properties
mv version.properties resources/
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- name: Prepare JDK ${{ matrix.java-version }}
uses: actions/setup-java@v4
with:
java-version: ${{ matrix.java-version }}
distribution: "temurin"
- name: Prepare Cypress environment
uses: ./.github/actions/prepare-cypress
- name: Run Snowplow micro
uses: ./.github/actions/run-snowplow-micro
- name: Run OSS-specific Cypress tests
if: matrix.edition == 'oss' && github.event_name != 'schedule'
run: |
yarn run test-cypress-run \
--env grepTags=@OSS \
--env grepTags=@OSS,grepOmitFiltered=true \
--spec './e2e/test/scenarios/**/*.cy.spec.js' \
--browser ${{ steps.setup-chrome.outputs.chrome-path }}
env:
TERM: xterm
--browser 'replay-chromium'
- name: Run EE Cypress tests on ${{ matrix.folder }}
if: matrix.edition == 'ee' && github.event_name != 'schedule'
- name: Run slow and resource-intensive Cypress tests
if: matrix.name == 'slow' && github.event_name != 'schedule'
run: |
yarn run test-cypress-run \
--env grepTags="-@quarantine" \
--folder ${{ matrix.folder }} \
--browser ${{ steps.setup-chrome.outputs.chrome-path }}
env:
TERM: xterm
# REPLAY.IO specific jobs
- name: Install Replay.io browser
if: ${{ github.event_name == 'schedule' }}
run: npx @replayio/cypress install
- name: Run OSS-specific Cypress tests using Replay.io browser
if: matrix.edition == 'oss' && github.event_name == 'schedule'
run: |
yarn run test-cypress-run \
--env grepTags=@OSS \
--env grepTags="@slow",grepOmitFiltered=true \
--spec './e2e/test/scenarios/**/*.cy.spec.js' \
--browser "replay-chromium"
env:
TERM: xterm
CYPRESS_REPLAYIO_ENABLED: 1
RECORD_REPLAY_METADATA_FILE: /tmp/replay-metadata.json
RECORD_REPLAY_METADATA_TEST_RUN_ID: ${{ needs.test-run-id.outputs.testRunId }}
--browser 'replay-chromium'
- name: Run EE Cypress tests on ${{ matrix.folder }} using Replay.io browser
if: matrix.edition == 'ee' && github.event_name == 'schedule'
- name: Run Flaky Cypress tests
if: matrix.name == 'flaky' && github.event_name != 'schedule'
run: |
yarn run test-cypress-run \
--env grepTags="-@quarantine" \
--folder ${{ matrix.folder }} \
--browser "replay-chromium"
env:
TERM: xterm
CYPRESS_REPLAYIO_ENABLED: 1
RECORD_REPLAY_METADATA_FILE: /tmp/replay-metadata.json
RECORD_REPLAY_METADATA_TEST_RUN_ID: ${{ needs.test-run-id.outputs.testRunId }}
--env grepTags="@flaky",grepOmitFiltered=true \
--spec './e2e/test/scenarios/**/*.cy.spec.js' \
--browser 'replay-chromium'
- name: Upload Replay.io recordings
if: github.event_name == 'schedule' && always()
uses: replayio/action-upload@v0.4.7
- name: Run EE Cypress tests on ${{ matrix.name }}
if: matrix.context == 'folder' && github.event_name != 'schedule'
run: |
yarn run test-cypress-run \
--env grepTags="-@slow+-@mongo+-@flaky --@quarantine",grepOmitFiltered=true \
--folder ${{ matrix.name }} \
--browser 'replay-chromium'
- name: Run E2E tests that depend on Mongo
if: matrix.name == 'mongo'
run: |
yarn run test-cypress-run \
--env grepTags="@mongo --@quarantine",grepOmitFiltered=true \
--spec './e2e/test/scenarios/**/*.cy.spec.js' \
--browser 'replay-chromium'
env:
CYPRESS_QA_DB_MONGO: true
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
with:
api-key: rwk_gXbvYctIcR6RZyEzUvby3gtkO4esrB2L321lkY8FSuQ
public: true
input-path: ./target/junit
output-name: e2e-${{ matrix.name }}
bucket: ${{ vars.AWS_S3_TEST_RESULTS_BUCKET }}
aws-access-key-id: ${{ secrets.AWS_TEST_RESULTS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_TEST_RESULTS_SECRET_ACCESS_KEY }}
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
- name: Upload Cypress Artifacts upon failure
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
if: failure()
with:
name: cypress-recording-${{ matrix.folder }}${{ matrix.context }}-${{ matrix.edition }}
name: cypress-recording-${{ matrix.name }}-${{ matrix.edition }}
path: |
./cypress
./logs/test.log
if-no-files-found: ignore
e2e-tests-skipped-stub:
needs: [build, files-changed]
needs: [e2e-tests, e2e-matrix-builder]
if: |
always() &&
needs.files-changed.outputs.e2e_all == 'false' &&
needs.build.result == 'skipped'
runs-on: ubuntu-22.04
!cancelled() &&
needs.e2e-tests.result == 'skipped'
runs-on: ${{ matrix.runner }}
timeout-minutes: 5
name: e2e-tests-${{ matrix.folder }}${{ matrix.context }}-${{ matrix.edition }}
name: e2e-tests-${{ matrix.name }}-${{ matrix.edition }}
strategy:
fail-fast: false
matrix:
java-version: [11]
edition: [ee]
folder:
- "auditing"
- "actions"
- "admin"
- "binning"
- "collections"
- "custom-column"
- "dashboard"
- "dashboard-filters"
- "embedding"
- "filters"
- "joins"
- "models"
- "native"
- "native-filters"
- "onboarding"
- "organization"
- "permissions"
- "question"
- "sharing"
- "visualizations"
include:
- edition: oss
context: grep
java-version: 11
matrix: ${{ fromJSON(needs.e2e-matrix-builder.outputs.matrix) }}
steps:
- run: |
echo "Didn't run due to conditional filtering"
@@ -310,45 +220,43 @@ jobs:
visual-regression-tests:
runs-on: ubuntu-22.04
timeout-minutes: 60
needs: build
if: ${{ github.event_name != 'schedule' }}
needs: [build]
if: |
!cancelled() && needs.build.result == 'success'
name: percy-visual-regression-tests
env:
MB_EDITION: ${{ matrix.edition }}
services:
maildev:
image: maildev/maildev:2.0.5
ports:
- "1080:1080"
- "1025:1025"
credentials:
steps:
- uses: actions/checkout@v4
- name: Prepare Docker containers
uses: ./.github/actions/e2e-prepare-containers
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
steps:
- uses: actions/checkout@v3
- name: Enable Percy recording on master only
if: github.ref == 'refs/heads/master'
run: |
echo "PERCY_TOKEN=${{ secrets.PERCY_TOKEN }}" >> $GITHUB_ENV
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- name: Prepare JDK 11
uses: actions/setup-java@v3
with:
java-version: 11
distribution: 'temurin'
- name: Prepare Cypress environment
uses: ./.github/actions/prepare-cypress
maildev: true
- uses: actions/download-artifact@v3
name: Retrieve uberjar artifact for ee
- name: Retrieve uberjar artifact for ${{ matrix.edition }}
uses: actions/download-artifact@v4
with:
name: metabase-ee-uberjar
name: metabase-ee-${{ github.event.pull_request.head.sha || github.sha }}-uberjar
- name: Get the version info
run: |
jar xf target/uberjar/metabase.jar version.properties
mv version.properties resources/
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- name: Prepare JDK 11
uses: actions/setup-java@v4
with:
java-version: 11
distribution: 'temurin'
- name: Prepare Cypress environment
uses: ./.github/actions/prepare-cypress
- name: Percy Test
run: yarn run test-visual-run
env:
PERCY_TOKEN: ${{ env.PERCY_TOKEN }}
PERCY_TOKEN: ${{ github.ref == 'refs/heads/master' && secrets.PERCY_TOKEN || ''}}

View File

@@ -11,7 +11,7 @@ jobs:
timeout-minutes: 10
steps:
- name: Format issue title (escape quotes)
uses: actions/github-script@v6
uses: actions/github-script@v7
id: vars
with:
script: |

View File

@@ -0,0 +1,57 @@
name: Frontend Unit Test Stress Test Flake Fix
on:
workflow_dispatch:
inputs:
spec:
description: 'Relative path of the target spec'
type: string
required: true
burn_in:
description: 'Number of times to run the test (e.g. 20)'
type: string
required: true
grep:
description: 'Grep and filter tests to run in isolation'
type: string
required: false
jobs:
workflow-summary:
name: Stress test inputs
runs-on: ubuntu-22.04
timeout-minutes: 5
steps:
- name: Generate workflow summary
run: |
echo '**Inputs:**' >> $GITHUB_STEP_SUMMARY
echo '' >> $GITHUB_STEP_SUMMARY
echo '- `branch`: ${{ github.ref_name }}' >> $GITHUB_STEP_SUMMARY
echo '- `spec`: ${{ inputs.spec }}' >> $GITHUB_STEP_SUMMARY
echo '- `burn_in`: ${{ inputs.burn_in }}' >> $GITHUB_STEP_SUMMARY
echo '- `grep`: "${{ inputs.grep }}"' >> $GITHUB_STEP_SUMMARY
echo '' >> $GITHUB_STEP_SUMMARY
echo 'triggered by: @${{ github.event.sender.login }}' >> $GITHUB_STEP_SUMMARY
frontend-unit-test-stress-test-flake-fix:
runs-on: ubuntu-22.04
timeout-minutes: 60
name: Stress test frontend unit test flake fix
steps:
- uses: actions/checkout@v4
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- name: Prepare back-end environment
uses: ./.github/actions/prepare-backend
with:
m2-cache-key: "cljs"
- name: Stress-test ${{ github.event.inputs.spec }} ${{ github.event.inputs.burn_in }} times
run: |
for i in {1..${{ github.event.inputs.burn_in }}}; do
yarn test-unit \
--testPathPattern '${{ github.event.inputs.spec }}' \
--testNamePattern '${{ github.event.inputs.grep }}'
if [[ "$?" != 0 ]]; then
echo "Failed after $i attempts" && break;
fi
done

View File

@@ -3,8 +3,8 @@ name: Frontend
on:
push:
branches:
- 'master'
- 'release-**'
- "master"
- "release-**"
pull_request:
types: [opened, synchronize, reopened, ready_for_review]
@@ -21,41 +21,33 @@ jobs:
frontend_all: ${{ steps.changes.outputs.frontend_all }}
e2e_specs: ${{ steps.changes.outputs.e2e_specs }}
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Test which files changed
uses: dorny/paths-filter@v2.11.1
uses: dorny/paths-filter@v3.0.0
id: changes
with:
token: ${{ github.token }}
filters: .github/file-paths.yaml
fe-linter-prettier:
needs: files-changed
if: needs.files-changed.outputs.frontend_all == 'true' || needs.files-changed.outputs.e2e_specs == 'true'
runs-on: ubuntu-22.04
timeout-minutes: 10
steps:
- uses: actions/checkout@v3
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- run: yarn run lint-prettier
name: Run Prettier formatting linter
fe-linter-eslint:
fe-lint:
needs: files-changed
if: needs.files-changed.outputs.frontend_all == 'true' || needs.files-changed.outputs.e2e_specs == 'true'
runs-on: ubuntu-22.04
timeout-minutes: 20
steps:
- uses: actions/checkout@v3
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- name: Prepare back-end environment
uses: ./.github/actions/prepare-backend
with:
m2-cache-key: 'cljs'
- run: yarn run lint-eslint
name: Run ESLint linter
- uses: actions/checkout@v4
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- name: Prepare back-end environment
uses: ./.github/actions/prepare-backend
with:
m2-cache-key: "cljs"
- name: Compile CLJS
run: yarn build-pure:cljs
- name: Run Prettier formatting linter
run: yarn run lint-prettier-pure
- name: Run ESLint linter
run: yarn run lint-eslint-pure
fe-type-check:
needs: files-changed
@@ -63,38 +55,57 @@ jobs:
runs-on: ubuntu-22.04
timeout-minutes: 10
steps:
- uses: actions/checkout@v3
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- name: Prepare back-end environment
uses: ./.github/actions/prepare-backend
with:
m2-cache-key: 'cljs'
- run: yarn build:cljs
name: Compile CLJS
- run: yarn type-check
name: Check types
- uses: actions/checkout@v4
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- name: Prepare back-end environment
uses: ./.github/actions/prepare-backend
with:
m2-cache-key: "cljs"
- run: yarn build-pure:cljs
name: Compile CLJS
- run: yarn type-check-pure
name: Check types
fe-tests-unit:
needs: files-changed
if: github.event.pull_request.draft == false && needs.files-changed.outputs.frontend_all == 'true'
runs-on: buildjet-2vcpu-ubuntu-2204
timeout-minutes: 60
env:
JEST_JUNIT_OUTPUT_DIR: ./target/junit
JEST_JUNIT_OUTPUT_NAME: test-report-frontend-unit.xml
steps:
- uses: actions/checkout@v3
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- name: Prepare back-end environment
uses: ./.github/actions/prepare-backend
with:
m2-cache-key: 'cljs'
- run: yarn run test-unit --coverage --silent
name: Run frontend unit tests
- name: Upload coverage to codecov.io
uses: codecov/codecov-action@v3
with:
files: ./coverage/lcov.info
flags: front-end
- uses: actions/checkout@v4
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- name: Prepare back-end environment
uses: ./.github/actions/prepare-backend
with:
m2-cache-key: "cljs"
- name: Run frontend unit tests and collect the code coverage information
if: github.ref_name == 'master'
run: yarn run test-unit --coverage --silent
- name: Run frontend unit tests
if: github.ref_name != 'master'
run: yarn run test-unit --silent
- name: Upload coverage to codecov.io
if: github.ref_name == 'master'
uses: codecov/codecov-action@v3
with:
files: ./coverage/lcov.info
flags: front-end
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
with:
input-path: ./target/junit
output-name: frontend-unit
bucket: ${{ vars.AWS_S3_TEST_RESULTS_BUCKET }}
aws-access-key-id: ${{ secrets.AWS_TEST_RESULTS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_TEST_RESULTS_SECRET_ACCESS_KEY }}
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
fe-tests-timezones:
needs: files-changed
@@ -102,37 +113,12 @@ jobs:
runs-on: ubuntu-22.04
timeout-minutes: 20
steps:
- uses: actions/checkout@v3
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- name: Prepare back-end environment
uses: ./.github/actions/prepare-backend
with:
m2-cache-key: 'cljs'
- run: yarn run test-timezones
name: Run frontend timezones tests
fe-chromatic:
needs: files-changed
if: github.event.pull_request.draft == false && needs.files-changed.outputs.frontend_all == 'true'
runs-on: ubuntu-22.04
steps:
- name: Checkout repository
uses: actions/checkout@v3
with:
fetch-depth: 0
- uses: actions/checkout@v4
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- name: Prepare back-end environment
uses: ./.github/actions/prepare-backend
with:
m2-cache-key: 'cljs'
- name: Publish to Chromatic
uses: chromaui/action@v1
env:
PUBLISH_CHROMATIC: ${{ secrets.CHROMATIC_PROJECT_TOKEN }}
STORYBOOK_BUILD_TIMEOUT: 900000
if: env.PUBLISH_CHROMATIC != null
with:
token: ${{ secrets.GITHUB_TOKEN }}
projectToken: ${{ secrets.CHROMATIC_PROJECT_TOKEN }}
m2-cache-key: "cljs"
- name: Run frontend timezones tests
run: yarn run test-timezones

View File

@@ -1,21 +1,23 @@
name: Fuzzing
on:
workflow_dispatch:
push:
branches:
- 'master'
- 'release-**'
paths:
- 'frontend/src/metabase-lib/expressions/**'
pull_request:
paths-ignore:
- 'docs/**'
paths:
- 'frontend/src/metabase-lib/expressions/**'
jobs:
fe-fuzz-tokenizer:
runs-on: ubuntu-22.04
timeout-minutes: 15
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- name: Prepare back-end environment
@@ -31,7 +33,7 @@ jobs:
runs-on: ubuntu-22.04
timeout-minutes: 15
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- name: Prepare back-end environment

View File

@@ -12,12 +12,28 @@ concurrency:
cancel-in-progress: true
jobs:
files-changed:
name: Check which files changed
runs-on: ubuntu-22.04
timeout-minutes: 3
outputs:
i18n: ${{ steps.changes.outputs.i18n }}
steps:
- uses: actions/checkout@v4
- name: Test which files changed
uses: dorny/paths-filter@v3.0.0
id: changes
with:
token: ${{ github.token }}
filters: .github/file-paths.yaml
verify-i18n-files:
needs: files-changed
if: needs.files-changed.outputs.i18n == 'true'
runs-on: ubuntu-22.04
timeout-minutes: 15
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- name: Prepare back-end environment

View File

@@ -13,7 +13,7 @@ jobs:
runs-on: ubuntu-22.04
timeout-minutes: 15
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Prepare back-end environment
uses: ./.github/actions/prepare-backend
with:

View File

@@ -14,19 +14,24 @@ jobs:
branch_name: ${{ fromJson(steps.fetch_pr.outputs.data).head.ref }}
commit_sha: ${{ fromJson(steps.fetch_pr.outputs.data).head.sha }}
steps:
- uses: tibdex/github-app-token@v1.6.0
- uses: tibdex/github-app-token@v2.1.0
id: generate-token
with:
app_id: ${{ secrets.METABASE_BOT_APP_ID }}
private_key: ${{ secrets.METABASE_BOT_APP_PRIVATE_KEY }}
- id: is_organization_member
uses: JamesSingleton/is-organization-member@1.0.0
- uses: actions/checkout@v4
with:
organization: metabase
username: ${{ github.event.issue.user.login }}
token: ${{ steps.generate-token.outputs.token }}
ref: ${{ needs.pr_info.outputs.branch_name }}
token: ${{ secrets.GITHUB_TOKEN }}
- name: Verify Membership
id: verify-membership
uses: ./.github/actions/verify-membership
with:
github_token: ${{ steps.generate-token.outputs.token }}
organization_name: metabase
username: ${{ github.event.comment.user.login }}
- run: |
result=${{ steps.is_organization_member.outputs.result }}
result=${{ steps.verify-membership.outputs.is_member }}
if [ $result == false ]; then
echo User ${{ github.event.comment.user.login }} is not a member of Metabase organization
exit 1
@@ -57,7 +62,7 @@ jobs:
CYPRESS_ALL_FEATURES_TOKEN: ${{ secrets.ENTERPRISE_TOKEN }}
CYPRESS_NO_FEATURES_TOKEN: ${{ secrets.E2E_STARTER_TOKEN }}
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
with:
ref: ${{ needs.pr_info.outputs.branch_name }}
token: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -17,7 +17,7 @@ jobs:
CYPRESS_ALL_FEATURES_TOKEN: ${{ secrets.ENTERPRISE_TOKEN }}
CYPRESS_NO_FEATURES_TOKEN: ${{ secrets.E2E_STARTER_TOKEN }}
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- name: Prepare back-end environment

View File

@@ -1,132 +1,90 @@
name: Pre-release [WIP]
name: Release 2 - Pre-release testing
run-name: Pre-release testing of ${{ inputs.version }}
on:
workflow_dispatch:
inputs:
version:
description: 'Metabase version (e.g. v0.46.3)'
type: string
required: true
commit:
description: 'A full-length commit SHA-1 hash'
required: true
version:
description: 'Intended version (e.g. v0.46.3)'
required: true
env:
MAX_HASH_LENGTH: 8
CUSTOM_REPO: ${{ secrets.CUSTOM_RELEASE_REPO }}
jobs:
check-commit:
release-artifact:
runs-on: ubuntu-22.04
timeout-minutes: 10
steps:
- name: Ensure that the intended version (${{ github.event.inputs.version }}) was never released before
run: |
if [[ "${{ github.event.inputs.version }}" = v* ]]; then
echo "Checking if ${{ github.event.inputs.version }} conflicts with a past release..."
else
echo "ERROR: the intended version must start with 'v', e.g. 'v0.46.3."
echo "ABORT!"
exit -1
fi
CANONICAL_REFS=https://github.com/metabase/metabase/archive/refs
URL=${CANONICAL_REFS}/tags/${{ github.event.inputs.version }}.zip
HTTP_CODE=$(curl -s -L -o /dev/null --head -w "%{HTTP_CODE}" ${URL})
if [[ $HTTP_CODE =~ "200" ]]; then
echo "ERROR: that version was already released in the past."
echo "ABORT!"
exit -1
else
if [[ $HTTP_CODE =~ "404" ]]; then
echo "That version has not been released yet."
echo "Proceeding to the next step..."
exit 0
else
echo "ERROR: Unhandled case of HTTP $HTTP_CODE while checking ${URL}"
echo "ABORT!"
exit -1
fi
fi
- name: Check out the code to verify the release branch
uses: actions/checkout@v3
with:
fetch-depth: 0 # IMPORTANT! to get all the branches
- name: Ensure that the specified commit exists in the latest release branch
run: |
echo "Checking if the specified commit is in a release branch..."
COMMIT=${{ github.event.inputs.commit }}
git branch -a --contains $COMMIT > branches.txt
if [[ $(grep -c master branches.txt) =~ 1 ]]; then
echo "Found in master branch. ABORT!"
exit -1
fi
if [[ $(grep -c 'release-x' branches.txt) =~ 1 ]]; then
echo "Found the commit $COMMIT in:"
git branch -a --contains $COMMIT
echo "Proceeding to the next step..."
exit 0
else
echo "Commit $COMMIT is not found in a single release branch"
echo "ABORT!."
exit -1
fi
build:
if: ${{ github.repository }} != 'metabase/metabase'
runs-on: ubuntu-22.04
needs: check-commit
name: Build Metabase ${{ matrix.edition }} @${{ github.event.inputs.commit }}
timeout-minutes: 40
strategy:
matrix:
edition: [oss, ee]
env:
MB_EDITION: ${{ matrix.edition }}
INTERACTIVE: false
outputs:
ee_version: ${{ steps.version-properties.outputs.ee_version }}
oss_version: ${{ steps.version-properties.outputs.oss_version }}
commit: ${{ steps.version-properties.outputs.commit }}
steps:
- name: Fail early if custom docker release repo is missing
if: ${{ env.CUSTOM_REPO == null }}
run: exit 1
- name: Check out the code
uses: actions/checkout@v3
with:
ref: ${{ github.event.inputs.commit }}
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- name: Prepare back-end environment
uses: ./.github/actions/prepare-backend
with:
m2-cache-key: pre-release-build
- name: find_release_artifact
id: find_release_artifact
uses: actions/github-script@v7
with:
result-encoding: string
script: | # js
const fs = require('fs');
- name: Determine the canonical version ## EE is always v1.x.y, OSS is always v0.x.y
uses: actions/github-script@v6
id: canonical_version
env:
INTENDED_VERSION: ${{ github.event.inputs.version }}
EDITION: ${{ matrix.edition }}
with:
result-encoding: string
script: |
var canonical_version;
const ver = process.env.INTENDED_VERSION;
if (process.env.EDITION === "ee") {
canonical_version = ver.replace(/^v0\./, "v1."); // always e.g. v1.47.2
} else {
canonical_version = ver.replace(/^v1\./, "v0."); // always e.g. v0.45.6
}
console.log("The canonical version of this", process.env.EDITION, "edition is", canonical_version);
return canonical_version;
const artifacts = await github.rest.actions.listArtifactsForRepo({
owner: context.repo.owner,
repo: context.repo.repo,
name: `metabase-release-${{ matrix.edition }}-${{ inputs.commit }}-uberjar`,
per_page: 1,
});
- name: Build
run: ./bin/build.sh :edition :${{ matrix.edition }} :version ${{ steps.canonical_version.outputs.result }}
if (!artifacts.data?.artifacts?.[0]?.id) {
throw new Error(`No artifacts found for ${{ inputs.commit }}`);
}
- name: Prepare uberjar artifact
uses: ./.github/actions/prepare-uberjar-artifact
const artifact_id = artifacts.data.artifacts[0].id;
const download = await github.rest.actions.downloadArtifact({
owner: context.repo.owner,
repo: context.repo.repo,
artifact_id: artifact_id,
archive_format: 'zip',
});
fs.writeFileSync(`${process.env.GITHUB_WORKSPACE}/mb.zip`, Buffer.from(download.data));
- name: Unzip Metabase artifact containing an uberjar
run: unzip mb.zip
- name: Extract the version.properties file from the JAR
run: |
jar xf metabase.jar version.properties
- name: Reveal Metabase ${{ matrix.edition }} properties
id: version-properties
run: |
cat version.properties
echo "commit=$(cat ./COMMIT-ID)" >> $GITHUB_OUTPUT
version=$(grep -o '^tag=.*' version.properties | cut -d'=' -f2)
if [[ "${{ matrix.edition }}" == "ee" ]]; then
echo "ee_version=$version" >> $GITHUB_OUTPUT
else
echo "oss_version=$version" >> $GITHUB_OUTPUT
fi
shell: bash
- name: Upload Metabase ${{ matrix.edition }} JAR as artifact
uses: actions/upload-artifact@v4
with:
name: metabase-${{ matrix.edition }}-uberjar
path: |
./metabase.jar
./COMMIT-ID
./SHA256.sum
check-uberjar-health:
needs: [release-artifact]
runs-on: ubuntu-22.04
name: Is ${{ matrix.edition }} (java ${{ matrix.java-version }}) healthy?
needs: build
timeout-minutes: 10
strategy:
matrix:
@@ -134,25 +92,25 @@ jobs:
java-version: [11, 17]
steps:
- name: Prepare JRE (Java Run-time Environment)
uses: actions/setup-java@v3
uses: actions/setup-java@v4
with:
java-package: jre
java-version: ${{ matrix.java-version }}
distribution: 'temurin'
- run: java -version
- uses: actions/download-artifact@v3
- uses: actions/download-artifact@v4
name: Retrieve uberjar artifact
with:
name: metabase-${{ matrix.edition }}-uberjar
- name: Launch uberjar (and keep it running)
run: java -jar ./target/uberjar/metabase.jar &
run: java -jar ./metabase.jar &
- name: Wait for Metabase to start
run: while ! curl -s 'http://localhost:3000/api/health' | grep '{"status":"ok"}'; do sleep 1; done
run-sanity-check:
runs-on: ubuntu-22.04
timeout-minutes: 15
needs: check-uberjar-health
timeout-minutes: 30
needs: [release-artifact, check-uberjar-health]
strategy:
matrix:
edition: [oss, ee]
@@ -163,6 +121,7 @@ jobs:
CYPRESS_NO_FEATURES_TOKEN: ${{ secrets.E2E_STARTER_TOKEN }}
MB_SNOWPLOW_AVAILABLE: true
MB_SNOWPLOW_URL: "http://localhost:9090" # Snowplow micro
TERM: xterm
services:
maildev:
image: maildev/maildev:2.0.5
@@ -174,13 +133,13 @@ jobs:
password: ${{ secrets.DOCKERHUB_TOKEN }}
steps:
- name: Check out the code
uses: actions/checkout@v3
uses: actions/checkout@v4
with:
ref: ${{ github.event.inputs.commit }}
ref: ${{ needs.release-artifact.outputs.commit }}
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- name: Prepare JDK 11
uses: actions/setup-java@v3
uses: actions/setup-java@v4
with:
java-version: 11
distribution: "temurin"
@@ -188,20 +147,21 @@ jobs:
uses: ./.github/actions/prepare-cypress
- name: Run Snowplow micro
uses: ./.github/actions/run-snowplow-micro
- uses: actions/download-artifact@v3
- uses: actions/download-artifact@v4
name: Retrieve uberjar artifact for ${{ matrix.edition }}
with:
name: metabase-${{ matrix.edition }}-uberjar
- name: Get the version info
run: |
jar xf target/uberjar/metabase.jar version.properties
jar xf metabase.jar version.properties
mv version.properties resources/
- name: Run a few important Cypress tests as sanity check
run: yarn test-cypress-run --folder onboarding
env:
TERM: xterm
run: |
mkdir -p ./target/uberjar && cp metabase.jar ./target/uberjar/metabase.jar
yarn test-cypress-run --folder onboarding
- name: Upload Cypress Artifacts upon failure
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
if: failure()
with:
name: cypress-failed-tests-recording
@@ -211,8 +171,8 @@ jobs:
if-no-files-found: ignore
containerize:
needs: [release-artifact, run-sanity-check]
runs-on: ubuntu-22.04
needs: run-sanity-check
timeout-minutes: 15
strategy:
matrix:
@@ -222,24 +182,26 @@ jobs:
image: registry:2
ports:
- 5000:5000
outputs:
image_tag: ${{ steps.target.outputs.image_tag }}
steps:
- name: Check out the code
uses: actions/checkout@v3
with:
ref: ${{ github.event.inputs.commit }}
- name: Truncate commit hash
- name: Get the version
run: |
commit_id=${{ github.event.inputs.commit }}
truncated_hash=${commit_id:0:${{ env.MAX_HASH_LENGTH }}}
echo "COMMIT_IDENTIFIER=$truncated_hash" >> $GITHUB_ENV
shell: bash
- uses: actions/download-artifact@v3
if [[ "${{ matrix.edition }}" == "ee" ]]; then
echo "VERSION=${{ needs.release-artifact.outputs.ee_version }}" >> $GITHUB_ENV
else
echo "VERSION=${{ needs.release-artifact.outputs.oss_version }}" >> $GITHUB_ENV
fi
- name: Check out the code
uses: actions/checkout@v4
with:
ref: ${{ needs.release-artifact.outputs.commit }}
- uses: actions/download-artifact@v4
name: Retrieve uberjar artifact
with:
name: metabase-${{ matrix.edition }}-uberjar
- name: Move the Uberjar to the context dir
run: mv ./target/uberjar/metabase.jar bin/docker/.
run: mv metabase.jar bin/docker/.
- name: Set up Docker Buildx
id: buildx
uses: docker/setup-buildx-action@v2
@@ -251,12 +213,12 @@ jobs:
context: bin/docker/.
platforms: linux/amd64
network: host
tags: localhost:5000/local-metabase:${{ env.COMMIT_IDENTIFIER }}-${{ matrix.edition }}
tags: localhost:5000/local-metabase:${{ env.VERSION }}
no-cache: true
push: true
- name: Launch container
run: docker run --rm -dp 3000:3000 localhost:5000/local-metabase:${{ env.COMMIT_IDENTIFIER }}-${{ matrix.edition }}
run: docker run --rm -dp 3000:3000 localhost:5000/local-metabase:${{ env.VERSION }}
timeout-minutes: 5
- name: Wait for Metabase to start
run: while ! curl -s 'http://localhost:3000/api/health' | grep '{"status":"ok"}'; do sleep 1; done
@@ -267,48 +229,53 @@ jobs:
with:
username: ${{ secrets.DOCKERHUB_RELEASE_USERNAME }}
password: ${{ secrets.DOCKERHUB_RELEASE_TOKEN }}
- name: Determine the target Docker Hub repository
- name: Retag and push container image to ${{ vars.DOCKERHUB_OWNER }} staging Docker Hub repo
id: target
run: |
echo "DOCKERHUB_REPO=${{ github.repository_owner }}/${{ env.CUSTOM_REPO }}" >> $GITHUB_ENV
echo "IMAGE_NAME=${{ env.COMMIT_IDENTIFIER }}-${{ matrix.edition }}" >> $GITHUB_ENV
- name: Retag and push container image to Docker Hub
run: |
echo "Pushing container image ${{ env.IMAGE_NAME}} to ${{ env.DOCKERHUB_REPO }} ..."
docker tag localhost:5000/local-metabase:${{ env.IMAGE_NAME }} ${{ env.DOCKERHUB_REPO }}:${{ env.IMAGE_NAME }}
docker push ${{ env.DOCKERHUB_REPO }}:${{ env.IMAGE_NAME }}
# SHA-1 truncated to 7 digits should be enough
SHORT_HASH=${COMMIT:0:7}
IMAGE_TAG=$VERSION-$SHORT_HASH
CONTAINER_IMAGE=${{ vars.DOCKERHUB_OWNER }}/${{ vars.DOCKERHUB_STAGING_REPO }}:$IMAGE_TAG
echo "image_tag=$IMAGE_TAG" >> $GITHUB_OUTPUT
echo "Retag local image for staging"
docker tag localhost:5000/local-metabase:$VERSION $CONTAINER_IMAGE
echo "Pushing container image $CONTAINER_IMAGE ..."
docker push $CONTAINER_IMAGE
echo "Finished!"
shell: bash
env:
COMMIT: ${{ needs.release-artifact.outputs.commit }}
verify-docker-pull:
runs-on: ubuntu-22.04
needs: containerize
needs: [release-artifact, containerize]
timeout-minutes: 15
strategy:
matrix:
edition: [oss, ee]
env:
IMAGE_TAG: ${{ needs.containerize.outputs.image_tag }}
steps:
- name: Truncate commit hash
run: |
commit_id=${{ github.event.inputs.commit }}
truncated_hash=${commit_id:0:${{ env.MAX_HASH_LENGTH }}}
echo "COMMIT_IDENTIFIER=$truncated_hash" >> $GITHUB_ENV
shell: bash
- name: Login to Docker Hub # authenticated, to avoid being rate-throttled
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKERHUB_RELEASE_USERNAME }}
password: ${{ secrets.DOCKERHUB_RELEASE_TOKEN }}
- name: Determine the container image to pull
run: |
echo "DOCKERHUB_REPO=${{ github.repository_owner }}/${{ env.CUSTOM_REPO }}" >> $GITHUB_ENV
echo "IMAGE_NAME=${{ env.COMMIT_IDENTIFIER }}-${{ matrix.edition }}" >> $GITHUB_ENV
- name: Pull the container image
run: |
echo "Pulling container image ${{ env.DOCKERHUB_REPO }}:${{ env.IMAGE_NAME }} ..."
docker pull ${{ env.DOCKERHUB_REPO }}:${{ env.IMAGE_NAME }}
CONTAINER_IMAGE=${{ vars.DOCKERHUB_OWNER }}/${{ vars.DOCKERHUB_STAGING_REPO }}:$IMAGE_TAG
echo "Pulling container image $CONTAINER_IMAGE ..."
docker pull $CONTAINER_IMAGE
echo "Successful!"
- name: Launch container
run: docker run --rm -dp 3000:3000 ${{ env.DOCKERHUB_REPO }}:${{ env.IMAGE_NAME }}
run: |
CONTAINER_IMAGE=${{ vars.DOCKERHUB_OWNER }}/${{ vars.DOCKERHUB_STAGING_REPO }}:$IMAGE_TAG
docker run --rm -dp 3000:3000 $CONTAINER_IMAGE
timeout-minutes: 5
- name: Wait for Metabase to start
run: while ! curl -s 'http://localhost:3000/api/health' | grep '{"status":"ok"}'; do sleep 1; done

View File

@@ -18,9 +18,9 @@ jobs:
outputs:
backend_presto_kerberos: ${{ steps.changes.outputs.backend_presto_kerberos }}
steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Test which files changed
uses: dorny/paths-filter@v2.11.1
uses: dorny/paths-filter@v3.0.0
id: changes
with:
token: ${{ github.token }}
@@ -41,11 +41,11 @@ jobs:
&& sudo ./install \
&& cd -
- name: Checkout Metabase repository
uses: actions/checkout@v3
uses: actions/checkout@v4
with:
token: ${{ secrets.GITHUB_TOKEN }}
- name: Check out Presto Kerberos Docker Compose
uses: actions/checkout@v3
uses: actions/checkout@v4
with:
repository: metabase/presto-kerberos-docker
ref: master
@@ -64,7 +64,7 @@ jobs:
- name: Copy client.keytab file to resources
run: docker cp presto-kerberos:/home/presto/client.keytab resources
- name: Checkout mba
uses: actions/checkout@v3
uses: actions/checkout@v4
with:
repository: metabase/mba
ref: master

View File

@@ -0,0 +1,45 @@
name: Pull Request Reminders
on:
pull_request:
types: [opened]
branches:
- "master"
jobs:
external-reminder:
name: External PR Helper
if: ${{ github.event.pull_request.head.repo.full_name != github.repository }}
runs-on: ubuntu-22.04
timeout-minutes: 5
permissions:
pull-requests: write
issues: read
steps:
- uses: actions/github-script@v7
with:
script: | # js
const owner = context.repo.owner;
const repo = context.repo.repo;
const pullNumber = '${{ github.event.pull_request.number }}';
const author = '${{ github.event.pull_request.user.login }}';
await github.rest.issues.addLabels({
owner,
repo,
issue_number: pullNumber,
labels: ["External"],
});
const guideLink = "https://www.notion.so/metabase/Third-Party-PRs-External-contributions-5954061854424c1ea6391d98746646e0";
const message = `@${author} Thanks for your contribution! ❤️ We'll try to review it as soon as we can.\n\n
Reviewers, make sure to check out our [External PR Review Guide](${guideLink}) when reviewing.
`;
await github.rest.issues.createComment({
owner,
repo,
issue_number: pullNumber,
body: message,
});

40
.github/workflows/release-status.yml vendored Normal file
View File

@@ -0,0 +1,40 @@
name: Release Status Check
on:
workflow_dispatch:
schedule:
- cron: '0 13 * * *' # every day at 8am US eastern time
jobs:
check-release-status:
runs-on: ubuntu-22.04
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
with:
sparse-checkout: release
- name: Prepare build scripts
run: cd ${{ github.workspace }}/release && yarn --frozen-lockfile && yarn build
- name: Check release status and post to Slack
uses: actions/github-script@v7
env:
SLACK_BOT_TOKEN: ${{ secrets.SLACK_BOT_TOKEN }}
SLACK_RELEASE_CHANNEL: ${{ vars.SLACK_RELEASE_CHANNEL }}
with:
script: | # js
const { checkReleaseStatus } = require('${{ github.workspace }}/release/dist/index.cjs');
if (!process.env.SLACK_BOT_TOKEN) {
throw new Error('SLACK_BOT_TOKEN is required');
}
if (!process.env.SLACK_RELEASE_CHANNEL) {
throw new Error('SLACK_RELEASE_CHANNEL is required');
}
const ossReleased = await checkReleaseStatus({
github,
owner: context.repo.owner,
repo: context.repo.repo,
channelName: process.env.SLACK_RELEASE_CHANNEL,
});

Some files were not shown because too many files have changed in this diff Show More