* 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>
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.
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.
* 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>
* 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
* 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>
* 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
* 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>
* 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>
`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.
* 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>
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.
* 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>
* 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>
* 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.
* 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>
* 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
* [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
* 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>
* 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
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.
* 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
* 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/`
* Fix ESlint from the result of upgrading ESLint package
* Support `component` prop on Mantine
* Prevent accidental ESLint log in Cypress
* Upgrade ESLint rule
* 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
* 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
* 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>
* 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>
* 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.
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.
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.
* 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`
* 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
* 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
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.
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.
* 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
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.
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.
* 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>
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>
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>
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
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
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
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.
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.
* 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
* Support converting aggregation references to legacy references
* Pass query and stageIndex to legacyQuery
---------
Co-authored-by: Alexander Polyankin <alexander.polyankin@metabase.com>
* 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
* 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)
* 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
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.
* 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
* 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
* 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
* 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
* [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
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.
* 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
* 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
* Revert "Remove internal query check (#37587)"
This reverts commit 16aa9974fb.
* Add a comment
Explains why the guard against `internal` queries is needed here.
* 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
* 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
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.
* 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>
* 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
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.
* 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>
- 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.
* 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
* 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
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.
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.
* 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
* Turn `Dashboard` into a functional component
* Fix loading
* Fix loading
* Properly type `fetchDashboard` result
* Update `tabHasCards` check
* Group data fetching `useEffects` into one
* 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>
* 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>
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.
- 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
* Migrate `_serializeForUrl` method to MLv2
* Use MLv2 function to compare queries
---------
Co-authored-by: Alexander Polyankin <alexander.polyankin@metabase.com>
* 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>
* 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.
* 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>
* 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>
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.
* 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
* 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>
* 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>
* 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>
* 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
`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>
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.
* 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
* 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>
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.
* [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
* 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
* 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
* 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>
* 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
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.
* 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
* 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
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.
* 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)
* 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
* 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!
* 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>
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`.
* 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
* Migrate `isEmpty` check for structured queries in DatasetEditor
Resolves#37515
* Remove `isEmpty` method from StructuredQuery
* Remove related unit test
* 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>
* 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`
* 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]}
* 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>
* 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
* 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.
* 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
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
* 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>
* 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
* 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
* 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.
* 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
* 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>
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.
#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`
* 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>
* 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
* 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.
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)))))
```
* 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
* [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>
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.
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.
* 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]
* 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.
* 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
* 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>
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.
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.
* 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
* 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.
* 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.
* 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>
* 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
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.
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.
* 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>
* 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>
* 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
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.
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.
* 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
* 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.
* 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
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`).
- 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.
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.
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.
* 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>
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
* 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
* 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
* 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
* 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.
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.
@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.
* 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>
* 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
* 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.
* 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>
* Bump dependencies based on vulnerabilities
* More deps bumped
* Bump more deps
* Rollback H2 dependency bump
* Add comments and make guava match elsewhere.
* 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
* 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
* 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
* 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.
* 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
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.
* Revert "Temporarily skip server-side-relative-datetime-honeysql-form (#36567)"
This reverts commit 769b5eb439.
This was not flaking.
* Skip test that flakes
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.
* 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.
* 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
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.
* 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
* 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
* 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
* 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
* 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
* 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>
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.
* 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
* 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>
* 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
* 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.
* 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.
* 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
* 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.
* 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
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.
* 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
* 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
* 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>
* 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>
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.
* `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>
* 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>
This replaces the existing setting max-results-bare-rows with two settings:
- `max-unaggregated-query-row-limit`, and
- `max-aggregated-query-row-limit`
* 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>
* 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>
* QueryBuild and SQL questions: hide Explore results with parameters
* Fix AtomicQuery.canNest return type (so that it is always boolean)
* Add Question.canExploreResults tests
* 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
* 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
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>
* [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
* Update Admin User Form to use Formik
* typing LoginAttributesWidget
* Making first and last name not required
* PR Feedback
* adding unit tests
* fixing email selector
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>
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.
* 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.
* 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
* 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
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.
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.
* 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
* 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
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.
* 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>
* 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>
* 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
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
* 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
* 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.
* 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>
* 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>
* 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.
* 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
* 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>
* 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
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.
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.
* 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.
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.
* 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>
* 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
* 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
* 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
* 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
* 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
* 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]
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.
* 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
* 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>
* 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>
* 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
* 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
* 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
* [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>
* 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]
* 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.
* 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.
* 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
* 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
* 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`.
* 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
* 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.
* 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
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
`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.
* 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
* 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`.
* 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)
* 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
```
* 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
* 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>
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.
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
* 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.
```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.
* 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
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
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} ...)
```
* 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
* 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
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.
* 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>
* 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
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
* 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
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>
* 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.
* 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
* 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
* 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.
* 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
* 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
* 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
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.
* 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>
* 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
* 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>
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.
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
* 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
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`.
* 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
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
* 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
* 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
* 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
* 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-R332https://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>
* 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>
### 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.
* 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
* 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
* 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
* 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
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.
`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.
* 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
* 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?
* 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
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.
* 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?
* 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
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.
* 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
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
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.
* 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>
* 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
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.
* 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>
* 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.
* 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>
* 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>
* 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.
* 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>
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
* 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
* 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.
* [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>
* [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
* 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`
* 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
* 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
* 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>
* [PivotTable] Skip unnecessary rendering
* Update imports
* Oops. no need to render children 3 times
* Rename prop isScrolling -> showTooltip
* Rename hook parameter
* Delete test
* 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>
* 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
* 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>
* [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
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.
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
* 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>
* 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
* 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]
* 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
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]
* 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>
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.
* 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
# 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>
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.
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]
* 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
* 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 🔧
* 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>
* 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
* 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
* 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>
* 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
* 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>
* 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
* 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
* 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>
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.
* 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>
* 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
* 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
* 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
* 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
* 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
* 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>
* 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
* 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
* 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`
* 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
* 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>
* 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>
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.
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.
* 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
* 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.
* Drills migration preparation - unified types, moved Mode, detached actions from drills
* Click actions components renaming
* Moved Automatic Insights back to drills
* 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
* Fix `filterClause` return type
* Add `FilterOperatorDisplayInfo`
* Make `ColumnWithOperators` a subset of `ColumnMetadata`
* Fix `ExternalOp` marked as opaque
* Use `ColumnMetadata` in `ExternalOp` `args`
* 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
* 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
* 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
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
* 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`
* 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
* 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
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.
* 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>
* 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>
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>
* 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>
* 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
* 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
* 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
* 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>
* 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
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
* 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>
* 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>
* 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`
{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"}}
(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"
> 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.
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
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.