Skip to content

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

403 KB
Raw Blame
databaseChangeLog:
  - objectQuotingStrategy: QUOTE_ALL_OBJECTS

  - changeSet:
      id: v00.00-000
      validCheckSum: 8:a59595109e74e7a2678a1b0dfd25f74a
      author: qnkhuat
      comment: Initialze metabase
      preConditions:
        - onFail: MARK_RAN
        - not:
          - tableExists: ## Have to manually check since the changest ids don't always match
              tableName: core_user
      changes:
        - sqlFile:
            dbms: postgresql
            path: initialization/metabase_postgres.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: initialization/metabase_mysql.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: initialization/metabase_h2.sql
            relativeToChangelogFile: true

# Note on rollback: migrations for v45 onwards should always include a rollback key unless they are supported
# by Liquibase Auto Rollback. Most common changes are supported. See docs here:
#
#  https://docs.liquibase.com/workflows/liquibase-community/liquibase-auto-rollback.html

  - changeSet:
      id: v45.00-001
      validCheckSum: 8:da99b71a4ac7eb662f6a95e69585935e
      author: snoe
      comment: Added 0.44.0 - writeback
      # This migration was previously numbered v44.00-012 but ultimately was not shipped with 44.
      preConditions:
        - onFail: MARK_RAN
        - or:
            # For some insane reason databasechangelog is upper-case in MySQL and MariaDB.
            - and:
                - dbms:
                    type: postgresql,h2
                - sqlCheck:
                    expectedResult: 0
                    sql: SELECT count(*) FROM databasechangelog WHERE id = 'v44.00-012';
            - and:
                - dbms:
                    type: mysql,mariadb
                - sqlCheck:
                    expectedResult: 0
                    sql: SELECT count(*) FROM `DATABASECHANGELOG` WHERE id = 'v44.00-012';
      changes:
        - createTable:
            tableName: action
            remarks: An action is something you can do, such as run a readwrite query
            columns:
              - column:
                  name: id
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  remarks: The timestamp of when the action was created
                  name: created_at
                  type: ${timestamp_type}
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false
              - column:
                  remarks: The timestamp of when the action was updated
                  name: updated_at
                  type: ${timestamp_type}
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false
              - column:
                  remarks: Type of action
                  name: type
                  type: ${text.type}
                  constraints:
                    nullable: false

  - changeSet:
      id: v45.00-002
      validCheckSum: 8:6da7a6285edb138c404de0eeba209570
      author: snoe
      comment: Added 0.44.0 - writeback
      # This migration was previously numbered v44.00-013 but ultimately was not shipped with 44.
      preConditions:
        - onFail: MARK_RAN
        - or:
            # For some insane reason databasechangelog is upper-case in MySQL and MariaDB.
            - and:
                - dbms:
                    type: postgresql,h2
                - sqlCheck:
                    expectedResult: 0
                    sql: SELECT count(*) FROM databasechangelog WHERE id = 'v44.00-013';
            - and:
                - dbms:
                    type: mysql,mariadb
                - sqlCheck:
                    expectedResult: 0
                    sql: SELECT count(*) FROM `DATABASECHANGELOG` WHERE id = 'v44.00-013';
      changes:
        - createTable:
            tableName: query_action
            remarks: A readwrite query type of action
            columns:
              - column:
                  name: action_id
                  type: int
                  remarks: The related action
                  constraints:
                    nullable: false
                    referencedTableName: action
                    referencedColumnNames: id
                    foreignKeyName: fk_query_action_ref_action_id
                    deleteCascade: true
              - column:
                  name: card_id
                  type: int
                  remarks: The related card
                  constraints:
                    nullable: false
                    referencedTableName: report_card
                    referencedColumnNames: id
                    foreignKeyName: fk_query_action_ref_card_id
                    deleteCascade: true

  - changeSet:
      id: v45.00-003
      validCheckSum: 8:512337d6d4af38016aa79585abbe03a1
      author: snoe
      comment: Added 0.44.0 - writeback
      # This migration was previously numbered v44.00-014 but ultimately was not shipped with 44.
      preConditions:
        - onFail: MARK_RAN
        - or:
            # For some insane reason databasechangelog is upper-case in MySQL and MariaDB.
            - and:
                - dbms:
                    type: postgresql,h2
                - sqlCheck:
                    expectedResult: 0
                    sql: SELECT count(*) FROM databasechangelog WHERE id = 'v44.00-014';
            - and:
                - dbms:
                    type: mysql,mariadb
                - sqlCheck:
                    expectedResult: 0
                    sql: SELECT count(*) FROM `DATABASECHANGELOG` WHERE id = 'v44.00-014';
      changes:
        - addPrimaryKey:
            tableName: query_action
            columnNames: action_id, card_id
            constraintName: pk_query_action
      rollback: # will be deleted when table is deleted

  # note: some migrations which only added and deleted tables within v45 were removed, hence an ID gap here

  - changeSet:
      id: v45.00-011
      validCheckSum: 8:dcf1cda9f20dca4b6ff8101b13b98c4a
      author: snoe
      comment: Added 0.44.0 - writeback
      # This migration was previously numbered v44.00-022 but ultimately was not shipped with 44.
      preConditions:
        - onFail: MARK_RAN
        - or:
            # For some insane reason databasechangelog is upper-case in MySQL and MariaDB.
            - and:
                - dbms:
                    type: postgresql,h2
                - sqlCheck:
                    expectedResult: 0
                    sql: SELECT count(*) FROM databasechangelog WHERE id = 'v44.00-022';
            - and:
                - dbms:
                    type: mysql,mariadb
                - sqlCheck:
                    expectedResult: 0
                    sql: SELECT count(*) FROM `DATABASECHANGELOG` WHERE id = 'v44.00-022';
      changes:
        - addColumn:
            columns:
              - column:
                  name: is_write
                  type: boolean
                  defaultValueBoolean: false
                  remarks: Indicates that this query will perform writes to a db
                  constraints:
                    nullable: false
            tableName: report_card

  - changeSet:
      id: v45.00-012
      validCheckSum: 8:aadf28229f585cff7c4b4c1918e558b2
      author: snoe
      comment: Added 0.44.0 - writeback
      # This migration was previously numbered v44.00-031 but ultimately was not shipped with 44.
      preConditions:
        - onFail: MARK_RAN
        - or:
            # For some insane reason databasechangelog is upper-case in MySQL and MariaDB.
            - and:
                - dbms:
                    type: postgresql,h2
                - sqlCheck:
                    expectedResult: 0
                    sql: SELECT count(*) FROM databasechangelog WHERE id = 'v44.00-031';
            - and:
                - dbms:
                    type: mysql,mariadb
                - sqlCheck:
                    expectedResult: 0
                    sql: SELECT count(*) FROM `DATABASECHANGELOG` WHERE id = 'v44.00-031';
      changes:
        - createTable:
            tableName: http_action
            remarks: An http api call type of action
            columns:
              - column:
                  name: action_id
                  type: int
                  remarks: The related action
                  constraints:
                    nullable: false
                    referencedTableName: action
                    referencedColumnNames: id
                    foreignKeyName: fk_http_action_ref_action_id
                    deleteCascade: true
              - column:
                  name: name
                  type: varchar(254)
                  remarks: The name of this action
                  constraints:
                    nullable: false
              - column:
                  name: description
                  type: ${text.type}
                  remarks: An optional description for this action
              - column:
                  name: template
                  type: ${text.type}
                  remarks: A template that defines method,url,body,headers required to make an api call
                  constraints:
                    nullable: false
              - column:
                  name: response_handle
                  type: ${text.type}
                  remarks: A program to take an api response and transform to an appropriate response for emitters
              - column:
                  name: error_handle
                  type: ${text.type}
                  remarks: A program to take an api response to determine if an error occurred

  - changeSet:
      id: v45.00-013
      validCheckSum: 8:26dba276b14255d4346507a1a25d117b
      author: snoe
      comment: Added 0.44.0 - writeback
      # This migration was previously numbered v44.00-032 but ultimately was not shipped with 44.
      preConditions:
        - onFail: MARK_RAN
        - or:
            # For some insane reason databasechangelog is upper-case in MySQL and MariaDB.
            - and:
                - dbms:
                    type: postgresql,h2
                - sqlCheck:
                    expectedResult: 0
                    sql: SELECT count(*) FROM databasechangelog WHERE id = 'v44.00-032';
            - and:
                - dbms:
                    type: mysql,mariadb
                - sqlCheck:
                    expectedResult: 0
                    sql: SELECT count(*) FROM `DATABASECHANGELOG` WHERE id = 'v44.00-032';
      changes:
        - addPrimaryKey:
            tableName: http_action
            columnNames: action_id
            constraintName: pk_http_action
      rollback: # no rollback needed, will be deleted with table


  # note: some migrations which only added and deleted tables within v45 were removed, hence an ID gap here

  - changeSet:
      id: v45.00-022
      validCheckSum: 8:d46fa24e4d75a11b2e92aecbf39c6ee1
      author: snoe
      comment: Added 0.45.0 - add app container
      changes:
        - createTable:
            tableName: app
            remarks: Defines top level concerns for App
            columns:
              - column:
                  name: id
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: entity_id
                  type: char(21)
                  remarks: Random NanoID tag for unique identity.
                  constraints:
                    nullable: false
                    unique: true
              - column:
                  name: collection_id
                  type: int
                  remarks: The associated collection
                  constraints:
                    nullable: false
                    referencedTableName: collection
                    referencedColumnNames: id
                    foreignKeyName: fk_app_ref_collection_id
                    deleteCascade: true
                    unique: true
              - column:
                  name: dashboard_id
                  type: int
                  remarks: The homepage of the app
              - column:
                  remarks: JSON for the navigation items of the app
                  name: nav_items
                  type: ${text.type}
              - column:
                  remarks: JSON for frontend related additions, such as styling
                  name: options
                  type: ${text.type}
              - column:
                  remarks: The timestamp of when the app was created
                  name: created_at
                  type: ${timestamp_type}
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false
              - column:
                  remarks: The timestamp of when the app was updated
                  name: updated_at
                  type: ${timestamp_type}
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false

  - changeSet:
      id: v45.00-023
      validCheckSum: 8:c6c1ff9ca3b62d4cda3a2d782dd86f2f
      author: snoe
      comment: Added 0.45.0 - add app container
      changes:
        - addForeignKeyConstraint:
            baseTableName: app
            baseColumnNames: dashboard_id
            referencedTableName: report_dashboard
            referencedColumnNames: id
            constraintName: fk_app_ref_dashboard_id
            onDelete: SET NULL

  - changeSet:
      id: v45.00-025
      validCheckSum: 8:50a43cea3123ecdb602123825f5a7dbf
      author: metamben
      comment: Added 0.45.0 - mark app pages
      changes:
        - addColumn:
            columns:
              - column:
                  name: is_app_page
                  type: boolean
                  defaultValueBoolean: false
                  remarks: Indicates that this dashboard serves as a page of an app
                  constraints:
                    nullable: false
            tableName: report_dashboard

  - changeSet:
      id: v45.00-026
      validCheckSum: 8:ae77d4086998911877e3207fcf90c9c7
      author: snoe
      comment: Added 0.45.0 - apps add action_id to report_dashboardcard
      changes:
        - addColumn:
            columns:
              - column:
                  name: action_id
                  type: int
                  remarks: The related action
            tableName: report_dashboardcard

  # FK constraint is added separately because deleteCascade doesn't work in addColumn -- see #14321
  - changeSet:
      id: v45.00-027
      validCheckSum: 8:40c3c8391c1416a3bce09ca3c7237173
      author: snoe
      comment: Added 0.45.0 - apps add fk for action_id to report_dashboardcard
      changes:
        - addForeignKeyConstraint:
            baseTableName: report_dashboardcard
            baseColumnNames: action_id
            referencedTableName: action
            referencedColumnNames: id
            constraintName: fk_report_dashboardcard_ref_action_id
            onDelete: CASCADE

  - changeSet:
      id: v45.00-028
      validCheckSum: 8:f8f68f80627aeb2ef7f28f2af2b5a31b
      author: camsaul
      comment: Added 0.45.0 -- rename DashboardCard sizeX to size_x. See https://github.com/metabase/metabase/issues/16344
      changes:
        - renameColumn:
            tableName: report_dashboardcard
            columnDataType: int
            oldColumnName: sizeX
            newColumnName: size_x

  - changeSet:
      id: v45.00-029
      validCheckSum: 8:579957652133eab3ee023dd911162a1e
      author: camsaul
      comment: Added 0.45.0 -- rename DashboardCard size_y to size_y. See https://github.com/metabase/metabase/issues/16344
      changes:
        - renameColumn:
            tableName: report_dashboardcard
            columnDataType: int
            oldColumnName: sizeY
            newColumnName: size_y

  - changeSet:
      id: v45.00-030
      validCheckSum: 8:41eda097feb034c4d01b2dbda74753c8
      author: camsaul
      comment: Added 0.45.0 -- add default value to DashboardCard size_x -- this was previously done by Toucan
      changes:
        - addDefaultValue:
            tableName: report_dashboardcard
            columnName: size_x
            defaultValue: 2

  - changeSet:
      id: v45.00-031
      validCheckSum: 8:6416e373e335dc1c12c7571af674dede
      author: camsaul
      comment: Added 0.45.0 -- add default value to DashboardCard size_y -- this was previously done by Toucan
      changes:
        - addDefaultValue:
            tableName: report_dashboardcard
            columnName: size_y
            defaultValue: 2

  - changeSet:
      id: v45.00-032
      validCheckSum: 8:d97444fe24a2dca618a2804741335f6d
      author: camsaul
      comment: Added 0.45.0 -- add default value for DashboardCard created_at (Postgres/H2)
      dbms: postgresql,h2
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: postgresql,h2
      changes:
        - addDefaultValue:
            tableName: report_dashboardcard
            columnName: created_at
            columnDataType: ${timestamp_type}
            defaultValueComputed: current_timestamp

    # addDefaultValue with defaultValueComputed doesn't work for MySQL/MariaDB so we have to do this the hard way.
  - changeSet:
      id: v45.00-033
      validCheckSum: 8:34df79fc79e086ab05bb2fd79bb4e322
      author: camsaul
      comment: Added 0.45.0 -- add default value for DashboardCard created_at (MySQL/MariaDB)
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb
      changes:
        - sql:
            sql: >-
              ALTER TABLE report_dashboardcard
              CHANGE created_at
              created_at timestamp(6) NOT NULL DEFAULT current_timestamp(6);
      rollback: # nothing to do, but required for sql

  - changeSet:
      id: v45.00-034
      validCheckSum: 8:ba0505a87ef876026759cdcb4e704f41
      author: camsaul
      comment: Added 0.45.0 -- add default value for DashboardCard updated_at (Postgres/H2)
      dbms: postgresql,h2
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: postgresql,h2
      changes:
        - addDefaultValue:
            tableName: report_dashboardcard
            columnName: updated_at
            columnDataType: ${timestamp_type}
            defaultValueComputed: current_timestamp

  - changeSet:
      id: v45.00-035
      validCheckSum: 8:dcee49781d80d9c4be5ad9dd51975a07
      author: camsaul
      comment: Added 0.45.0 -- add default value for DashboardCard updated_at (MySQL/MariaDB)
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb
      changes:
        - sql:
            sql: >-
              ALTER TABLE report_dashboardcard
              CHANGE updated_at
              updated_at timestamp(6) NOT NULL DEFAULT current_timestamp(6);
      rollback: # nothing to do

  - changeSet:
      id: v45.00-036
      validCheckSum: 8:cd4009254bd2c56aaf281082038c1f0b
      author: snoe
      comment: Added 0.45.0 - add model action table
      changes:
        - createTable:
            tableName: model_action
            remarks: Ties actions to models
            columns:
              - column:
                  name: id
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: entity_id
                  type: char(21)
                  remarks: Random NanoID tag for unique identity.
                  constraints:
                    nullable: false
                    unique: true
              - column:
                  name: slug
                  type: varchar(254)
                  remarks: The referenceable name for this action
                  constraints:
                    nullable: false
              - column:
                  name: card_id
                  type: int
                  remarks: The associated model
                  constraints:
                    nullable: false
                    referencedTableName: report_card
                    referencedColumnNames: id
                    foreignKeyName: fk_model_action_ref_card_id
                    deleteCascade: true
              - column:
                  name: action_id
                  type: int
                  remarks: The associated action
                  constraints:
                    nullable: true
                    referencedTableName: action
                    referencedColumnNames: id
                    foreignKeyName: fk_model_action_ref_action_id
                    deleteCascade: true
              - column:
                  name: requires_pk
                  remarks: Indicates that the primary key(s) need to be passed in as parameters
                  type: boolean
                  defaultValueBoolean: false
                  constraints:
                    nullable: false
              - column:
                  name: parameter_mappings
                  type: ${text.type}
                  remarks: Mappings for primary keys to action parameters
              - column:
                  name: visualization_settings
                  type: ${text.type}
                  remarks: Settings for rendering the action

  - changeSet:
      id: v45.00-037
      validCheckSum: 8:56f548cc84a53cc6d18302761ee71554
      author: snoe
      comment: Added 0.45.0 - model action
      changes:
        - addUniqueConstraint:
            tableName: model_action
            columnNames: card_id, slug
            constraintName: unique_model_action_card_id_slug
      rollback: # will be deleted with table

  # The next 4 values add default values for Database `created_at` and `updated_at`; previously this was handled by
  # Toucan but it's more convenient to do this at the application database level instead -- it facilitates stuff like
  # schema migration tests that don't use Toucan, or other manual scripting
  - changeSet:
      id: v45.00-038
      validCheckSum: 8:c38ddc295206e807c7254581ed9566c3
      author: camsaul
      comment: Added 0.45.0 -- add default value for Database created_at (Postgres/H2)
      dbms: postgresql,h2
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: postgresql,h2
      changes:
        - addDefaultValue:
            tableName: metabase_database
            columnName: created_at
            columnDataType: ${timestamp_type}
            defaultValueComputed: current_timestamp

    # addDefaultValue with defaultValueComputed doesn't work for MySQL/MariaDB so we have to do this the hard way.
  - changeSet:
      id: v45.00-039
      validCheckSum: 8:2c539d76d3aead7f7366b15333132b30
      author: camsaul
      comment: Added 0.45.0 -- add default value for Database created_at (MySQL/MariaDB)
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb
      changes:
        - sql:
            sql: >-
              ALTER TABLE metabase_database
              CHANGE created_at
              created_at timestamp(6) NOT NULL DEFAULT current_timestamp(6);
      rollback: # nothing to do

  - changeSet:
      id: v45.00-040
      validCheckSum: 8:00ac7c24cfd3e7ea3a21f21f4e45dbcf
      author: camsaul
      comment: Added 0.45.0 -- add default value for Database updated_at (Postgres/H2)
      dbms: postgresql,h2
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: postgresql,h2
      changes:
        - addDefaultValue:
            tableName: metabase_database
            columnName: updated_at
            columnDataType: ${timestamp_type}
            defaultValueComputed: current_timestamp

  - changeSet:
      id: v45.00-041
      validCheckSum: 8:82dc368fa3e0163a06929da6e9556fe2
      author: camsaul
      comment: Added 0.45.0 -- add default value for Database updated_at (MySQL/MariaDB)
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb
      changes:
        - sql:
            sql: >-
              ALTER TABLE metabase_database
              CHANGE updated_at
              updated_at timestamp(6) NOT NULL DEFAULT current_timestamp(6);
      rollback: # nothing to do

  # It was probably an oversight, but while we validated Database `details` in the API layer it was not a required/NOT
  # NULL column in the application Database itself. No problem; let's add it now that we've noticed it.
  #
  # MySQL (at least 5.7) won't let us have nice things:
  #
  # https://dev.mysql.com/doc/refman/5.7/en/data-type-defaults.html
  #
  # The BLOB, TEXT, GEOMETRY, and JSON data types cannot be assigned a default value.
  #
  # Because of this restriction we will just have to update existing NULL values in SQL and then add a NOT NULL
  # restriction separately; we can use Toucan `pre-insert` to set defaults values when saving things.
  - changeSet:
      id: v45.00-042
      validCheckSum: 8:d04207471480e335f14094e9a7a5d293
      author: camsaul
      comment: Added 0.45.0 -- add default value for Database with NULL details
      changes:
        - sql:
            sql: >-
              UPDATE metabase_database SET details = '{}' WHERE details IS NULL;
      rollback: # nothing to do, since a '{}' is okay for v44

  - changeSet:
      id: v45.00-043
      validCheckSum: 8:1d07a5435e51abd0663458d907865a6b
      author: camsaul
      comment: Added 0.45.0 -- make Database details NOT NULL
      changes:
        - addNotNullConstraint:
            columnDataType: ${text.type}
            tableName: metabase_database
            columnName: details

  - changeSet:
      id: v45.00-044
      validCheckSum: 8:0b23976c5d2248d511ac31b244efef22
      author: metamben
      comment: Added 0.45.0 -- create app permission graph revision table
      changes:
        - createTable:
            tableName: app_permission_graph_revision
            remarks: 'Used to keep track of changes made to app permissions.'
            columns:
              - column:
                  name: id
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: before
                  type: ${text.type}
                  remarks: 'Serialized JSON of the apps graph before the changes.'
                  constraints:
                    nullable: false
              - column:
                  name: after
                  type: ${text.type}
                  remarks: 'Serialized JSON of the apps graph after the changes.'
                  constraints:
                    nullable: false
              - column:
                  name: user_id
                  type: int
                  remarks: 'The ID of the admin who made this set of changes.'
                  constraints:
                    nullable: false
                    referencedTableName: core_user
                    referencedColumnNames: id
                    foreignKeyName: fk_app_permission_graph_revision_user_id
              - column:
                  name: created_at
                  type: ${timestamp_type}
                  remarks: 'The timestamp of when these changes were made.'
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false
              - column:
                  name: remark
                  type: ${text.type}
                  remarks: 'Optional remarks explaining why these changes were made.'

  # note: some migrations which only added and deleted tables within v45 were removed, hence an ID gap here

  # Add created_at to Collection
  - changeSet:
      id: v45.00-048
      validCheckSum: 8:0aca8f157f163e62805b7202f8aa202f
      author: camsaul
      comment: Added 0.45.0 -- add created_at to Collection
      changes:
        - addColumn:
            tableName: collection
            columns:
              - column:
                  name: created_at
                  type: ${timestamp_type}
                  remarks: Timestamp of when this Collection was created.
                  constraints:
                    nullable: false
                  defaultValueComputed: current_timestamp

  # Seed Collection created_at for Personal Collections with the date_joined of the User that owns them.
  - changeSet:
      id: v45.00-049
      author: camsaul
      comment: Added 0.45.0 -- set Collection.created_at to User.date_joined for Personal Collections
      validCheckSum: 8:df2097d176fad99c142c5dd75ce8a3db
      changes:
        - sql:
            dbms: postgresql
            sql: >-
              UPDATE collection c
              SET created_at = u.date_joined
              FROM core_user u
              WHERE c.personal_owner_id = u.id;
        - sql:
            dbms: mysql,mariadb
            sql: >-
              UPDATE collection c
              INNER JOIN core_user u
              ON c.personal_owner_id = u.id
              SET c.created_at = u.date_joined;
        - sql:
            dbms: h2
            sql: >-
              UPDATE collection c
              SET created_at = (
                SELECT u.date_joined
                FROM core_user u
                WHERE c.personal_owner_id = u.id
              )
              WHERE c.personal_owner_id IS NOT NULL;
      rollback: # nothing to roll back, but required for sql change types

  # seed Collection created_at based on the max created at of child objects
  #
  # At the time of this writing, the following Models can appear in a Collection:
  #
  # - App
  # - Card
  # - Dashboard
  # - Pulse
  # - Timeline
  # - NativeQuerySnippet
  - changeSet:
      id: v45.00-050
      author: camsaul
      validCheckSum: ANY
      comment: Added 0.45.0 -- seed Collection.created_at with value of oldest item for non-Personal Collections
      changes:
        - sql:
            dbms: postgresql
            sql: >-
              UPDATE collection c
              SET created_at = created_ats.created_at
              FROM (
                SELECT min(created_at) AS created_at, collection_id
                FROM (
                  SELECT created_at, collection_id FROM app                  UNION ALL
                  SELECT created_at, collection_id FROM report_card          UNION ALL
                  SELECT created_at, collection_id FROM report_dashboard     UNION ALL
                  SELECT created_at, collection_id FROM pulse                UNION ALL
                  SELECT created_at, collection_id FROM timeline             UNION ALL
                  SELECT created_at, collection_id FROM native_query_snippet
                ) created_ats
                GROUP BY collection_id
              ) created_ats
              WHERE c.id = created_ats.collection_id
                AND c.personal_owner_id IS NULL;
        - sql:
            dbms: mysql,mariadb
            sql: >-
              UPDATE collection c
              LEFT JOIN (
                SELECT min(created_at) AS created_at, collection_id
                FROM (
                  SELECT created_at, collection_id FROM app                  UNION ALL
                  SELECT created_at, collection_id FROM report_card          UNION ALL
                  SELECT created_at, collection_id FROM report_dashboard     UNION ALL
                  SELECT created_at, collection_id FROM pulse                UNION ALL
                  SELECT created_at, collection_id FROM timeline             UNION ALL
                  SELECT created_at, collection_id FROM native_query_snippet
                ) created_ats
                GROUP BY collection_id
              ) created_ats
              ON c.id = created_ats.collection_id
              SET c.created_at = created_ats.created_at
              WHERE c.personal_owner_id IS NULL
                AND created_ats.created_at IS NOT NULL;
        - sql:
            dbms: h2
            # I would have preferred using MERGE ... USING instead of WHERE EXISTS ... but it's broken in 1.4.197
            # because of https://github.com/h2database/h2database/issues/1034, which is fixed in 1.4.198. So this will
            # have to do for now, even if it's a little ugly.
            sql: >-
              WITH created_ats AS (
                SELECT min(created_at) AS created_at, collection_id
                FROM (
                  SELECT created_at, collection_id FROM app                  UNION ALL
                  SELECT created_at, collection_id FROM report_card          UNION ALL
                  SELECT created_at, collection_id FROM report_dashboard     UNION ALL
                  SELECT created_at, collection_id FROM pulse                UNION ALL
                  SELECT created_at, collection_id FROM timeline             UNION ALL
                  SELECT created_at, collection_id FROM native_query_snippet
                ) created_ats
                GROUP BY collection_id
              )
              UPDATE collection c
              SET created_at = (
                SELECT created_ats.created_at
                FROM created_ats
                WHERE created_ats.collection_id = c.id
              )
              WHERE EXISTS (
                SELECT created_ats.collection_id
                FROM created_ats
                WHERE c.id = created_ats.collection_id
                  AND c.personal_owner_id IS NULL
              );
      rollback: # rollback is a no-op for most seed migrations, but required for sql change type

  - changeSet:
      id: v45.00-051
      validCheckSum: 8:2378c7031da6871dcf1c737bf323d211
      author: qnkhuat
      comment: >-
        Added 0.45.0 - modify type of collection_permission_graph_revision.after from text to ${text.type}
        on mysql,mariadb
      changes:
        - modifyDataType:
            tableName: collection_permission_graph_revision
            columnName: after
            newDataType: ${text.type}
      rollback:
        - modifyDataType:
            tableName: collection_permission_graph_revision
            columnName: after
            newDataType: text
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v45.00-052
      validCheckSum: 8:b7343eb9556c3e636b6f8dd70708c0b3
      author: qnkhuat
      comment: >-
        Added 0.45.0 - modify type of collection_permission_graph_revision.before from text to ${text.type}
        on mysql,mariadb
      changes:
        - modifyDataType:
            tableName: collection_permission_graph_revision
            columnName: before
            newDataType: ${text.type}
      rollback:
        - modifyDataType:
            tableName: collection_permission_graph_revision
            columnName: before
            newDataType: text
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v45.00-053
      validCheckSum: 8:fa552605d5a587c4fa74e0c6bd358097
      author: qnkhuat
      comment: >-
        Added 0.45.0 - modify type of collection_permission_graph_revision.remark from text to ${text.type}
        on mysql,mariadb
      changes:
        - modifyDataType:
            tableName: collection_permission_graph_revision
            columnName: remark
            newDataType: ${text.type}
      rollback:
        - modifyDataType:
            tableName: collection_permission_graph_revision
            columnName: remark
            newDataType: text
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v45.00-054
      validCheckSum: 8:60862c4ecf505727e839ac5e94f95528
      author: qnkhuat
      comment: >-
        Added 0.45.0 - modify type of permissions_revision.after from text to ${text.type}
        on mysql,mariadb
      changes:
        - modifyDataType:
            tableName: permissions_revision
            columnName: after
            newDataType: ${text.type}
      rollback:
        - modifyDataType:
            tableName: permissions_revision
            columnName: after
            newDataType: text
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v45.00-055
      validCheckSum: 8:717f0c266da5768098a2ead6168f3b18
      author: qnkhuat
      comment: >-
        Added 0.45.0 - modify type of permissions_revision.before from text to ${text.type}
        on mysql,mariadb
      changes:
        - modifyDataType:
            tableName: permissions_revision
            columnName: before
            newDataType: ${text.type}
      rollback:
        - modifyDataType:
            tableName: permissions_revision
            columnName: before
            newDataType: text
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v45.00-056
      validCheckSum: 8:a1f364d45a922c90b4fac741a22e66b3
      author: qnkhuat
      comment: >-
        Added 0.45.0 - modify type of permissions_revision.remark from text to ${text.type}
        on mysql,mariadb
      changes:
        - modifyDataType:
            tableName: permissions_revision
            columnName: remark
            newDataType: ${text.type}
      rollback:
        - modifyDataType:
            tableName: permissions_revision
            columnName: remark
            newDataType: text
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v45.00-057
      validCheckSum: 8:650a5b435f8195765a2ab1e3e4bc7b14
      author: qnkhuat
      comment: >-
        Added 0.45.0 - modify type of secret.value from blob to longblob
        on mysql,mariadb
      changes:
        - modifyDataType:
            tableName: secret
            columnName: value
            newDataType: longblob
      rollback:
        - modifyDataType:
            tableName: secret
            columnName: value
            newDataType: ${blob.type}
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v46.00-000
      validCheckSum: 8:97251413292221e51490e990b6f683f2
      author: snoe
      comment: Added 0.46.0 - Unify action representation
      changes:
        - createTable:
            tableName: implicit_action
            remarks: An action with dynamic parameters based on the underlying model
            columns:
              - column:
                  name: action_id
                  type: int
                  remarks: The associated action
                  constraints:
                    nullable: false
                    referencedTableName: action
                    referencedColumnNames: id
                    foreignKeyName: fk_implicit_action_action_id
                    deleteCascade: true
              - column:
                  name: kind
                  type: ${text.type}
                  remarks: The kind of implicit action create/update/delete
                  constraints:
                    nullable: false

  - changeSet:
      id: v46.00-001
      validCheckSum: 8:4a90c7523749aa7e4e4d2ea9dd6db777
      author: snoe
      comment: Added 0.46.0 - Unify action representation
      changes:
        - addColumn:
            tableName: action
            columns:
              - column:
                  name: model_id
                  remarks: The associated model
                  type: int

  - changeSet:
      id: v46.00-002
      validCheckSum: 8:b2b112f0df413692631b75822f658de1
      author: snoe
      comment: Added 0.46.0 - Unify action representation
      changes:
        - addColumn:
            tableName: action
            columns:
              - column:
                  name: name
                  remarks: The name of the action
                  type: varchar(254)

  - changeSet:
      id: v46.00-003
      validCheckSum: 8:45b8358f31811335aaa93032726a042b
      author: snoe
      comment: Added 0.46.0 - Unify action representation
      changes:
        - addColumn:
            tableName: action
            columns:
              - column:
                  name: description
                  remarks: The description of the action
                  type: ${text.type}

  - changeSet:
      id: v46.00-004
      validCheckSum: 8:0ce8ff05beffc5c72e2348bcec581eee
      author: snoe
      comment: Added 0.46.0 - Unify action representation
      changes:
        - addColumn:
            tableName: action
            columns:
              - column:
                  name: parameters
                  remarks: The saved parameters for this action
                  type: ${text.type}

  - changeSet:
      id: v46.00-005
      validCheckSum: 8:84cf1fbf435c7c3f794c973de4d62fad
      author: snoe
      comment: Added 0.46.0 - Unify action representation
      changes:
        - addColumn:
            tableName: action
            columns:
              - column:
                  name: parameter_mappings
                  remarks: The saved parameter mappings for this action
                  type: ${text.type}

  - changeSet:
      id: v46.00-006
      validCheckSum: 8:df43ef08b76c33c5626dbf9b226717b5
      author: snoe
      comment: Added 0.46.0 - Unify action representation
      changes:
        - addColumn:
            tableName: action
            columns:
              - column:
                  name: visualization_settings
                  remarks: The UI visualization_settings for this action
                  type: ${text.type}

  - changeSet:
      id: v46.00-007
      validCheckSum: 8:6830901cccc14ad22cdfd86bd3a2afe7
      author: snoe
      comment: Added 0.46.0 - Unify action representation
      changes:
        - addForeignKeyConstraint:
            baseTableName: action
            baseColumnNames: model_id
            referencedTableName: report_card
            referencedColumnNames: id
            constraintName: fk_action_model_id

  - changeSet:
      id: v46.00-008
      validCheckSum: 8:6e73a8683d1b757c5f9034513ec8a581
      author: snoe
      comment: Added 0.46.0 - Unify action representation
      changes:
        - addColumn:
            tableName: query_action
            columns:
              - column:
                  name: database_id
                  remarks: The associated database
                  type: int

  - changeSet:
      id: v46.00-009
      validCheckSum: 8:2b4fd7cee77d5ed8de22fcc2fba158bc
      author: snoe
      comment: Added 0.46.0 - Unify action representation
      changes:
        - addColumn:
            tableName: query_action
            columns:
              - column:
                  name: dataset_query
                  remarks: The MBQL writeback query
                  type: ${text.type}

  - changeSet:
      id: v46.00-010
      validCheckSum: 8:77ca03e5a0dbe370461295da1c77cf0f
      author: snoe
      comment: Added 0.46.0 - Unify action representation
      changes:
        - addForeignKeyConstraint:
            baseTableName: query_action
            baseColumnNames: database_id
            referencedTableName: metabase_database
            referencedColumnNames: id
            constraintName: fk_query_action_database_id
            onDelete: CASCADE

  - changeSet:
      id: v46.00-011
      author: snoe
      validCheckSum: ANY
      comment: Added 0.46.0 - Unify action representation
      changes:
        - sql:
            dbms: mysql,mariadb
            sql: >-
              ALTER TABLE query_action DROP PRIMARY KEY, ADD PRIMARY KEY pk_query_action (action_id);
        - sql:
            dbms: h2
            sql: >-
              ALTER TABLE query_action DROP PRIMARY KEY;
              ALTER TABLE query_action ADD CONSTRAINT pk_query_action PRIMARY KEY (action_id);
        - sql:
            dbms: postgresql
            sql: >-
              ALTER TABLE query_action DROP CONSTRAINT pk_query_action;
              ALTER TABLE query_action ADD CONSTRAINT pk_query_action PRIMARY KEY (action_id);
      rollback:
        - sql:
            dbms: mysql,mariadb
            sql: >-
              ALTER TABLE query_action DROP PRIMARY KEY, ADD PRIMARY KEY pk_query_action (action_id, card_id);
        - sql:
            dbms: h2
            sql: >-
              ALTER TABLE query_action DROP CONSTRAINT fk_query_action_ref_action_id;
              ALTER TABLE query_action DROP PRIMARY KEY;
              ALTER TABLE query_action ADD CONSTRAINT fk_query_action_ref_action_id FOREIGN KEY (action_id) REFERENCES action(id) ON DELETE CASCADE;
              ALTER TABLE query_action ADD CONSTRAINT pk_query_action PRIMARY KEY (action_id, card_id);
        - sql:
            dbms: postgresql
            sql: >-
              ALTER TABLE query_action DROP CONSTRAINT pk_query_action;
              ALTER TABLE query_action ADD CONSTRAINT pk_query_action PRIMARY KEY (action_id, card_id);

  - changeSet:
      id: v46.00-012
      validCheckSum: 8:7e4dffe8bbbb740207001ead696a8557
      author: snoe
      comment: Added 0.46.0 - Unify action representation
      changes:
        - dropNotNullConstraint:
            tableName: query_action
            columnDataType: int
            columnName: card_id

  # migration for developers and internal use of actions created in 45 during a short period.
  - changeSet:
      id: v46.00-013
      author: snoe
      comment: Added 0.46.0 - Unify action representation
      validCheckSum: ANY
      changes:
        - sql:
            sql: >-
              INSERT INTO action (type, model_id, name)
              SELECT 'implicit', card_id, slug
              FROM model_action
              WHERE action_id is null AND slug in ('insert','update','delete');

              INSERT INTO implicit_action (action_id, kind)
              SELECT
                id,
                case name
                  when 'insert' then 'row/create'
                  when 'update' then 'row/update'
                  when 'delete' then 'row/delete'
                end
              FROM action
              WHERE type = 'implicit';

              UPDATE action
              SET model_id = (SELECT card_id
                              FROM model_action
                              WHERE model_action.action_id = action.id)
              WHERE model_id is null;

              DELETE FROM action WHERE model_id is null;

              UPDATE report_dashboardcard
              SET action_id = (SELECT action.id
                               FROM action
                               LEFT JOIN implicit_action ON implicit_action.action_id = action.id
                               WHERE action.model_id = report_dashboardcard.card_id
                               AND coalesce((
                                  CASE implicit_action.kind
                                     WHEN 'row/create' THEN 'insert'
                                     WHEN 'row/delete' THEN 'delete'
                                     WHEN 'row/update' THEN 'update'
                                  END), ('action_' || action.id)) =
                                  substring(report_dashboardcard.visualization_settings,
                                    position('"action_slug":"' in report_dashboardcard.visualization_settings)+15,
                                    position('"' in
                                      substring(report_dashboardcard.visualization_settings,
                                        position('"action_slug":"' in visualization_settings)+15)) - 1))
              WHERE report_dashboardcard.visualization_settings like '%action_slug%';

              UPDATE query_action SET
                dataset_query = (select dataset_query from report_card where report_card.id = query_action.card_id),
                database_id = (select database_id from report_card where report_card.id = query_action.card_id);

              UPDATE action SET
                name = (
                  select name
                  from query_action
                  inner join report_card on report_card.id = query_action.card_id
                  where query_action.action_id = action.id),
                description = (
                  select description
                  from query_action
                  inner join report_card on report_card.id = query_action.card_id
                  where query_action.action_id = action.id),
                parameters = (
                  select parameters
                  from query_action
                  inner join report_card on report_card.id = query_action.card_id
                  where query_action.action_id = action.id),
                parameter_mappings = (
                  select parameter_mappings
                  from query_action
                  inner join report_card on report_card.id = query_action.card_id
                  where query_action.action_id = action.id),
                visualization_settings = (
                  select visualization_settings
                  from query_action
                  inner join report_card on report_card.id = query_action.card_id
                  where query_action.action_id = action.id)
              WHERE type = 'query';
      rollback: # no-op, we do not care to preserve actions from 46->45

  - changeSet:
      id: v46.00-014
      validCheckSum: 8:585958ee7e90e23a9cc22ebf7e4228cb
      author: snoe
      comment: Added 0.46.0 - Unify action representation
      changes:
        - dropForeignKeyConstraint:
            baseTableName: query_action
            constraintName: fk_query_action_ref_card_id
      rollback:

  - changeSet:
      id: v46.00-015
      validCheckSum: 8:9b57260e146618caff3f468116031008
      author: snoe
      comment: Added 0.46.0 - Unify action representation
      changes:
        - dropColumn:
            tableName: query_action
            columnName: card_id

      rollback:
        - addColumn:
            tableName: query_action
            columns:
              - column:
                  name: card_id
                  type: int
                  remarks: The related card
                  constraints:
                    nullable: false
                    referencedTableName: report_card
                    referencedColumnNames: id
                    foreignKeyName: fk_query_action_ref_card_id
                    deleteCascade: true

  - changeSet:
      id: v46.00-016
      validCheckSum: 8:cb79eef9f483e73b3d9b571f916b8598
      author: snoe
      comment: Added 0.46.0 - Unify action representation
      changes:
        - sql:
            sql: >-
              DELETE FROM report_card
              WHERE is_write = true;

              DELETE FROM model_action;
      rollback: # we do not care to preserve actions from 46->45
        - sql:
            sql: >-
              DELETE FROM report_dashboardcard WHERE action_id is not null;
              DELETE FROM action;

  - changeSet:
      id: v46.00-017
      validCheckSum: 8:90525ade34e7bb883bf75cdf8a2b3340
      author: snoe
      comment: Added 0.46.0 - Unify action representation
      changes:
        - dropColumn:
            tableName: http_action
            columnName: name
      rollback:
        - addColumn:
            tableName: http_action
            columns:
              - column:
                  name: name
                  type: varchar(254)
                  remarks: The name of this action
                  constraints:
                    nullable: false

  - changeSet:
      id: v46.00-018
      validCheckSum: 8:cf3c31a975dc86f1def6ee5d11f5f9dc
      author: snoe
      comment: Added 0.46.0 - Unify action representation
      changes:
        - dropColumn:
            tableName: http_action
            columnName: description
      rollback:
        - addColumn:
            tableName: http_action
            columns:
              - column:
                  name: description
                  type: ${text.type}
                  remarks: An optional description for this action

  - changeSet:
      id: v46.00-019
      validCheckSum: 8:a9f70163707cc7f798bdd0527a55854b
      author: snoe
      comment: Added 0.46.0 - Unify action representation
      changes:
        - dropColumn:
            tableName: report_card
            columnName: is_write
      rollback:
        - addColumn:
            columns:
              - column:
                  name: is_write
                  type: boolean
                  defaultValueBoolean: false
                  remarks: Indicates that this query will perform writes to a db
                  constraints:
                    nullable: false
            tableName: report_card

  - changeSet:
      id: v46.00-020
      validCheckSum: 8:2def45c139267d7424e1187764122669
      author: snoe
      comment: Added 0.46.0 - Unify action representation
      changes:
        - addNotNullConstraint:
            tableName: query_action
            columnName: database_id
            columnDataType: int

  - changeSet:
      id: v46.00-021
      validCheckSum: 8:52c8107f4bcc6e9889b270e0a4954921
      author: snoe
      comment: Added 0.46.0 - Unify action representation
      changes:
        - addNotNullConstraint:
            tableName: query_action
            columnName: dataset_query
            columnDataType: ${text.type}

  - changeSet:
      id: v46.00-022
      validCheckSum: 8:52c8107f4bcc6e9889b270e0a4954921
      author: snoe
      comment: Added 0.46.0 - Unify action representation
      changes:
        - addNotNullConstraint:
            tableName: query_action
            columnName: dataset_query
            columnDataType: ${text.type}

  - changeSet:
      id: v46.00-023
      validCheckSum: 8:33c91db1b039855af8bf1dc8315bd5d2
      author: snoe
      comment: Added 0.46.0 - Unify action representation
      changes:
        - addNotNullConstraint:
            tableName: action
            columnName: model_id
            columnDataType: int

  - changeSet:
      id: v46.00-024
      validCheckSum: 8:080ff435bae61f324535393d9e78de38
      author: snoe
      comment: Added 0.46.0 - Unify action representation
      changes:
        - addNotNullConstraint:
            tableName: action
            columnName: name
            columnDataType: varchar(254)

  - changeSet:
      id: v46.00-025
      validCheckSum: 8:60016f3de98c7382602485f13bc4e04f
      author: snoe
      comment: Added 0.46.0 - Unify action representation
      changes:
        - dropTable:
            tableName: model_action
      rollback:
        - createTable:
            tableName: model_action
            remarks: Ties actions to models
            columns:
              - column:
                  name: id
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: entity_id
                  type: char(21)
                  remarks: Random NanoID tag for unique identity.
                  constraints:
                    nullable: false
                    unique: true
              - column:
                  name: slug
                  type: varchar(254)
                  remarks: The referenceable name for this action
                  constraints:
                    nullable: false
              - column:
                  name: card_id
                  type: int
                  remarks: The associated model
                  constraints:
                    nullable: false
                    referencedTableName: report_card
                    referencedColumnNames: id
                    foreignKeyName: fk_model_action_ref_card_id
                    deleteCascade: true
              - column:
                  name: action_id
                  type: int
                  remarks: The associated action
                  constraints:
                    nullable: true
                    referencedTableName: action
                    referencedColumnNames: id
                    foreignKeyName: fk_model_action_ref_action_id
                    deleteCascade: true
              - column:
                  name: requires_pk
                  remarks: Indicates that the primary key(s) need to be passed in as parameters
                  type: boolean
                  defaultValueBoolean: false
                  constraints:
                    nullable: false
              - column:
                  name: parameter_mappings
                  type: ${text.type}
                  remarks: Mappings for primary keys to action parameters
              - column:
                  name: visualization_settings
                  type: ${text.type}
                  remarks: Settings for rendering the action

  - changeSet:
      id: v46.00-026
      validCheckSum: 8:948b9653bfbadeb29c847ef41d053dba
      author: metamben
      comment: Added 0.46.0 -- add field for tracking DBMS versions
      changes:
        - addColumn:
            tableName: metabase_database
            columns:
              - column:
                  name: dbms_version
                  type: ${text.type}
                  remarks: 'A JSON object describing the flavor and version of the DBMS.'

  - changeSet:
      id: v46.00-027
      validCheckSum: 8:5f7773b797a3c85a99cd35cb60cfd0b3
      author: snoe
      comment: Added 0.46.0 -- add last_used_at to FieldValues
      changes:
        - addColumn:
            tableName: metabase_fieldvalues
            columns:
              - column:
                  name: last_used_at
                  type: ${timestamp_type}
                  remarks: Timestamp of when these FieldValues were last used.
                  constraints:
                    nullable: false
                  defaultValueComputed: current_timestamp

  - changeSet:
      id: v46.00-028
      validCheckSum: 8:33cc1a038e926acb7dfd7cf29b4fa545
      author: tsmacdonald
      comment: Added 0.46.0 -- Join table connecting cards to dashboards/cards's parameters that need custom filter values from the card
      changes:
        - createTable:
            tableName: parameter_card
            remarks: "Join table connecting cards to entities (dashboards, other cards, etc.) that use the values generated by the card for filter values"
            columns:
              - column:
                  name: id
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: updated_at
                  type: ${timestamp_type}
                  defaultValueComputed: current_timestamp
                  remarks: "most recent modification time"
                  constraints:
                    nullable: false
              - column:
                  name: created_at
                  type: ${timestamp_type}
                  defaultValueComputed: current_timestamp
                  remarks: "creation time"
                  constraints:
                    nullable: false
              - column:
                  name: card_id
                  type: int
                  remarks: "ID of the card generating the values"
                  constraints:
                    nullable: false
              - column:
                  name: parameterized_object_type
                  type: varchar(32)
                  remarks: "Type of the entity consuming the values (dashboard, card, etc.)"
                  constraints:
                    nullable: false
              - column:
                  name: parameterized_object_id
                  type: int
                  remarks: "ID of the entity consuming the values"
                  constraints:
                    nullable: false
              - column:
                  name: parameter_id
                  type: varchar(32)
                  remarks: "The parameter ID"
                  constraints:
                    nullable: false

  # Make Dimension <=> Field a 1t1 relationship. Replace unique field_id + name with unique field_id.
  # See issue #27054.
  - changeSet:
      id: v46.00-029
      validCheckSum: 8:96336855a4180eaf51d7be4a97f3b1a4
      author: camsaul
      comment: Make Dimension <=> Field a 1t1 relationship. Drop unique constraint on field_id + name. (1/3)
      changes:
        - dropUniqueConstraint:
            tableName: dimension
            constraintName: unique_dimension_field_id_name
      rollback:
        - addUniqueConstraint:
            tableName: dimension
            constraintName: unique_dimension_field_id_name
            columnNames: field_id, name

  - changeSet:
      id: v46.00-030
      validCheckSum: 8:e1f67579cb8dc1102445df299636cb7b
      author: camsaul
      comment: Make Dimension <=> Field a 1t1 relationship. Delete duplicate entries. (2/3)
      changes:
        - sql:
            # Which rows to keep is not 100% clear. I decided to keep newer entries, by ID. I considered keeping new
            # entries by `updated_at` but the SQL for doing that across the three databases was such a hairball and
            # having duplicates in the first place was such an edge case I decided this approach is fine for now. The
            # `row_number()` window function would have made this easier to do but we haven't merged H2 v2 yet.
            #
            # Writing the query with these unnecessary subselects is stupid, but MySQL 5.7 doesn't work without them.
            # See https://metaboat.slack.com/archives/CKZEMT1MJ/p1670624514320419 for more info
            sql: >-
              DELETE FROM dimension
              WHERE field_id IN (
                SELECT field_id
                FROM (
                  SELECT field_id
                  FROM dimension
                  GROUP BY field_id
                  HAVING COUNT(*) > 1
                ) duplicates
              )
              AND id NOT IN (
                SELECT id FROM (
                  SELECT max(id) AS id
                  FROM dimension
                  GROUP BY field_id
                ) most_recents
              );
      rollback: # don't need to roll back anything, deleting duplicate entries doesn't need to be reversed.

  - changeSet:
      id: v46.00-031
      validCheckSum: 8:a9b4c86de880b2bc01e208d8d4d8cf64
      author: camsaul
      comment: Make Dimension <=> Field a 1t1 relationship. Add unique constraint on field_id. (3/3)
      changes:
        - addUniqueConstraint:
            tableName: dimension
            columnNames: field_id
            constraintName: unique_dimension_field_id
        # this change can roll back automatically.

  - changeSet:
      id: v46.00-032
      validCheckSum: 8:2a7de9726282af199737a334395f1068
      author: tsmacdonald
      comment: Added 0.46.0 -- Unique parameter_card
      changes:
        - addUniqueConstraint:
            tableName: parameter_card
            columnNames: parameterized_object_id, parameterized_object_type, parameter_id
            constraintName: unique_parameterized_object_card_parameter

  - changeSet:
      id: v46.00-033
      validCheckSum: 8:25bc5b1a806d4b352d43f5b16e7e6e20
      author: tsmacdonald
      comment: Added 0.46.0 -- parameter_card index on connected object
      changes:
        - createIndex:
            tableName: parameter_card
            columns:
              - column:
                  name: parameterized_object_id
            indexName: idx_parameter_card_parameterized_object_id

  - changeSet:
      id: v46.00-034
      validCheckSum: 8:5a6b5a2cf7160baec4f81f6675de898c
      author: tsmacdonald
      comment: Added 0.46.0 -- parameter_card index on connected card
      changes:
        - createIndex:
            tableName: parameter_card
            columns:
              - column:
                  name: card_id
            indexName: idx_parameter_card_card_id

  - changeSet:
      id: v46.00-035
      validCheckSum: 8:0639e4c0939848b4377792290311f239
      author: tsmacdonald
      comment: Added 0.46.0 - parameter_card.card_id foreign key
      changes:
        - addForeignKeyConstraint:
            baseTableName: parameter_card
            baseColumnNames: card_id
            referencedTableName: report_card
            referencedColumnNames: id
            constraintName: fk_parameter_card_ref_card_id
            onDelete: CASCADE

  - changeSet:
      id: v46.00-036
      validCheckSum: 8:39d440f29a481e9f0915532106079a1a
      author: metamben
      comment: App containers are removed in 0.46.0
      changes:
        - dropTable:
            tableName: app_permission_graph_revision
      rollback:
        - createTable:
            tableName: app_permission_graph_revision
            remarks: 'Used to keep track of changes made to app permissions.'
            columns:
              - column:
                  name: id
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: before
                  type: ${text.type}
                  remarks: 'Serialized JSON of the apps graph before the changes.'
                  constraints:
                    nullable: false
              - column:
                  name: after
                  type: ${text.type}
                  remarks: 'Serialized JSON of the apps graph after the changes.'
                  constraints:
                    nullable: false
              - column:
                  name: user_id
                  type: int
                  remarks: 'The ID of the admin who made this set of changes.'
                  constraints:
                    nullable: false
                    referencedTableName: core_user
                    referencedColumnNames: id
                    foreignKeyName: fk_app_permission_graph_revision_user_id
              - column:
                  name: created_at
                  type: ${timestamp_type}
                  remarks: 'The timestamp of when these changes were made.'
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false
              - column:
                  name: remark
                  type: ${text.type}
                  remarks: 'Optional remarks explaining why these changes were made.'

  - changeSet:
      id: v46.00-037
      validCheckSum: 8:dbbe898501c554e3ee74c6b9ef9c1575
      author: metamben
      comment: App pages are removed in 0.46.0
      changes:
        - dropColumn:
            tableName: report_dashboard
            columnName: is_app_page
      rollback:
        - addColumn:
            columns:
              - column:
                  name: is_app_page
                  type: boolean
                  defaultValueBoolean: false
                  remarks: Indicates that this dashboard serves as a page of an app
                  constraints:
                    nullable: false
            tableName: report_dashboard

  - changeSet:
      id: v46.00-038
      validCheckSum: 8:220a27bae93423a2c9a76f611f10b87b
      author: metamben
      comment: App containers are removed in 0.46.0
      changes:
        - dropTable:
            tableName: app
      rollback:
        - createTable:
            tableName: app
            remarks: Defines top level concerns for App
            columns:
              - column:
                  name: id
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: entity_id
                  type: char(21)
                  remarks: Random NanoID tag for unique identity.
                  constraints:
                    nullable: false
                    unique: true
              - column:
                  name: collection_id
                  type: int
                  remarks: The associated collection
                  constraints:
                    nullable: false
                    referencedTableName: collection
                    referencedColumnNames: id
                    foreignKeyName: fk_app_ref_collection_id
                    deleteCascade: true
                    unique: true
              - column:
                  name: dashboard_id
                  type: int
                  remarks: The homepage of the app
              - column:
                  remarks: JSON for the navigation items of the app
                  name: nav_items
                  type: ${text.type}
              - column:
                  remarks: JSON for frontend related additions, such as styling
                  name: options
                  type: ${text.type}
              - column:
                  remarks: The timestamp of when the app was created
                  name: created_at
                  type: ${timestamp_type}
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false
              - column:
                  remarks: The timestamp of when the app was updated
                  name: updated_at
                  type: ${timestamp_type}
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false
        - addForeignKeyConstraint:
            baseTableName: app
            baseColumnNames: dashboard_id
            referencedTableName: report_dashboard
            referencedColumnNames: id
            constraintName: fk_app_ref_dashboard_id
            onDelete: SET NULL

  - changeSet:
      id: v46.00-039
      validCheckSum: 8:7ed32de11fbe8565148d8491f908ad05
      author: qnkhuat
      comment: Added 0.46.0 - add entity_id to parameter_card
      changes:
        - addColumn:
            columns:
            - column:
                remarks: Random NanoID tag for unique identity.
                name: entity_id
                type: char(21)
                constraints:
                  nullable: true
                  unique: true
            tableName: parameter_card

  - changeSet:
      id: v46.00-040
      validCheckSum: 8:7fec881cac598cce34b62c98fcf37563
      author: tsmacdonald
      comment: Added 0.46.0 -- Bump default dashcard size to 4x4
      changes:
        - addDefaultValue:
            tableName: report_dashboardcard
            columnName: size_x
            defaultValue: 4

  - changeSet:
      id: v46.00-041
      validCheckSum: 8:0214a8d0b94a9eb48aad75b1d50dd279
      author: tsmacdonald
      comment: Added 0.46.0 -- Bump default dashcard size to 4x4
      changes:
        - addDefaultValue:
            tableName: report_dashboardcard
            columnName: size_y
            defaultValue: 4

  - changeSet:
      id: v46.00-042
      validCheckSum: 8:7b91ad83569565517c43e9f7b9bfa29a
      author: tsmacdonald
      comment: Added 0.46.0 -- index query_execution.executor_id
      changes:
        - createIndex:
            tableName: query_execution
            columns:
              - column:
                  name: executor_id
            indexName: idx_query_execution_executor_id

  - changeSet:
      id: v46.00-043
      validCheckSum: 8:d9cab29076035068cfc49fb9570832af
      author: tsmacdonald
      comment: Added 0.46.0 -- index query_execution.context
      changes:
        - createIndex:
            tableName: query_execution
            columns:
              - column:
                  name: context
            indexName: idx_query_execution_context

  - changeSet:
      id: v46.00-045
      validCheckSum: 8:7a9cabf1c693de8b0c9555f7deb072a4
      author: calherries
      comment: Added 0.46.0 -- add public_uuid to action.
      changes:
        - addColumn:
            tableName: action
            columns:
              - column:
                  name: public_uuid
                  type: char(36)
                  remarks: 'Unique UUID used to in publically-accessible links to this Action.'
                  constraints:
                    unique: true

  - changeSet:
      id: v46.00-051
      validCheckSum: 8:74e83fc2ee7c1a06a94f07830f361773
      author: calherries
      comment: Added 0.46.0 -- drop defaults for dashcard's position and size
      changes:
        - dropDefaultValue:
            tableName: report_dashboardcard
            columnName: row
      rollback:
        - addDefaultValue:
            tableName: report_dashboardcard
            columnName: row
            defaultValueNumeric: 4

  - changeSet:
      id: v46.00-052
      validCheckSum: 8:948c978fcb2d938d272a05b3e56808d1
      author: calherries
      comment: Added 0.46.0 -- drop defaults for dashcard's position and size
      changes:
        - dropDefaultValue:
            tableName: report_dashboardcard
            columnName: col
      rollback:
        - addDefaultValue:
            tableName: report_dashboardcard
            columnName: col
            defaultValueNumeric: 4

  - changeSet:
      id: v46.00-053
      validCheckSum: 8:04e092dbffdfda13f28b1e3ea38299a7
      author: calherries
      comment: Added 0.46.0 -- drop defaults for dashcard's position and size
      changes:
        - dropDefaultValue:
            tableName: report_dashboardcard
            columnName: size_x
      rollback:
        - addDefaultValue:
            tableName: report_dashboardcard
            columnName: size_x
            defaultValueNumeric: 4

  - changeSet:
      id: v46.00-054
      validCheckSum: 8:bc3abf9ab94199aeaebb2be28dea77aa
      author: calherries
      comment: Added 0.46.0 -- drop defaults for dashcard's position and size
      changes:
        - dropDefaultValue:
            tableName: report_dashboardcard
            columnName: size_y
      rollback:
        - addDefaultValue:
            tableName: report_dashboardcard
            columnName: size_y
            defaultValueNumeric: 4

  - changeSet:
      id: v46.00-055
      validCheckSum: 8:48a516459b84a21e9edbdbfe1bffd671
      author: calherries
      comment: Added 0.46.0 -- add made_public_by_id
      changes:
        - addColumn:
            tableName: action
            columns:
              - column:
                  name: made_public_by_id
                  type: int
                  remarks: 'The ID of the User who first publically shared this Action.'

  - changeSet:
      id: v46.00-056
      validCheckSum: 8:af93ab591b44b5d81d8d8a496600c1bc
      author: calherries
      comment: Added 0.46.0 -- add public_uuid and made_public_by_id to action. public_uuid is indexed
      changes:
        - createIndex:
            tableName: action
            indexName: idx_action_public_uuid
            columns:
              column:
                name: public_uuid

  - changeSet:
      id: v46.00-057
      validCheckSum: 8:aff3b0e15dcfc36a4fd97faade0751c0
      author: dpsutton
      comment: Added 0.46.0 -- parameter_card.parameter_id long enough to hold a uuid
      changes:
        - modifyDataType:
            tableName: parameter_card
            columnName: parameter_id
            newDataType: varchar(36)
      rollback: #nothing to do, char(32) or char(36) are equivalent

  - changeSet:
      id: v46.00-058
      validCheckSum: 8:11440c629413c7231e7f156347353761
      author: calherries
      comment: Added 0.46.0 -- add FK constraint for action.made_public_by_id with core_user.id
      changes:
        - addForeignKeyConstraint:
            baseTableName: action
            baseColumnNames: made_public_by_id
            referencedTableName: core_user
            referencedColumnNames: id
            constraintName: fk_action_made_public_by_id
            onDelete: CASCADE

  - changeSet:
      id: v46.00-059
      validCheckSum: 8:6ddec7d622e9200e36bd5e2e2e0a48c2
      author: tsmacdonald
      comment: Added 0.46.0 -- add actions.creator_id
      changes:
        - addColumn:
            tableName: action
            columns:
              - column:
                  name: creator_id
                  type: int
                  remarks: 'The user who created the action'
      rollback:
        - dropColumn:
            tableName: action
            columnName: creator_id

  - changeSet:
      id: v46.00-060
      validCheckSum: 8:fc1762a930726afb11131acf3a56312b
      author: tsmacdonald
      comment: Added 0.46.0 -- action.creator_id index
      changes:
        - createIndex:
            tableName: action
            columns:
              - column:
                  name: creator_id
            indexName: idx_action_creator_id
      rollback:
        - dropIndex:
            tableName: action
            indexName: idx_action_creator_id

  - changeSet:
      id: v46.00-061
      validCheckSum: 8:d57393ae0e96a9b1a0bd7a66597cb485
      author: tsmacdonald
      comment: Added 0.46.0 -- action.creator_id index
      changes:
        - addForeignKeyConstraint:
            baseTableName: action
            baseColumnNames: creator_id
            referencedTableName: core_user
            referencedColumnNames: id
            constraintName: fk_action_creator_id
            nullable: false

  - changeSet:
      id: v46.00-062
      validCheckSum: 8:20efdbd79df3c76cbf77318d871a9836
      author: tsmacdonald
      comment: Added 0.46.0 -- add actions.archived
      changes:
        - addColumn:
            tableName: action
            columns:
              - column:
                  name: archived
                  type: boolean
                  defaultValueBoolean: false
                  remarks: 'Whether or not the action has been archived'
                  constraints:
                    nullable: false
      rollback:
        - dropColumn:
            tableName: action
            columnName: archived

  - changeSet:
      id: v46.00-064
      validCheckSum: 8:0ac10ca0d82f1bbe39737eb0a8fdcd7d
      author: noahmoss
      comment: Added 0.46.0 -- rename `group_table_access_policy` to `sandboxes`
      changes:
        - renameTable:
            newTableName: sandboxes
            oldTableName: group_table_access_policy

  - changeSet:
      id: v46.00-065
      validCheckSum: 8:5cbb335952dd1ab7a137d80d6c1ab82e
      author: noahmoss
      comment: Added 0.46.0 -- add `permission_id` to `sandboxes`
      changes:
      - addColumn:
          tableName: sandboxes
          columns:
          - column:
              name: permission_id
              type: int
              remarks: The ID of the corresponding permissions path for this sandbox

  - changeSet:
      id: v46.00-070
      validCheckSum: 8:d440a8d0aef0bbfdae24a9c70bd37605
      author: calherries
      comment: Added 0.46.0 - add entity_id column to action
      changes:
        - addColumn:
            columns:
            - column:
                remarks: Random NanoID tag for unique identity.
                name: entity_id
                type: char(21)
                constraints:
                  nullable: true
                  unique: true
            tableName: action

  - changeSet:
      id: v46.00-074
      validCheckSum: 8:c1273a3003d82638a0a5413bf2aa6777
      author: metamben
      comment: Added 0.46.0 -- increase precision of updated_at of report_card
      changes:
        - modifyDataType:
            tableName: report_card
            columnName: updated_at
            newDataType: ${timestamp_type}
      rollback:
        - modifyDataType:
            tableName: report_card
            columnName: updated_at
            newDataType: DATETIME

  - changeSet:
      id: v46.00-079
      validCheckSum: 8:de167f33d3f7670246623466487d2e67
      author: john-metabase
      comment: Added 0.46.0 -- migrates Databases using deprecated and removed presto driver to presto-jdbc
      changes:
        - sql: UPDATE metabase_database SET engine = 'presto-jdbc' WHERE engine = 'presto'
      rollback: # nothing to do, since we don't know which drivers used to be presto

  - changeSet:
      id: v46.00-080
      validCheckSum: ANY
      author: noahmoss
      comment: Migrate data permission paths from v1 to v2 (splitting them into separate data and query permissions)
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.SplitDataPermissions"

  - changeSet:
      id: v46.00-084
      validCheckSum: 8:b4f465ca3be584028e077b907656b804
      author: qnkhuat
      comment: Added 0.46.0 - CASCADE delete for action.model_id
      changes:
        - dropForeignKeyConstraint:
            baseTableName: action
            constraintName: fk_action_model_id
      rollback:
        - addForeignKeyConstraint:
            baseTableName: action
            baseColumnNames: model_id
            referencedTableName: report_card
            referencedColumnNames: id
            constraintName: fk_action_model_id
            onDelete: CASCADE

  - changeSet:
      id: v46.00-085
      validCheckSum: 8:17fe48c56aa457a6a09775099d44d7a5
      author: qnkhuat
      comment: Added 0.46.0 - CASCADE delete for action.model_id
      changes:
        - addForeignKeyConstraint:
            baseTableName: action
            baseColumnNames: model_id
            referencedTableName: report_card
            referencedColumnNames: id
            constraintName: fk_action_model_id
            onDelete: CASCADE

  - changeSet:
      id: v46.00-086
      validCheckSum: ANY
      author: calherries
      comment: Added 0.46.0 - Delete the abandonment email task
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.DeleteAbandonmentEmailTask"

  - changeSet:
      id: v46.00-088
      validCheckSum: 8:ff9defc19920960db55ef71e4d32b4ea
      author: noahmoss
      comment: Added 0.46.5 -- backfill `permission_id` values in `sandboxes`. This is a fixed verison of v46.00-066
               which has been removed, since it had a bug that blocked a customer from upgrading.
      changes:
        - sql: >-
            UPDATE sandboxes s
            SET permission_id = (
              SELECT p.id
              FROM permissions p
              WHERE
                p.object = CONCAT('/db/',
                                  (SELECT t.db_id FROM metabase_table t WHERE t.id = s.table_id),
                                  '/schema/',
                                  (SELECT t.schema FROM metabase_table t WHERE t.id = s.table_id),
                                  '/table/',
                                  s.table_id,
                                  '/query/segmented/')
                AND p.group_id = s.group_id
              LIMIT 1
            )
            WHERE permission_id IS NULL;
      rollback:
        # not required, new values added here do not need to be dropped

  - changeSet:
      id: v46.00-089
      validCheckSum: 8:e0fbd2514cc960cc74106204ac65a3ea
      author: noahmoss
      comment: Added 0.46.5 -- remove orphaned entries in `sandboxes`
      changes:
        - sql: >-
            DELETE FROM sandboxes
            WHERE permission_id IS NULL;
      rollback: # not required, orphaned sandboxes should not be re-added to the DB

  - changeSet:
      id: v46.00-090
      validCheckSum: 8:963c0cd3a7bd2858e4dbfd4d4aad95cb
      author: noahmoss
      comment: Add foreign key constraint on sandboxes.permission_id
      changes:
        - addForeignKeyConstraint:
            baseTableName: sandboxes
            baseColumnNames: permission_id
            referencedTableName: permissions
            referencedColumnNames: id
            constraintName: fk_sandboxes_ref_permissions
            onDelete: CASCADE

  - changeSet:
      id: v47.00-001
      validCheckSum: 8:14bf2732687c04256e9c036ba142aa93
      author: calherries
      comment: Added 0.47.0 -- set base-type to type/JSON for JSON database-types for postgres and mysql
      changes:
        - sql:
            sql: >-
              UPDATE metabase_field f
              SET base_type = 'type/JSON'
              WHERE EXISTS (
                SELECT *
                FROM metabase_database d
                JOIN metabase_table t ON t.db_id = d.id
                WHERE f.table_id = t.id
                  AND lower(f.database_type) in ('json', 'jsonb')
                  AND d.engine in ('postgres', 'mysql')
              )
      rollback:
        - sql:
            dbms: postgresql
            sql: >-
              UPDATE metabase_field f
              SET base_type = case when d.engine = 'postgres' then 'type/Structured' else 'type/SerializedJSON' end
              FROM metabase_database d
              JOIN metabase_table t ON t.db_id = d.id
              WHERE f.table_id = t.id
                AND lower(f.database_type) in ('json', 'jsonb')
                AND d.engine in ('postgres', 'mysql')
        - sql:
            dbms: mysql,mariadb
            sql: >-
              UPDATE metabase_field f
              JOIN metabase_table t ON f.table_id = t.id
              JOIN metabase_database d ON t.db_id = d.id
              SET base_type = case when d.engine = 'postgres' then 'type/Structured' else 'type/SerializedJSON' end
              WHERE lower(f.database_type) in ('json', 'jsonb')
                AND d.engine in ('postgres', 'mysql')
        - sql:
            dbms: h2
            sql: >-
              MERGE INTO metabase_field f
              USING (
                SELECT f.id, case when d.engine = 'postgres' then 'type/Structured' else 'type/SerializedJSON' end as base_type
                FROM metabase_field f
                JOIN metabase_table t ON f.table_id = t.id
                JOIN metabase_database d ON t.db_id = d.id
                WHERE lower(f.database_type) in ('json', 'jsonb')
                  AND d.engine in ('postgres', 'mysql')
              ) as updates
              ON f.id = updates.id
              WHEN MATCHED THEN
                UPDATE SET f.base_type = updates.base_type;

  - changeSet:
      id: v47.00-002
      validCheckSum: 8:963690f41f487b122464277c627823f6
      author: calherries
      comment: Added 0.47.0 - Add json_unfolding column to metabase_field
      changes:
        - addColumn:
            columns:
            - column:
                remarks: 'Enable/disable JSON unfolding for a field'
                name: json_unfolding
                type: boolean
                defaultValueBoolean: false
                constraints:
                  nullable: false
            tableName: metabase_field

  - changeSet:
      id: v47.00-003
      validCheckSum: 8:97bccdf5e9bcdfacd1c315fa1342c167
      author: calherries
      comment: Added 0.47.0 - Populate metabase_field.json_unfolding based on base_type
      changes:
        - sql:
            sql: >-
              UPDATE metabase_field
              SET json_unfolding = true
              WHERE base_type = 'type/JSON';
      rollback: # nothing to do, since json_unfolding is new in 47

  - changeSet:
      id: v47.00-004
      validCheckSum: 8:58ad79be7de00e413da51fab3c8beea0
      author: qnkhuat
      comment: Added 0.47.0 - Add auto_incremented to metabase_field
      changes:
        - addColumn:
            tableName: metabase_field
            columns:
              - column:
                  name: database_is_auto_increment
                  type: boolean
                  remarks: Indicates this field is auto incremented
                  defaultValueBoolean: false
                  constraints:
                    nullable: false

  - changeSet:
      id: v47.00-005
      validCheckSum: 8:ccf53f27a551fd0799d0103bd65cca99
      author: winlost
      comment: Added 0.47.0 - Add auto_apply_filters to dashboard
      changes:
        - addColumn:
            tableName: report_dashboard
            columns:
              - column:
                  name: auto_apply_filters
                  type: boolean
                  remarks: Whether or not to auto-apply filters on a dashboard
                  defaultValueBoolean: true
                  constraints:
                    nullable: false

  - changeSet:
      id: v47.00-006
      validCheckSum: 8:b63ff10d3d121bed42eece1ae3dbb177
      author: qnkhuat
      comment: Added 0.47.0 - Add dashboard_tab table
      changes:
        - createTable:
            tableName: dashboard_tab
            remarks: "Join table connecting dashboard to dashboardcards"
            columns:
              - column:
                  name: id
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: dashboard_id
                  type: int
                  remarks: The dashboard that a tab is on
                  constraints:
                    nullable: false
                    referencedTableName: report_dashboard
                    referencedColumnNames: id
                    foreignKeyName: fk_dashboard_tab_ref_dashboard_id
                    deleteCascade: true
              - column:
                  name: name
                  remarks: Displayed name of the tab
                  type: ${text.type}
                  constraints:
                    nullable: false
              - column:
                  name: position
                  remarks: Position of the tab with respect to others tabs in dashboard
                  type: int
                  constraints:
                    nullable: false
              - column:
                  name: entity_id
                  type: char(21)
                  remarks: Random NanoID tag for unique identity.
                  constraints:
                    nullable: false
                    unique: true
              - column:
                  name: created_at
                  remarks: The timestamp at which the tab was created
                  type: ${timestamp_type}
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false
              - column:
                  name: updated_at
                  remarks: The timestamp at which the tab was last updated
                  type: ${timestamp_type}
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false

  - changeSet:
      id: v47.00-007
      validCheckSum: 8:e9f7d6b18d65be6fde07c0b5471b8760
      author: qnkhuat
      comment: Added 0.47.0 -- add report_dashboardcard.dashboard_tab_id
      changes:
        - addColumn:
            tableName: report_dashboardcard
            columns:
              - column:
                  name: dashboard_tab_id
                  type: int
                  remarks: The referenced tab id that dashcard is on, it's nullable for dashboard with no tab
                  constraints:
                    nullable: true

  - changeSet:
      id: v47.00-008
      validCheckSum: 8:e37c88d202007bd3e6a72b6404d1b0e9
      author: qnkhuat
      comment: Added 0.47.0 -- add report_dashboardcard.dashboard_tab_id fk constraint
      changes:
        - addForeignKeyConstraint:
            baseTableName: report_dashboardcard
            baseColumnNames: dashboard_tab_id
            referencedTableName: dashboard_tab
            referencedColumnNames: id
            constraintName: fk_report_dashboardcard_ref_dashboard_tab_id
            deleteCascade: true

  - changeSet:
      id: v47.00-009
      validCheckSum: 8:398124b0dd4dd6e117cdc1378152469b
      author: qwef
      comment: Added 0.47.0 - Replace user google_auth and ldap_auth columns with sso_source values
      changes:
        - sql:
            sql: UPDATE core_user SET sso_source = 'google' WHERE google_auth = true;
      rollback:
        - sql:
            sql: UPDATE core_user SET google_auth = true, sso_source = NULL WHERE sso_source = 'google';

  - changeSet:
      id: v47.00-010
      validCheckSum: 8:3c4f9fc116fbced18c50952def65b3e0
      author: tsmacdonald
      comment: Added 0.47.0 - Make metabase_table.name long enough for H2 names
      changes:
        - modifyDataType:
            tableName: metabase_table
            columnName: name
            newDataType: varchar(256)
      rollback: # no rollback needed, varchar(256) is backwards compatible

  - changeSet:
      id: v47.00-011
      validCheckSum: 8:148b982debddfa511cb45b87179b8c46
      author: tsmacdonald
      comment: Added 0.47.0 - Make metabase_table.display_name long enough for H2 names
      changes:
        - modifyDataType:
            tableName: metabase_table
            columnName: display_name
            newDataType: varchar(256)
      rollback: # no rollback needed, varchar(256) is backwards compatible

  - changeSet:
      id: v47.00-012
      validCheckSum: 8:bf19ef077bc6bc517c515dd78ca46e3b
      author: qwef
      comment: Added 0.47.0 - Replace user google_auth and ldap_auth columns with sso_source values
      changes:
        - dropColumn:
            tableName: core_user
            columnName: google_auth
      rollback:
        - addColumn:
            tableName: core_user
            columns:
              - column:
                  name: google_auth
                  type: boolean
                  defaultValueBoolean: false
                  constraints:
                    nullable: false

  - changeSet:
      id: v47.00-013
      validCheckSum: 8:044aec6d07049e3c5a45830797189ab0
      author: qwef
      comment: Added 0.47.0 - Replace user google_auth and ldap_auth columns with sso_source values
      changes:
        - sql:
            sql: UPDATE core_user SET sso_source = 'ldap' WHERE ldap_auth = true;
      rollback:
        - sql:
            sql: UPDATE core_user SET ldap_auth = true, sso_source = NULL WHERE sso_source = 'ldap';

  - changeSet:
      id: v47.00-014
      validCheckSum: 8:6a973f3198ad4596ecade95e61b35991
      author: qwef
      comment: Added 0.47.0 - Replace user google_auth and ldap_auth columns with sso_source values
      changes:
        - dropColumn:
            tableName: core_user
            columnName: ldap_auth
      rollback:
        - addColumn:
            tableName: core_user
            columns:
              - column:
                  name: ldap_auth
                  type: boolean
                  defaultValueBoolean: false
                  constraints:
                    nullable: false

  - changeSet:
      id: v47.00-015
      validCheckSum: 8:d2d5eea99db75e656709006b3a7749f0
      author: escherize
      comment: added 0.47.0 - Add is_audit to metabase_database
      changes:
        - addColumn:
            tableName: metabase_database
            columns:
              - column:
                  name: is_audit
                  type: boolean
                  defaultValueBoolean: false
                  remarks: 'Only the app db, visible to admins via auditing should have this set true.'
                  constraints:
                    nullable: false

  - changeSet:
      id: v47.00-016
      validCheckSum: ANY
      author: calherres
      comment: Added 0.47.0 - Migrate the report_card.visualization_settings.column_settings field refs from legacy format
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.MigrateLegacyColumnSettingsFieldRefs"

  - changeSet:
      id: v47.00-018
      validCheckSum: 8:7bacd2f60393eebd3bebcfdb0e952ecd
      author: dpsutton
      comment: Indexed Entities information table
      changes:
        - createTable:
            tableName: model_index
            remarks: 'Used to keep track of which models have indexed columns.'
            columns:
              - column:
                  name: id
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: model_id
                  type: int
                  remarks: 'The ID of the indexed model.'
              - column:
                  name: pk_ref
                  type: ${text.type}
                  remarks: 'Serialized JSON of the primary key field ref.'
                  constraints:
                    nullable: false
              - column:
                  name: value_ref
                  type: ${text.type}
                  remarks: 'Serialized JSON of the label field ref.'
                  constraints:
                    nullable: false
              - column:
                  name: schedule
                  type: ${text.type}
                  remarks: 'The cron schedule for when value syncing should happen.'
                  constraints:
                    nullable: false
              - column:
                  name: state
                  type: ${text.type}
                  remarks: 'The status of the index: initializing, indexed, error, overflow.'
                  constraints:
                    nullable: false
              - column:
                  name: indexed_at
                  type: ${timestamp_type}
                  remarks: 'When the status changed'
                  constraints:
                    nullable: true
              - column:
                  name: error
                  type: ${text.type}
                  remarks: 'The error message if the status is error.'
                  constraints:
                    nullable: true
              - column:
                  name: created_at
                  type: ${timestamp_type}
                  remarks: 'The timestamp of when these changes were made.'
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false
              - column:
                  remarks: 'ID of the user who created the event'
                  name: creator_id
                  type: int
                  constraints:
                    nullable: false
                    references: core_user(id)
                    foreignKeyName: fk_model_index_creator_id
                    deleteCascade: true
      rollback:
        - dropTable:
            tableName: model_index

  - changeSet:
      id: v47.00-019
      validCheckSum: 8:7a5589d70c80b3ffc99a85722f440a91
      author: dpsutton
      comment: Indexed Entities values table
      changes:
        - createTable:
            tableName: model_index_value
            remarks: 'Used to keep track of the values indexed in a model'
            columns:
              - column:
                  name: model_index_id
                  type: int
                  remarks: 'The ID of the indexed model.'
              - column:
                  name: model_pk
                  type: int
                  remarks: 'The primary key of the indexed value'
                  constraints:
                    nullable: false
              - column:
                  name: name
                  type: ${text.type}
                  remarks: 'The label to display identifying the indexed value.'
                  constraints:
                    nullable: false
      rollback:
        - dropTable:
            tableName: model_index_value

  - changeSet:
      id: v47.00-020
      validCheckSum: 8:d32a4cf7b37f012a7db74628cdde48df
      author: dpsutton
      comment: Add unique constraint on index_id and pk
      changes:
        - addUniqueConstraint:
            tableName: model_index_value
            constraintName: unique_model_index_value_model_index_id_model_pk
            columnNames: model_index_id, model_pk
      rollback:
        - dropUniqueConstraint:
            tableName: model_index_value
            constraintName: unique_model_index_value_model_index_id_model_pk

  - changeSet:
      id: v47.00-023
      validCheckSum: 8:5d9e81c3e950afad66cb5e9e823b1f03
      author: dpsutton
      comment: Added 0.47.0 -- model_index index
      changes:
        - createIndex:
            tableName: model_index
            columns:
              - column:
                  name: model_id
            indexName: idx_model_index_model_id

  - changeSet:
      id: v47.00-024
      validCheckSum: 8:3079db8d91e54ff2b41050f7dab27936
      author: dpsutton
      comment: Added 0.47.0 -- model_index foriegn key to report_card
      changes:
        - addForeignKeyConstraint:
            baseTableName: model_index
            baseColumnNames: model_id
            referencedTableName: report_card
            referencedColumnNames: id
            constraintName: fk_model_index_model_id
            nullable: false
            deleteCascade: true

  - changeSet:
      id: v47.00-025
      validCheckSum: 8:6889e314a2016c9bc017a358b81ed24e
      author: dpsutton
      comment: Added 0.47.0 -- model_index_value foriegn key to model_index
      changes:
        - addForeignKeyConstraint:
            baseTableName: model_index_value
            baseColumnNames: model_index_id
            referencedTableName: model_index
            referencedColumnNames: id
            constraintName: fk_model_index_value_model_id
            nullable: false
            deleteCascade: true

  - changeSet:
      id: v47.00-026
      validCheckSum: 8:acf279edf538ee29a4ea9103d809b3da
      author: noahmoss
      comment: Added 0.47.0 - New table for connection impersonation policies
      changes:
        - createTable:
            tableName: connection_impersonations
            remarks: Table for holding connection impersonation policies
            columns:
              - column:
                  name: id
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: db_id
                  type: int
                  remarks: 'ID of the database this connection impersonation policy affects'
                  constraints:
                    nullable: false
                    referencedTableName: metabase_database
                    referencedColumnNames: id
                    foreignKeyName: fk_conn_impersonation_db_id
                    deleteCascade: true
              - column:
                  name: group_id
                  type: int
                  remarks: 'ID of the permissions group this connection impersonation policy affects'
                  constraints:
                    nullable: false
                    referencedTableName: permissions_group
                    referencedColumnNames: id
                    foreignKeyName: fk_conn_impersonation_group_id
                    deleteCascade: true
              - column:
                  name: attribute
                  type: ${text.type}
                  remarks: 'User attribute associated with the database role to use for this connection impersonation policy'

  - changeSet:
      id: v47.00-027
      validCheckSum: ANY
      author: calherries
      comment: Added 0.47.0 - Migrate field_ref in report_card.result_metadata from legacy format
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.MigrateLegacyResultMetadataFieldRefs"

  - changeSet:
      id: v47.00-028
      validCheckSum: ANY
      author: calherries
      comment: Added 0.47.0 - Add join-alias to the report_card.visualization_settings.column_settings field refs
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.AddJoinAliasToVisualizationSettingsFieldRefs"

  - changeSet:
      id: v47.00-029
      validCheckSum: ANY
      author: qnkhuat
      comment: Added 0.47.0 - Stack cards vertically for dashboard with tabs on downgrade
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.DowngradeDashboardTab"

  - changeSet:
      id: v47.00-030
      validCheckSum: 8:7919d959008457419a09fd3275d3ed00
      author: escherize
      comment: Added 0.47.0 - Type column for collections for instance-analytics
      changes:
        - addColumn:
            tableName: collection
            columns:
              - column:
                  name: type
                  type: varchar(256)
                  defaultValue: null
                  remarks: 'This is used to differentiate instance-analytics collections from all other collections.'

  - changeSet:
      id: v47.00-031
      author: qnkhuat
      comment: Added 0.47.0 - migrate dashboard grid size from 18 to 24
      validCheckSum: 8:ad9bdb62df65cf26a5a9892a82779ea7
      changes:
          # new_size_x = size_x + ((col + size_x + 1) // 3) - ((col + 1) // 3)
          # new_col    = col + ((col + 1) // 3)
          - sql:
              dbms: postgresql
              sql: >-
                  update report_dashboardcard set size_x = size_x + floor(cast(size_x + col + 1  as decimal) / 3) - floor(cast(col + 1 as decimal) / 3);
                  update report_dashboardcard set col    = col + floor(cast(col + 1 as decimal) / 3);
          - sql:
              dbms: mysql,mariadb,h2
              sql: >-
                  update report_dashboardcard set size_x = size_x + floor(cast(size_x + col + 1  as decimal) / 3) - floor(cast(col + 1 as decimal) / 3);
                  update report_dashboardcard set col    = col + floor(cast(col + 1 as decimal) / 3);

      rollback:
          # new_size_x = size_x - ((size_x + col + 1) // 4 - (col + 1) // 4) for size_x > 1
          # new_col    = col - (col + 1) // 4
          # for size_x, we keep it as it is, because it can't be smaller right?
          - sql:
              dbms: postgresql
              sql: >-
                  update report_dashboardcard set size_x = size_x - (floor(cast(size_x + col + 1 as decimal) / 4) - floor(cast(col + 1 as decimal) / 4)) where size_x <> 1;
                  update report_dashboardcard set col    = col - floor(cast(col + 1 as decimal) / 4);

          - sql:
              dbms: mysql,mariadb,h2
              sql: >-
                  update report_dashboardcard set size_x = size_x - (floor(cast(size_x + col + 1 as decimal) / 4) - floor(cast(col + 1 as decimal) / 4)) where size_x <> 1;
                  update report_dashboardcard set col    = col - floor(cast(col + 1 as decimal) / 4);

  - changeSet:
      id: v47.00-032
      author: qnkhuat
      comment: Added 0.47.0 - migrate dashboard grid size from 18 to 24 for revisions
      validCheckSum: ANY
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.RevisionDashboardMigrateGridFrom18To24"

  - changeSet:
      id: v47.00-033
      validCheckSum: ANY
      author: calherries
      comment: Added 0.47.0 - Migrate field refs in visualization_settings.column_settings keys from legacy format
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.RevisionMigrateLegacyColumnSettingsFieldRefs"

  - changeSet:
      id: v47.00-034
      validCheckSum: ANY
      author: calherries
      comment: Added 0.47.0 - Add join-alias to the visualization_settings.column_settings field refs in card revisions
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.RevisionAddJoinAliasToColumnSettingsFieldRefs"

  - changeSet:
      id: v47.00-035
      validCheckSum: 8:aeafa7ff310f799eb3fb2e14640a9e06
      author: calherries
      comment: Added 0.47.0 - Drop foreign key constraint on implicit_action.action_id
      changes:
        - dropForeignKeyConstraint:
            baseTableName: implicit_action
            constraintName: fk_implicit_action_action_id
      rollback:
        - addForeignKeyConstraint:
            baseTableName: implicit_action
            baseColumnNames: action_id
            referencedTableName: action
            referencedColumnNames: id
            constraintName: fk_implicit_action_action_id
            onDelete: CASCADE

  - changeSet:
      id: v47.00-036
      validCheckSum: 8:e815729b6ebfd4799743b249409558aa
      author: calherries
      comment: Added 0.47.0 - Set primary key to action_id for implicit_action table
      changes:
        - addPrimaryKey:
            tableName: implicit_action
            columnNames: action_id
            constraintName: pk_implicit_action

  - changeSet:
      id: v47.00-037
      validCheckSum: 8:58c705a18bb3441e3ed5d1167ec64fcb
      author: calherries
      comment: Added 0.47.0 - Add foreign key constraint on implicit_action.action_id
      changes:
        - addForeignKeyConstraint:
            baseTableName: implicit_action
            baseColumnNames: action_id
            referencedTableName: action
            referencedColumnNames: id
            constraintName: fk_implicit_action_action_id
            onDelete: CASCADE

  - changeSet:
      id: v47.00-043
      validCheckSum: ANY
      author: calherres
      comment: Added 0.47.0 - Migrate report_dashboardcard.visualization_settings.column_settings field refs from legacy format
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.MigrateLegacyDashboardCardColumnSettingsFieldRefs"

  - changeSet:
      id: v47.00-044
      validCheckSum: ANY
      author: calherries
      comment: Added 0.47.0 - Add join-alias to the report_dashboardcard.visualization_settings.column_settings field refs
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.AddJoinAliasToDashboardCardColumnSettingsFieldRefs"

  - changeSet:
      id: v47.00-045
      validCheckSum: ANY
      author: calherres
      comment: Added 0.47.0 - Migrate dashboard revision dashboard cards' visualization_settings.column_settings field refs from legacy format
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.RevisionMigrateLegacyDashboardCardColumnSettingsFieldRefs"

  - changeSet:
      id: v47.00-046
      validCheckSum: ANY
      author: calherries
      comment: Added 0.47.0 - Add join-alias to dashboard revision dashboard cards' visualization_settings.column_settings field refs
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.RevisionAddJoinAliasToDashboardCardColumnSettingsFieldRefs"

  - changeSet:
      id: v47.00-050
      validCheckSum: 8:a5d516f2b5ea92f401387646b49a9950
      author: tsmacdonald
      comment: Added 0.47.0 - table.is_upload
      changes:
        - addColumn:
            tableName: metabase_table
            columns:
              - column:
                  name: is_upload
                  type: boolean
                  defaultValueBoolean: false
                  remarks: 'Was the table created from user-uploaded (i.e., from a CSV) data?'
                  constraints:
                    nullable: false

  - changeSet:
      id: v47.00-051
      validCheckSum: 8:83a8b7ad58b2deb0732e671db51fa608
      author: noahmoss
      comment: Added 0.47.0 - Drop foreign key constraint on connection_impersonations.db_id
      changes:
        - dropForeignKeyConstraint:
            baseTableName: connection_impersonations
            constraintName: fk_conn_impersonation_db_id
      rollback:
        - addForeignKeyConstraint:
            baseTableName: connection_impersonations
            baseColumnNames: db_id
            referencedTableName: metabase_database
            referencedColumnNames: id
            constraintName: fk_conn_impersonation_db_id
            onDelete: CASCADE

  - changeSet:
      id: v47.00-052
      validCheckSum: 8:d170bef8f707027360cf08fb55e91452
      author: noahmoss
      comment: Added 0.47.0 - Drop foreign key constraint on connection_impersonations.group_id
      changes:
        - dropForeignKeyConstraint:
            baseTableName: connection_impersonations
            constraintName: fk_conn_impersonation_group_id
      rollback:
        - addForeignKeyConstraint:
            baseTableName: connection_impersonations
            baseColumnNames: group_id
            referencedTableName: permissions_group
            referencedColumnNames: id
            constraintName: fk_conn_impersonation_group_id
            onDelete: CASCADE

  - changeSet:
      id: v47.00-053
      validCheckSum: 8:3b52631c2c82b88043b840391c7d9ef0
      author: noahmoss
      comment: Added 0.47.0 -- connection_impersonations index for db_id column
      changes:
        - createIndex:
            tableName: connection_impersonations
            columns:
              - column:
                  name: db_id
            indexName: idx_conn_impersonations_db_id

  - changeSet:
      id: v47.00-054
      validCheckSum: 8:5404d7e3781f0dfcc984676ea434c842
      author: noahmoss
      comment: Added 0.47.0 -- connection_impersonations index for group_id column
      changes:
        - createIndex:
            tableName: connection_impersonations
            columns:
              - column:
                  name: group_id
            indexName: idx_conn_impersonations_group_id

  - changeSet:
      id: v47.00-055
      validCheckSum: 8:295c4477995058b93eba2857090eb6f6
      author: noahmoss
      comment: Added 0.47.0 - unique constraint for connection impersonations
      changes:
        - addUniqueConstraint:
            tableName: connection_impersonations
            columnNames: group_id, db_id
            constraintName: conn_impersonation_unique_group_id_db_id
      rollback:
        - dropUniqueConstraint:
            tableName: connection_impersonations
            constraintName: conn_impersonation_unique_group_id_db_id

  - changeSet:
      id: v47.00-056
      validCheckSum: 8:bd965141f770a65982ecebab51a565e9
      author: noahmoss
      comment: Added 0.47.0 - re-add foreign key constraint on connection_impersonations.db_id
      changes:
        - addForeignKeyConstraint:
            baseTableName: connection_impersonations
            baseColumnNames: db_id
            referencedTableName: metabase_database
            referencedColumnNames: id
            constraintName: fk_conn_impersonation_db_id
            onDelete: CASCADE

  - changeSet:
      id: v47.00-057
      validCheckSum: 8:fe79acdba9db58709b6fffbb7aac2844
      author: noahmoss
      comment: Added 0.47.0 - re-add foreign key constraint on connection_impersonations.group_id
      changes:
        - addForeignKeyConstraint:
            baseTableName: connection_impersonations
            baseColumnNames: group_id
            referencedTableName: permissions_group
            referencedColumnNames: id
            constraintName: fk_conn_impersonation_group_id
            onDelete: CASCADE

  - changeSet:
      id: v47.00-058
      validCheckSum: 8:05731b3e62deb09c64b60bc10031d206
      author: qnkhuat
      comment: 'Drop parameter_card.entity_id'
      changes:
        - dropColumn:
            tableName: parameter_card
            columnName: entity_id
      rollback:
        - addColumn:
            tableName: parameter_card
            columns:
              - column:
                  remarks: Random NanoID tag for unique identity.
                  name: entity_id
                  type: char(21)
                  constraints:
                    nullable: true
                    unique: true

  - changeSet:
      id: v47.00-059
      validCheckSum: 8:123cf42eed168444f88418f071d2730f
      author: piranha
      comment: 'Drops not null from dashboard_tab.entity_id since it breaks drop-entity-ids command'
      changes:
        - dropNotNullConstraint:
            tableName: dashboard_tab
            columnName: entity_id
            columnDataType: char(21)
      rollback: # noop, and 'drop not null' is a noop if it's dropped already

  - changeSet:
      id: v48.00-001
      validCheckSum: ANY
      author: qnkhuat
      comment: Added 0.47.0 - Migrate database.options to database.settings
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.MigrateDatabaseOptionsToSettings"

  - changeSet:
      id: v48.00-002
      validCheckSum: 8:deceb81591f51f2d7253976f247e36cc
      author: qnkhuat
      comment: Added 0.47.0 - drop metabase_database.options
      changes:
        - dropColumn:
            tableName: metabase_database
            columnName: options
      rollback:
        - addColumn:
            tableName: metabase_database
            columns:
              - column:
                  name: options
                  type: ${text.type}
                  remarks: "Serialized JSON containing various options like QB behavior."

  - changeSet:
      id: v48.00-003
      validCheckSum: 8:da33cde0f1f93eed56c0f6d9ac2007df
      author: qnkhuat
      comment: Added 0.48.0 - drop computation_job_result table
      changes:
          - dropTable:
              tableName: computation_job_result
      rollback: # no rollback needed since this table has been unused since 2018

  - changeSet:
      id: v48.00-004
      validCheckSum: 8:d0b1d7cc179c332b7e31f065325b7275
      author: qnkhuat
      comment: Added 0.48.0 - drop computation_job table
      changes:
          - dropTable:
              tableName: computation_job
      rollback: # no rollback needed since this table has been unused since 2018

  - changeSet:
      id: v48.00-005
      validCheckSum: 8:a570f2e1d90a302bc207c00e3776eaaf
      author: qnkhuat
      comment: Added 0.48.0 - Add query_execution.action_id
      changes:
        - addColumn:
            tableName: query_execution
            columns:
              - column:
                  name: action_id
                  type: integer
                  remarks: 'The ID of the action associated with this query execution, if any.'

  - changeSet:
      id: v48.00-006
      validCheckSum: 8:cf1413241565a186bf98eece35d519bf
      author: qnkhuat
      comment: Added 0.48.0 - Index query_execution.action_id
      changes:
        - createIndex:
            tableName: query_execution
            indexName: idx_query_execution_action_id
            columns:
              column:
                name: action_id

  - changeSet:
      id: v48.00-007
      validCheckSum: 8:15d05ceba05e5b7d25d351fb6ec5b100
      author: qnkhuat
      comment: Added 0.48.0 - Add revision.most_recent
      changes:
        - addColumn:
            tableName: revision
            columns:
              - column:
                  name: most_recent
                  type: boolean
                  defaultValueBoolean: false
                  remarks: 'Whether a revision is the most recent one'
                  constraints:
                    nullable: false

  - changeSet:
      id: v48.00-008
      validCheckSum: 8:c0a512701d6dfd5cc1c4a689919be074
      author: qnkhuat
      comment: Set revision.most_recent = true for latest revisions
      changes:
        - sql:
            dbms: postgresql,h2
            sql: >-
              UPDATE revision r
              SET most_recent = true
              WHERE (model, model_id, timestamp) IN (
                                 SELECT model, model_id, MAX(timestamp)
                                 FROM revision
                                 GROUP BY model, model_id);
          # mysql and mariadb does not allow update on a table that is in the select part
          # so it we join for them
        - sql:
            dbms: mysql,mariadb
            sql: >-
              UPDATE revision r
              JOIN (
                  SELECT model, model_id, MAX(timestamp) AS max_timestamp
                  FROM revision
                  GROUP BY model, model_id
              ) AS subquery
              ON r.model = subquery.model AND r.model_id = subquery.model_id AND r.timestamp = subquery.max_timestamp
              SET r.most_recent = true;
      rollback: # nothing to do since the most_recent will be dropped anyway

  - changeSet:
      id: v48.00-009
      validCheckSum: 8:dfd90256380263274ea7f5cc0c5ed413
      author: calherries
      comment: Added 0.48.0 - Create table_privileges table
      changes:
        - createTable:
            tableName: table_privileges
            remarks: Table for user and role privileges by table
            columns:
              - column:
                  name: table_id
                  type: int
                  remarks: 'Table ID'
                  constraints:
                    foreignKeyName: fk_table_privileges_table_id
                    nullable: false
                    referencedTableName: metabase_table
                    referencedColumnNames: id
                    deleteCascade: true
              - column:
                  name: role
                  type: varchar(255)
                  remarks: 'Role name. NULL indicates the privileges are the current user''s'
              - column:
                  name: select
                  type: boolean
                  remarks: 'Privilege to select from the table'
                  constraints:
                    nullable: false
                  defaultValue: false
              - column:
                  name: update
                  type: boolean
                  remarks: 'Privilege to update records in the table'
                  constraints:
                    nullable: false
                  defaultValue: false
              - column:
                  name: insert
                  type: boolean
                  remarks: 'Privilege to insert records into the table'
                  constraints:
                    nullable: false
                  defaultValue: false
              - column:
                  name: delete
                  type: boolean
                  remarks: 'Privilege to delete records from the table'
                  constraints:
                    nullable: false
                  defaultValue: false
            uniqueConstraints:
              - unique:
                  columnNames: table_id, role
                  name: uq_table_privileges_table_id_role


  - changeSet:
      id: v48.00-010
      validCheckSum: 8:da6117039b6e0249b710cc3160af982d
      author: qnkhuat
      comment: Remove ON UPDATE for revision.timestamp on mysql, mariadb
      preConditions:
          - onFail: MARK_RAN
          - dbms:
              type: mysql,mariadb
      changes:
          - sql:
                sql: ALTER TABLE `revision` CHANGE `timestamp` `timestamp` timestamp(6) NOT NULL DEFAULT current_timestamp(6);
      rollback: # no need

  - changeSet:
      id: v48.00-011
      validCheckSum: 8:65ef87949a7e9555fabaf69069806ee0
      author: qnkhuat
      comment: Index revision.most_recent
      changes:
        - createIndex:
            tableName: revision
            indexName: idx_revision_most_recent
            columns:
              column:
                name: most_recent

  - changeSet:
      id: v48.00-013
      validCheckSum: 8:145eb766e2d49e95f31d8a08df8ff776
      author: qnkhuat
      comment: Index unindexed FKs for postgres
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: postgresql
      changes:
          - sql:
              sql: >-
                  CREATE INDEX IF NOT EXISTS idx_action_made_public_by_id ON action (made_public_by_id);
                  CREATE INDEX IF NOT EXISTS idx_action_model_id ON action (model_id);
                  CREATE INDEX IF NOT EXISTS idx_application_permissions_revision_user_id ON application_permissions_revision (user_id);
                  CREATE INDEX IF NOT EXISTS idx_collection_permission_graph_revision_user_id ON collection_permission_graph_revision (user_id);
                  CREATE INDEX IF NOT EXISTS idx_core_session_user_id ON core_session (user_id);
                  CREATE INDEX IF NOT EXISTS idx_dashboard_tab_dashboard_id ON dashboard_tab (dashboard_id);
                  CREATE INDEX IF NOT EXISTS idx_dimension_human_readable_field_id ON dimension (human_readable_field_id);
                  CREATE INDEX IF NOT EXISTS idx_metabase_database_creator_id ON metabase_database (creator_id);
                  CREATE INDEX IF NOT EXISTS idx_model_index_creator_id ON model_index (creator_id);
                  CREATE INDEX IF NOT EXISTS idx_native_query_snippet_creator_id ON native_query_snippet (creator_id);
                  CREATE INDEX IF NOT EXISTS idx_permissions_revision_user_id ON permissions_revision (user_id);
                  CREATE INDEX IF NOT EXISTS idx_persisted_info_creator_id ON persisted_info (creator_id);
                  CREATE INDEX IF NOT EXISTS idx_persisted_info_database_id ON persisted_info (database_id);
                  CREATE INDEX IF NOT EXISTS idx_pulse_dashboard_id ON pulse (dashboard_id);
                  CREATE INDEX IF NOT EXISTS idx_pulse_card_dashboard_card_id ON pulse_card (dashboard_card_id);
                  CREATE INDEX IF NOT EXISTS idx_pulse_channel_recipient_pulse_channel_id ON pulse_channel_recipient (pulse_channel_id);
                  CREATE INDEX IF NOT EXISTS idx_pulse_channel_recipient_user_id ON pulse_channel_recipient (user_id);
                  CREATE INDEX IF NOT EXISTS idx_query_action_database_id ON query_action (database_id);
                  CREATE INDEX IF NOT EXISTS idx_report_card_database_id ON report_card (database_id);
                  CREATE INDEX IF NOT EXISTS idx_report_card_made_public_by_id ON report_card (made_public_by_id);
                  CREATE INDEX IF NOT EXISTS idx_report_card_table_id ON report_card (table_id);
                  CREATE INDEX IF NOT EXISTS idx_report_dashboard_made_public_by_id ON report_dashboard (made_public_by_id);
                  CREATE INDEX IF NOT EXISTS idx_report_dashboardcard_action_id ON report_dashboardcard (action_id);
                  CREATE INDEX IF NOT EXISTS idx_report_dashboardcard_dashboard_tab_id ON report_dashboardcard (dashboard_tab_id);
                  CREATE INDEX IF NOT EXISTS idx_revision_user_id ON revision (user_id);
                  CREATE INDEX IF NOT EXISTS idx_sandboxes_card_id ON sandboxes (card_id);
                  CREATE INDEX IF NOT EXISTS idx_sandboxes_permission_id ON sandboxes (permission_id);
                  CREATE INDEX IF NOT EXISTS idx_secret_creator_id ON secret (creator_id);
                  CREATE INDEX IF NOT EXISTS idx_timeline_creator_id ON timeline (creator_id);
                  CREATE INDEX IF NOT EXISTS idx_timeline_event_creator_id ON timeline_event (creator_id);
      rollback: # no need

  - changeSet:
      id: v48.00-014
      validCheckSum: 8:b2c1361f1dc14c2390a1dc25a4a86311
      author: calherries
      comment: Added 0.48.0 - Create table_privileges.table_id index
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: postgresql
      changes:
        - createIndex:
            indexName: idx_table_privileges_table_id
            tableName: table_privileges
            columns:
              - column:
                  name: table_id
      rollback: # not needed, it will be removed with the table

  - changeSet:
      id: v48.00-015
      validCheckSum: 8:6f58cf60c8048bb39bbf6128058ff85e
      author: calherries
      comment: Added 0.48.0 - Create table_privileges.role index
      changes:
        - createIndex:
            indexName: idx_table_privileges_role
            tableName: table_privileges
            columns:
              - column:
                  name: role
      rollback: # not needed, it will be removed with the table

  - changeSet:
      id: v48.00-016
      validCheckSum: 8:ea2cb901edad5cf3a1250bdd2a9b0866
      author: calherries
      comment: Added 0.48.0 - Change the type of collection.slug to varchar(510)
      changes:
        - modifyDataType:
            tableName: collection
            columnName: slug
            newDataType: varchar(510)
      rollback:
        - modifyDataType:
            tableName: collection
            columnName: slug
            newDataType: varchar(254)

  - changeSet:
      id: v48.00-018
      validCheckSum: 8:efae52e7403f39c1458f53e885b4393d
      author: noahmoss
      comment: Add new recent_views table
      changes:
        - createTable:
            tableName: recent_views
            remarks: Used to store recently viewed objects for each user
            columns:
              - column:
                  name: id
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: user_id
                  type: int
                  remarks: The user associated with this view
                  constraints:
                    nullable: false
                    referencedTableName: core_user
                    referencedColumnNames: id
                    foreignKeyName: fk_recent_views_ref_user_id
              - column:
                  name: model
                  type: varchar(16)
                  remarks: The name of the model that was viewed
                  constraints:
                    nullable: false
              - column:
                  name: model_id
                  type: int
                  remarks: The ID of the model that was viewed
                  constraints:
                    nullable: false
              - column:
                  name: timestamp
                  type: DATETIME
                  remarks: The time a view was recorded
                  constraints:
                    nullable: false

  - changeSet:
      id: v48.00-019
      validCheckSum: 8:c3866a4b7cfbb49d4b626dc2fd750935
      author: nemanjaglumac
      comment: 'Collection color is removed in 0.48.0'
      changes:
        - dropColumn:
            tableName: collection
            columnName: color
      rollback:
        - addColumn:
            tableName: collection
            columns:
              - column:
                  name: color
                  type: char(7)
                  remarks: 'Seven-character hex color for this Collection, including the preceding hash sign.'
                  constraints:
                    nullable: false
                  defaultValue: '#31698A'

  - changeSet:
      id: v48.00-020
      validCheckSum: 8:2c410019e1834304131ff57278003d35
      author: noahmoss
      comment: Added 0.48.0 - Create recent_views.user_id index
      changes:
        - createIndex:
            indexName: idx_recent_views_user_id
            tableName: recent_views
            columns:
              - column:
                  name: user_id
      rollback: # not needed, it will be removed with the table

  - changeSet:
      id: v48.00-021
      validCheckSum: 8:a1543239e39c70dc9bab3bbc303242b1
      author: piranha
      comment: 'Cards store Metabase version used to create them'
      changes:
        - addColumn:
            tableName: report_card
            columns:
              - column:
                  name: metabase_version
                  type: varchar(100)
                  remarks: 'Metabase version used to create the card.'

  - changeSet:
      id: v48.00-022
      validCheckSum: ANY
      author: johnswanson
      comment: Migrate migrate-click-through to a custom migration
      preConditions:
        - onFail: MARK_RAN
        - sqlCheck:
            expectedResult: 0
            sql: SELECT count(*) FROM data_migrations WHERE id = 'migrate-click-through';
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.MigrateClickThrough"

  - changeSet:
      id: v48.00-023
      validCheckSum: ANY
      author: piranha
      comment: Data migration migrate-remove-admin-from-group-mapping-if-needed
      preConditions:
        - onFail: MARK_RAN
        - sqlCheck:
            expectedResult: 0
            sql: SELECT count(*) FROM data_migrations WHERE id = 'migrate-remove-admin-from-group-mapping-if-needed';
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.MigrateRemoveAdminFromGroupMappingIfNeeded"

  - changeSet:
      id: v48.00-024
      validCheckSum: 8:fab2a51d73c66cea059d55a6fea8bb2f
      author: piranha
      comment: All data migrations were transferred to custom_migrations!
      changes:
        - dropTable:
            tableName: data_migrations
      rollback:
        - sql:
            sql: >-
              CREATE TABLE data_migrations (
                id varchar(254) primary key,
                timestamp ${timestamp_type} not null
              );
              INSERT INTO data_migrations VALUES
                  ('set-card-database-and-table-ids', current_timestamp),
                  ('set-mongodb-databases-ssl-false', current_timestamp),
                  ('set-default-schemas', current_timestamp),
                  ('set-admin-email', current_timestamp),
                  ('remove-database-sync-activity-entries', current_timestamp),
                  ('remove-duplicate-fk-entries', current_timestamp),
                  ('update-dashboards-to-new-grid', current_timestamp),
                  ('migrate-field-visibility-type', current_timestamp),
                  ('fix-dashboard-cards-without-positions', current_timestamp),
                  ('migrate-fk-metadata', current_timestamp),
                  ('create-raw-tables', current_timestamp),
                  ('migrate-base-types', current_timestamp),
                  ('migrate-field-types', current_timestamp),
                  ('fix-invalid-field-types', current_timestamp),
                  ('add-users-to-default-permissions-groups', current_timestamp),
                  ('add-admin-group-root-entry', current_timestamp),
                  ('add-databases-to-magic-permissions-groups', current_timestamp),
                  ('fix-legacy-magic-group-names', current_timestamp),
                  ('remove-trailing-slashes-from-site-url-setting', current_timestamp),
                  ('copy-site-url-setting-and-remove-trailing-slashes', current_timestamp),
                  ('migrate-query-executions', current_timestamp),
                  ('drop-old-query-execution-table', current_timestamp),
                  ('ensure-protocol-specified-in-site-url', current_timestamp),
                  ('populate-card-database-id', current_timestamp),
                  ('migrate-humanization-setting', current_timestamp),
                  ('populate-card-read-permissions', current_timestamp),
                  ('mark-category-fields-as-list', current_timestamp),
                  ('repopulate-card-read-permissions', current_timestamp),
                  ('add-legacy-sql-directive-to-bigquery-sql-cards', current_timestamp),
                  ('clear-ldap-user-local-passwords', current_timestamp),
                  ('add-migrated-collections', current_timestamp),
                  ('migrate-map-regions', current_timestamp),
                  ('migrate-click-through', current_timestamp),
                  ('migrate-remove-admin-from-group-mapping-if-needed', current_timestamp);

  - changeSet:
      id: v48.00-025
      validCheckSum: 8:a2fa9ab0913b9e4b97dff91f973344d6
      author: piranha
      comment: 'Revisions store Metabase version used to create them'
      changes:
        - addColumn:
            tableName: revision
            columns:
              - column:
                  name: metabase_version
                  type: varchar(100)
                  remarks: 'Metabase version used to create the revision.'

  - changeSet:
      id: v48.00-026
      validCheckSum: 8:7c8330e861c16997780a9b0881144b26
      author: lbrdnk
      comment: Set semantic_type with value type/Number to null (#18754)
      changes:
        - update:
            tableName: metabase_field
            columns:
              - column:
                  name: semantic_type
                  value: NULL
            where: semantic_type = 'type/Number'
      rollback:

  # this is a no op, it was previously used to Drop parameter_card.entity_id,
  # now it's moved to v47.00-058
  # this is still here because we want the change set id to be consistent
  # see #35239 for details
  - changeSet:
      id: v48.00-027
      author: qnkhuat
      validCheckSum: ANY
      comment: 'No op migration'
      changes:
        - sql:
            sql: SELECT 1;
      rollback:

  - changeSet:
      id: v48.00-028
      validCheckSum: 8:818119252c2e7877bbf46aec40fab160
      author: noahmoss
      comment: Add new audit_log table
      changes:
        - createTable:
            tableName: audit_log
            remarks: Used to store application events for auditing use cases
            columns:
              - column:
                  name: id
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: topic
                  type: varchar(32)
                  remarks: The topic of a given audit event
                  constraints:
                    nullable: false
              - column:
                  name: timestamp
                  type: ${timestamp_type}
                  remarks: The time an event was recorded
                  constraints:
                    nullable: false
              - column:
                  name: end_timestamp
                  type: ${timestamp_type}
                  remarks: The time an event ended, if applicable
                  constraints:
                    nullable: true
              - column:
                  name: user_id
                  type: int
                  remarks: The user who performed an action or triggered an event
                  constraints:
                    nullable: true
              - column:
                  name: model
                  type: varchar(32)
                  remarks: The name of the model this event applies to (e.g. Card, Dashboard), if applicable
                  constraints:
                    nullable: true
              - column:
                  name: model_id
                  type: int
                  remarks: The ID of the model this event applies to, if applicable
                  constraints:
                    nullable: true
              - column:
                  name: details
                  type: ${text.type}
                  remarks: A JSON map with metadata about the event
                  constraints:
                    nullable: false

  - changeSet:
      id: v48.00-029
      validCheckSum: 8:1994760ab0950e7f591c40e887295e1a
      author: noahmoss
      comment: Added 0.48.0 - new view v_audit_log
      changes:
        - sqlFile:
            dbms: postgresql
            path: instance_analytics_views/audit_log/v1/postgres-audit_log.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: instance_analytics_views/audit_log/v1/mysql-audit_log.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: instance_analytics_views/audit_log/v1/h2-audit_log.sql
            relativeToChangelogFile: true
      rollback:
        - sql:
            sql: drop view if exists v_audit_log;

  - changeSet:
      id: v48.00-030
      validCheckSum: 8:965d6479698fe55f2f6799be552b5edb
      author: noahmoss
      comment: Added 0.48.0 - new view v_content
      changes:
        - sqlFile:
            dbms: postgresql
            path: instance_analytics_views/content/v1/postgres-content.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: instance_analytics_views/content/v1/mysql-content.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: instance_analytics_views/content/v1/h2-content.sql
            relativeToChangelogFile: true
      rollback:
        - sql:
            sql: drop view if exists v_content;

  - changeSet:
      id: v48.00-031
      validCheckSum: 8:721bedb0dd362793a1a216cf3e552f3b
      author: noahmoss
      comment: Added 0.48.0 - new view v_dashboardcard
      changes:
        - sqlFile:
            path: instance_analytics_views/dashboardcard/v1/dashboardcard.sql
            relativeToChangelogFile: true
      rollback:
        - sql:
            sql: drop view if exists v_dashboardcard;

  - changeSet:
      id: v48.00-032
      validCheckSum: 8:64d52462def7bb6981a3b6a40d42e67e
      author: noahmoss
      comment: Added 0.48.0 - new view v_group_members
      changes:
        - sqlFile:
            path: instance_analytics_views/group_members/v1/group_members.sql
            relativeToChangelogFile: true
      rollback:
        - sql:
            sql: drop view if exists v_group_members;

  - changeSet:
      id: v48.00-033
      validCheckSum: 8:7ac57373a0fba4bd9613c242702c863d
      author: noahmoss
      comment: Added 0.48.0 - new view v_subscriptions for postgres
      changes:
        - sqlFile:
            dbms: postgresql
            path: instance_analytics_views/subscriptions/v1/postgres-subscriptions.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: instance_analytics_views/subscriptions/v1/mysql-subscriptions.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: instance_analytics_views/subscriptions/v1/h2-subscriptions.sql
            relativeToChangelogFile: true
      rollback:
        - sql:
            sql: drop view if exists v_subscriptions;

  - changeSet:
      id: v48.00-034
      validCheckSum: 8:1c268d93ce69eaee11e3ecdf9951449a
      author: noahmoss
      comment: Added 0.48.0 - new view v_users
      changes:
        - sqlFile:
            dbms: postgresql
            path: instance_analytics_views/users/v1/postgres-users.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: instance_analytics_views/users/v1/mysql-users.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: instance_analytics_views/users/v1/h2-users.sql
            relativeToChangelogFile: true
      rollback:
        - sql:
            sql: drop view if exists v_users;

  - changeSet:
      id: v48.00-035
      validCheckSum: 8:c0276764af3e1b4b5b0c4e5fdc979e60
      author: noahmoss
      comment: Added 0.48.0 - new view v_alerts
      changes:
        - sqlFile:
            dbms: postgresql
            path: instance_analytics_views/alerts/v1/postgres-alerts.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: instance_analytics_views/alerts/v1/mysql-alerts.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: instance_analytics_views/alerts/v1/h2-alerts.sql
            relativeToChangelogFile: true
      rollback:
        - sql:
            sql: drop view if exists v_alerts;

  - changeSet:
      id: v48.00-036
      validCheckSum: 8:8a35e1bdf0738ccac5da8062d6671dd0
      author: noahmoss
      comment: Added 0.48.0 - new view v_databases
      changes:
        - sqlFile:
            path: instance_analytics_views/databases/v1/databases.sql
            relativeToChangelogFile: true
      rollback:
        - sql:
            sql: drop view if exists v_databases;

  - changeSet:
      id: v48.00-037
      validCheckSum: 8:a4b6ebd594b4663a6a888211f36ce6c3
      author: noahmoss
      comment: Added 0.48.0 - new view v_fields
      changes:
        - sqlFile:
            dbms: postgresql
            path: instance_analytics_views/fields/v1/postgres-fields.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: instance_analytics_views/fields/v1/mysql-fields.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: instance_analytics_views/fields/v1/h2-fields.sql
            relativeToChangelogFile: true
      rollback:
        - sql:
            sql: drop view if exists v_fields;

  - changeSet:
      id: v48.00-038
      validCheckSum: 8:a24f4bcd3336e79d1c8ef33ab81c0db3
      author: noahmoss
      comment: Added 0.48.0 - new view v_query_log
      changes:
        - sqlFile:
            dbms: postgresql
            path: instance_analytics_views/query_log/v1/postgres-query_log.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: instance_analytics_views/query_log/v1/mysql-query_log.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: instance_analytics_views/query_log/v1/h2-query_log.sql
            relativeToChangelogFile: true
      rollback:
        - sql:
            sql: drop view if exists v_query_log;

  - changeSet:
      id: v48.00-039
      validCheckSum: 8:b43481a01df86830c4cb1adb8189d400
      author: noahmoss
      comment: Added 0.48.0 - new view v_tables
      changes:
        - sqlFile:
            dbms: postgresql
            path: instance_analytics_views/tables/v1/postgres-tables.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: instance_analytics_views/tables/v1/mysql-tables.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: instance_analytics_views/tables/v1/h2-tables.sql
            relativeToChangelogFile: true
      rollback:
        - sql:
            sql: drop view if exists v_tables;

  - changeSet:
      id: v48.00-040
      validCheckSum: 8:b8842eac1c7cba6e997d4d288306e36c
      author: noahmoss
      comment: Added 0.48.0 - new view v_view_log
      changes:
        - sqlFile:
            dbms: postgresql
            path: instance_analytics_views/view_log/v1/postgres-view_log.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: instance_analytics_views/view_log/v1/mysql-view_log.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: instance_analytics_views/view_log/v1/h2-view_log.sql
            relativeToChangelogFile: true
      rollback:
        - sql:
            sql: drop view if exists v_view_log;

  - changeSet:
      id: v48.00-045
      validCheckSum: 8:874f14ae26d742448d8dd2b47dc8aa3d
      author: qwef
      comment: Added 0.48.0 - add is_sandboxed to query_execution
      changes:
        - addColumn:
            tableName: query_execution
            columns:
              - column:
                  name: is_sandboxed
                  type: boolean
                  remarks: "Is query from a sandboxed user"
                  constraints:
                    nullable: true

  - changeSet:
      id: v48.00-046
      validCheckSum: 8:4bb11295621890202e066cd15de93a52
      author: noahmoss
      comment: Added 0.48.0 - new indexes to optimize audit v2 queries
      changes:
        - sqlFile:
            dbms: postgresql
            path: instance_analytics_views/indexes/v1/postgres-indexes.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql
            path: instance_analytics_views/indexes/v1/mysql-indexes.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mariadb
            path: instance_analytics_views/indexes/v1/mariadb-indexes.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: instance_analytics_views/indexes/v1/h2-indexes.sql
            relativeToChangelogFile: true
      rollback:
        # Only MySQL needes a rollback because all the other DBs support "CREATE INDEX IF NOT EXISTS"
        - sqlFile:
            dbms: mysql
            path: instance_analytics_views/indexes/v1/mysql-rollback.sql
            relativeToChangelogFile: true

  - changeSet:
      id: v48.00-047
      validCheckSum: 8:2b18bed0e1ae18dd7b26a0770dac54c0
      author: noahmoss
      comment: Drop foreign key on recent_views so that it can be recreated with onDelete policy
      changes:
        - dropForeignKeyConstraint:
            baseTableName: recent_views
            constraintName: fk_recent_views_ref_user_id
      rollback:
        - addForeignKeyConstraint:
            baseTableName: recent_views
            constraintName: fk_recent_views_ref_user_id
            referencedTableName: core_user
            baseColumnNames: user_id
            referencedColumnNames: id
            onDelete: CASCADE

  - changeSet:
      id: v48.00-048
      validCheckSum: 8:872e632a8ffa42eb2969f77823e8bfc8
      author: noahmoss
      comment: Add foreign key on recent_views with onDelete CASCADE
      changes:
        - addForeignKeyConstraint:
            baseTableName: recent_views
            constraintName: fk_recent_views_ref_user_id
            referencedTableName: core_user
            baseColumnNames: user_id
            referencedColumnNames: id
            onDelete: CASCADE
      rollback:
        - dropForeignKeyConstraint:
            baseTableName: recent_views
            constraintName: fk_recent_views_ref_user_id

  - changeSet:
      id: v48.00-049
      validCheckSum: 8:853f2a24c53470bf2d9e85b1246bab7b
      author: noahmoss
      comment: Migrate data from activity to audit_log
      changes:
        - sql:
            dbms: postgresql
            sql: >-
              INSERT INTO audit_log (topic, timestamp, user_id, model, model_id, details)
              SELECT
                topic,
                timestamp,
                user_id,
                model,
                model_id,
                details::jsonb || json_strip_nulls(json_build_object('database_id', database_id, 'table_id', table_id))::jsonb
              FROM activity;
        - sql:
            dbms: mysql,mariadb
            sql: >-
              INSERT INTO audit_log (topic, timestamp, user_id, model, model_id, details)
              SELECT
                  topic,
                  timestamp,
                  user_id,
                  model,
                  model_id,
                  JSON_MERGE(
                      details,
                      JSON_OBJECT('database_id', database_id, 'table_id', table_id)
                  )
              FROM activity;
        - sql:
            dbms: h2
            sql: >-
              INSERT INTO audit_log (topic, timestamp, user_id, model, model_id, details)
              SELECT
                  topic,
                  timestamp,
                  user_id,
                  model,
                  model_id,
                  JSON_OBJECT(
                    'database_id': database_id,
                    'table_id': table_id
                    ABSENT ON NULL
                  )
              FROM activity;
      rollback: # not necessary

  - changeSet:
      id: v48.00-050
      validCheckSum: 8:d41d8cd98f00b204e9800998ecf8427e
      author: noahmoss
      comment: Added 0.48.0 - no-op migration to remove audit DB and collection on downgrade
      changes:
        - comment: "No operation performed for this changeset on execution."
      rollback:
        - sql: DELETE FROM metabase_database WHERE is_audit = TRUE;
        - sql: DELETE FROM collection WHERE type = 'instance_analytics';

  - changeSet:
      id: v48.00-051
      validCheckSum: 8:5f5d1fd5b6153a6613511fd8f765737d
      author: calherries
      comment: Migrate metabase_field when the fk target field is inactive
      changes:
        - sql:
            dbms: mariadb,mysql
            sql: >-
              UPDATE metabase_field AS a
              JOIN metabase_field AS b ON b.id = a.fk_target_field_id
              SET a.fk_target_field_id = NULL,
                  a.semantic_type = NULL
              WHERE b.active = FALSE;
        - sql:
            dbms: postgresql,h2
            sql: >-
              UPDATE metabase_field
              SET fk_target_field_id = NULL,
                  semantic_type = NULL
              WHERE fk_target_field_id IN (
                  SELECT id
                  FROM metabase_field
                  WHERE active = FALSE
              );
      rollback: # no change

  - changeSet:
      id: v48.00-053
      validCheckSum: 8:8b41162170f6d712871b2ee9221adc1a
      author: johnswanson
      comment: Increase length of `activity.model` to fit longer model names
      changes:
        - modifyDataType:
            tableName: activity
            columnName: model
            newDataType: VARCHAR(32)
      rollback: # not necessary

  - changeSet:
      id: v48.00-054
      validCheckSum: 8:d41d8cd98f00b204e9800998ecf8427e
      author: escherize
      comment: Added 0.48.0 - no-op migration to remove Internal Metabase User on downgrade
      changes:
        - comment: "No operation performed for this changeset on execution."
      rollback:
        - sql: DELETE FROM core_user WHERE id = 13371338;

  - changeSet:
      id: v48.00-055
      validCheckSum: 8:fd36092d50982fbf31ce16757c16e47e
      author: noahmoss
      comment: Added 0.48.0 - new view v_tasks
      changes:
        - sqlFile:
            dbms: postgresql
            path: instance_analytics_views/tasks/v1/postgres-tasks.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: instance_analytics_views/tasks/v1/mysql-tasks.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: instance_analytics_views/tasks/v1/h2-tasks.sql
            relativeToChangelogFile: true
      rollback:
        - sql:
            sql: drop view if exists v_tasks;

  - changeSet:
      id: v48.00-056
      validCheckSum: 8:229e8058cc8309053b344bbfdb042405
      author: noahmoss
      comment: 'Adjust view_log schema for Audit Log v2'
      changes:
        - addColumn:
            tableName: view_log
            columns:
              - column:
                  name: has_access
                  type: boolean
                  constraints:
                    nullable: true
                  remarks: 'Whether the user who initiated the view had read access to the item being viewed.'

  - changeSet:
      id: v48.00-057
      validCheckSum: 8:8e32153df1031ea12005d58ce1674873
      author: noahmoss
      comment: 'Adjust view_log schema for Audit Log v2'
      changes:
        - addColumn:
            tableName: view_log
            columns:
              - column:
                  name: context
                  type: varchar(32)
                  constraints:
                    nullable: true
                  remarks: 'The context of the view, can be collection, question, or dashboard. Only for cards.'

  - changeSet:
      id: v48.00-059
      validCheckSum: 8:fd8b5031dbbf69c4588ce2699eb20f33
      author: qwef
      comment: 'Update the namespace of any audit collections that are already loaded'
      changes:
        - sql:
            sql: UPDATE collection SET namespace = 'analytics' WHERE entity_id = 'okNLSZKdSxaoG58JSQY54' OR entity_id = 'vG58R8k-QddHWA7_47umn'
      rollback: # not necessary

  - changeSet:
      id: v48.00-060
      validCheckSum: 8:a59027f5494811033ce77cd0ba05d6bd
      author: noahmoss
      comment: Added 0.48.0 - task_history.started_at
      changes:
        - createIndex:
            indexName: idx_task_history_started_at
            tableName: task_history
            columns:
              - column:
                  name: started_at

  - changeSet:
      id: v48.00-061
      validCheckSum: 8:9b9939aad6ca12f7cf4dfa85dae6eb1c
      author: piranha
      comment: 'Adds query_execution.cache_hash -> query_cache.query_hash'
      changes:
        - addColumn:
            tableName: query_execution
            columns:
              - column:
                  name: cache_hash
                  type: ${blob.type}
                  constraints:
                    nullable: true
                  remarks: 'Hash of normalized query, calculated in middleware.cache'

  # this index was added in migration 95, but during our split migration work in #34400 we didn't include this index
  # in the sql initialization, so we need to recreate one here for new instances running 48+
  - changeSet:
      id: v48.00-067
      validCheckSum: 8:e7cd8168533c58c865dacf320e819218
      author: qnkhuat
      comment: 'Add unique constraint idx_databasechangelog_id_author_filename'
      preConditions:
        - onFail: MARK_RAN
        # If we're dumping the migration as a SQL file or trying to force-migrate we can't check the preconditions
        # so just go ahead and skip the entire thing. This is a non-critical migration
        - onUpdateSQL: IGNORE
        - and:
          - sqlCheck:
              expectedResult: 0
              sql: SELECT count(*) FROM (SELECT count(*) FROM DATABASECHANGELOG GROUP BY ID, AUTHOR, FILENAME HAVING count(*) > 1) t1
          - or:
            - and:
              - dbms:
                  type: postgresql
              - sqlCheck:
                  expectedResult: 0
                  sql: >-
                    SELECT COUNT(*)
                    FROM pg_indexes
                    WHERE tablename = 'databasechangelog' AND
                          indexname = 'idx_databasechangelog_id_author_filename';
            - and:
              - dbms:
                  type: h2
              - sqlCheck:
                  expectedResult: 0
                  sql: >-
                    SELECT COUNT(*)
                    FROM INFORMATION_SCHEMA.INDEXES
                    WHERE TABLE_NAME = 'DATABASECHANGELOG' AND
                          INDEX_NAME = 'IDX_DATABASECHANGELOG_ID_AUTHOR_FILENAME_INDEX_1';
            - and:
              - dbms:
                  type: mysql,mariadb
              - not:
                - indexExists:
                    tableName: ${databasechangelog.name}
                    indexName: idx_databasechangelog_id_author_filename
      changes:
        - addUniqueConstraint:
            constraintName: idx_databasechangelog_id_author_filename
            tableName: ${databasechangelog.name}
            columnNames: id, author, filename
      rollback:
        - dropUniqueConstraint:
            tableName: ${databasechangelog.name}
            constraintName: idx_databasechangelog_id_author_filename

  - changeSet:
      id: v49.00-000
      author: qnkhuat
      comment: Remove leagcy pulses
      changes:
        - sql: DELETE FROM pulse where dashboard_id is null and alert_condition is null;
      # pulse has been deprecated in v38(~2.5 years ago), even the UI to view it is broken
      # so we don't need to worry about recovering it on rollback
      rollback:

  - changeSet:
      id: v49.00-003
      author: johnswanson
      comment: Add a `type` to users
      changes:
        - addColumn:
            columns:
              - column:
                  name: type
                  type: varchar(64)
                  constraints:
                    nullable: false
                  defaultValue: 'personal'
                  remarks: The type of user
            tableName: core_user

  - changeSet:
      id: v49.00-004
      author: johnswanson
      comment: Add a table for API keys
      changes:
        - createTable:
            tableName: api_key
            remarks: An API Key
            columns:
              - column:
                  remarks: The ID of the API Key itself
                  name: id
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: user_id
                  type: int
                  remarks: The ID of the user who this API Key acts as
                  constraints:
                    nullable: false
                    referencedTableName: core_user
                    referencedColumnNames: id
                    foreignKeyName: fk_api_key_user_id
              - column:
                  remarks: The hashed API key
                  name: key
                  type: varchar(254)
                  constraints:
                    nullable: false
              - column:
                  remarks: The first 7 characters of the unhashed key
                  name: key_prefix
                  type: varchar(7)
                  constraints:
                    nullable: false
                    unique: true
              - column:
                  remarks: The ID of the user that created this API key
                  name: created_by
                  type: integer
                  constraints:
                    nullable: false
                    referencedTableName: core_user
                    referencedColumnNames: id
                    foreignKeyName: fk_api_key_created_by_user_id
              - column:
                  remarks: The timestamp when the key was created
                  name: created_at
                  type: ${timestamp_type}
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false
              - column:
                  remarks: The timestamp when the key was last updated
                  name: updated_at
                  type: ${timestamp_type}
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false

  - changeSet:
      id: v49.00-005
      author: johnswanson
      comment: Add an index on `api_key.created_by`
      rollback: # not necessary, will be removed with the table
      changes:
        - createIndex:
            tableName: api_key
            indexName: idx_api_key_created_by
            columns:
              column:
                name: created_by

  - changeSet:
      id: v49.00-006
      author: johnswanson
      comment: Add an index on `api_key.user_id`
      rollback: # not necessary, will be removed with the table
      changes:
        - createIndex:
            tableName: api_key
            indexName: idx_api_key_user_id
            columns:
              column:
                name: user_id

  - changeSet:
      id: v49.00-007
      author: johnswanson
      comment: Set the `type` of the internal user
      changes:
        - sql:
            sql: UPDATE core_user SET type='internal' WHERE id=13371338;
      rollback: # not necessary

  - changeSet:
      id: v49.00-008
      author: qnkhuat
      comment: Add metabase_field.database_indexed
      changes:
        - addColumn:
            tableName: metabase_field
            columns:
              - column:
                  name: database_indexed
                  type: boolean
                  constraints:
                    nullable: true
                  remarks: 'If the database supports indexing, this column indicate whether or not a field is indexed, or is the 1st column in a composite index'

  - changeSet:
      id: v49.00-009
      author: adam-james
      comment: Migrate pulse_card.include_csv to 'true' when the joined card.display is 'table'
      changes:
        - sql:
            dbms: mariadb,mysql
            sql: >-
              UPDATE pulse_card AS pc
              JOIN report_card AS rc ON rc.id = pc.card_id
              SET pc.include_csv = TRUE
              WHERE rc.display = 'table';
        - sql:
            dbms: postgresql,h2
            sql: >-
              UPDATE pulse_card pc
              SET include_csv = TRUE
              WHERE pc.card_id IN (
                  SELECT rc.id
                  FROM report_card rc
                  WHERE rc.display = 'table'
                  AND rc.id = pc.card_id
              );
      rollback: # no change

  - changeSet:
      id: v49.00-010
      author: johnswanson
      comment: Add a name to API Keys
      changes:
        - addColumn:
            tableName: api_key
            columns:
              - column:
                  name: name
                  type: varchar(254)
                  constraints:
                    nullable: false
                    unique: true
                  remarks: 'The user-defined name of the API key.'

  - changeSet:
      id: v49.00-011
      author: qnkhuat
      comment: Add metabase_table.database_require_filter
      changes:
        - addColumn:
            tableName: metabase_table
            columns:
              - column:
                  name: database_require_filter
                  type: boolean
                  constraints:
                    nullable: true
                  remarks: 'If true, the table requires a filter to be able to query it'

  - changeSet:
      id: v49.00-012
      author: qnkhuat
      comment: Add metabase_field.database_partitioned
      changes:
        - addColumn:
            tableName: metabase_field
            columns:
              - column:
                  name: database_partitioned
                  type: boolean
                  constraints:
                    nullable: true
                  remarks: 'Whether the table is partitioned by this field'

  - changeSet:
      id: v49.00-013
      author: johnswanson
      comment: Add `api_key.updated_by_id`
      rollback: # will be removed with the table
      changes:
        - addColumn:
            tableName: api_key
            columns:
              - column:
                  remarks: The ID of the user that last updated this API key
                  name: updated_by_id
                  type: integer
                  constraints:
                    # no default and nullable: false for a new column? yikes! But this should probably be ok, because
                    # we don't yet have any UI for creating a new API key.
                    nullable: false
                    referencedTableName: core_user
                    referencedColumnNames: id
                    foreignKeyName: fk_api_key_updated_by_id_user_id

  - changeSet:
      id: v49.00-014
      author: johnswanson
      comment: Add an index on `api_key.updated_by_id`
      rollback: # not necessary, will be removed with the table
      changes:
        - createIndex:
            tableName: api_key
            indexName: idx_api_key_updated_by_id
            columns:
              column:
                name: updated_by_id

  - changeSet:
      id: v49.00-015
      author: johnswanson
      comment: Rename `created_by` to `creator_id`
      rollback: # not necessary, will be removed with the table
      changes:
        - renameColumn:
            tableName: api_key
            columnDataType: integer
            oldColumnName: created_by
            newColumnName: creator_id

  - changeSet:
      id: v49.00-016
      author: noahmoss
      comment: >-
        Added 0.49.0 - modify type of action.archived from boolean to
        ${boolean.type} on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - modifyDataType:
            tableName: action
            columnName: archived
            newDataType: ${boolean.type}
      rollback:
        - modifyDataType:
            tableName: action
            columnName: archived
            newDataType: boolean
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-017
      author: noahmoss
      comment: Add NOT NULL constraint to action.archived
      changes:
        - addNotNullConstraint:
            columnDataType: ${boolean.type}
            tableName: action
            columnName: archived
            defaultNullValue: false
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-018
      author: noahmoss
      comment: Add default value to action.archived
      changes:
        - addDefaultValue:
            defaultValueBoolean: false
            tableName: action
            columnName: archived
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-019
      author: noahmoss
      comment: >-
        Added 0.49.0 - modify type of metabase_field.json_unfolding from
        boolean to ${boolean.type} on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - modifyDataType:
            tableName: metabase_field
            columnName: json_unfolding
            newDataType: ${boolean.type}
      rollback:
        - modifyDataType:
            tableName: metabase_field
            columnName: json_unfolding
            newDataType: boolean
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-020
      author: noahmoss
      comment: Add NOT NULL constraint to metabase_field.json_unfolding
      changes:
        - addNotNullConstraint:
            columnDataType: ${boolean.type}
            tableName: metabase_field
            columnName: json_unfolding
            defaultNullValue: false
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-021
      author: noahmoss
      comment: Add default value to metabase_field.json_unfolding
      changes:
        - addDefaultValue:
            defaultValueBoolean: false
            tableName: metabase_field
            columnName: json_unfolding
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-022
      author: noahmoss
      comment: >-
        Added 0.49.0 - modify type of metabase_field.database_is_auto_increment
        from boolean to ${boolean.type} on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - modifyDataType:
            tableName: metabase_field
            columnName: database_is_auto_increment
            newDataType: ${boolean.type}
      rollback:
        - modifyDataType:
            tableName: metabase_field
            columnName: database_is_auto_increment
            newDataType: boolean
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-023
      author: noahmoss
      comment: Add NOT NULL constraint to metabase_field.database_is_auto_increment
      changes:
        - addNotNullConstraint:
            columnDataType: ${boolean.type}
            tableName: metabase_field
            columnName: database_is_auto_increment
            defaultNullValue: false
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-024
      author: noahmoss
      comment: Add default value to metabase_field.database_is_auto_increment
      changes:
        - addDefaultValue:
            defaultValueBoolean: false
            tableName: metabase_field
            columnName: database_is_auto_increment
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-025
      author: noahmoss
      comment: >-
        Added 0.49.0 - modify type of report_dashboard.auto_apply_filters
        from boolean to ${boolean.type} on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - modifyDataType:
            tableName: report_dashboard
            columnName: auto_apply_filters
            newDataType: ${boolean.type}
      rollback:
        - modifyDataType:
            tableName: report_dashboard
            columnName: auto_apply_filters
            newDataType: boolean
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-026
      author: noahmoss
      comment: Add NOT NULL constraint to report_dashboard.auto_apply_filters
      changes:
        - addNotNullConstraint:
            columnDataType: ${boolean.type}
            tableName: report_dashboard
            columnName: auto_apply_filters
            defaultNullValue: true
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-027
      author: noahmoss
      comment: Add default value to report_dashboard.auto_apply_filters
      changes:
        - addDefaultValue:
            defaultValueBoolean: true
            tableName: report_dashboard
            columnName: auto_apply_filters
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-028
      author: noahmoss
      comment: >-
        Added 0.49.0 - modify type of metabase_database.is_audit
        from boolean to ${boolean.type} on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - modifyDataType:
            tableName: metabase_database
            columnName: is_audit
            newDataType: ${boolean.type}
      rollback:
        - modifyDataType:
            tableName: metabase_database
            columnName: is_audit
            newDataType: boolean
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-029
      author: noahmoss
      comment: Add NOT NULL constraint to metabase_database.is_audit
      changes:
        - addNotNullConstraint:
            columnDataType: ${boolean.type}
            tableName: metabase_database
            columnName: is_audit
            defaultNullValue: false
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-030
      author: noahmoss
      comment: Add default value to metabase_database.is_audit
      changes:
        - addDefaultValue:
            defaultValueBoolean: false
            tableName: metabase_database
            columnName: is_audit
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-031
      author: noahmoss
      comment: >-
        Added 0.49.0 - modify type of metabase_table.is_upload
        from boolean to ${boolean.type} on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - modifyDataType:
            tableName: metabase_table
            columnName: is_upload
            newDataType: ${boolean.type}
      rollback:
        - modifyDataType:
            tableName: metabase_table
            columnName: is_upload
            newDataType: boolean
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-032
      author: noahmoss
      comment: Add NOT NULL constraint to metabase_table.is_upload
      changes:
        - addNotNullConstraint:
            columnDataType: ${boolean.type}
            tableName: metabase_table
            columnName: is_upload
            defaultNullValue: false
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-033
      author: noahmoss
      comment: Add default value to metabase_table.is_upload
      changes:
        - addDefaultValue:
            defaultValueBoolean: false
            tableName: metabase_table
            columnName: is_upload
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-034
      author: noahmoss
      comment: >-
        Added 0.49.0 - modify type of revision.most_recent
        from boolean to ${boolean.type} on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - modifyDataType:
            tableName: revision
            columnName: most_recent
            newDataType: ${boolean.type}
      rollback:
        - modifyDataType:
            tableName: revision
            columnName: most_recent
            newDataType: boolean
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-035
      author: noahmoss
      comment: >-
        Added 0.49.0 - modify type of revision.most_recent
        from boolean to ${boolean.type} on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - modifyDataType:
            tableName: revision
            columnName: most_recent
            newDataType: ${boolean.type}
      rollback:
        - modifyDataType:
            tableName: revision
            columnName: most_recent
            newDataType: boolean
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-036
      author: noahmoss
      comment: Add NOT NULL constraint to revision.most_recent
      changes:
        - addNotNullConstraint:
            columnDataType: ${boolean.type}
            tableName: revision
            columnName: most_recent
            defaultNullValue: false
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-037
      author: noahmoss
      comment: Add default value to revision.most_recent
      changes:
        - addDefaultValue:
            defaultValueBoolean: false
            tableName: revision
            columnName: most_recent
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-038
      author: noahmoss
      comment: >-
        Added 0.49.0 - modify type of table_privileges.select
        from boolean to ${boolean.type} on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - modifyDataType:
            tableName: table_privileges
            columnName: select
            newDataType: ${boolean.type}
      rollback:
        - modifyDataType:
            tableName: table_privileges
            columnName: select
            newDataType: boolean
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-039
      author: noahmoss
      comment: Add NOT NULL constraint to table_privileges.select
      changes:
        - addNotNullConstraint:
            columnDataType: ${boolean.type}
            tableName: table_privileges
            columnName: select
            defaultNullValue: false
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-040
      author: noahmoss
      comment: Add default value to table_privileges.select
      changes:
        - addDefaultValue:
            defaultValueBoolean: false
            tableName: table_privileges
            columnName: select
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-041
      author: noahmoss
      comment: >-
        Added 0.49.0 - modify type of table_privileges.update
        from boolean to ${boolean.type} on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - modifyDataType:
            tableName: table_privileges
            columnName: update
            newDataType: ${boolean.type}
      rollback:
        - modifyDataType:
            tableName: table_privileges
            columnName: update
            newDataType: boolean
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-042
      author: noahmoss
      comment: Add NOT NULL constraint to table_privileges.update
      changes:
        - addNotNullConstraint:
            columnDataType: ${boolean.type}
            tableName: table_privileges
            columnName: update
            defaultNullValue: false
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-043
      author: noahmoss
      comment: Add default value to table_privileges.update
      changes:
        - addDefaultValue:
            defaultValueBoolean: false
            tableName: table_privileges
            columnName: update
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-044
      author: noahmoss
      comment: >-
        Added 0.49.0 - modify type of table_privileges.insert
        from boolean to ${boolean.type} on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - modifyDataType:
            tableName: table_privileges
            columnName: insert
            newDataType: ${boolean.type}
      rollback:
        - modifyDataType:
            tableName: table_privileges
            columnName: insert
            newDataType: boolean
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-045
      author: noahmoss
      comment: Add NOT NULL constraint to table_privileges.insert
      changes:
        - addNotNullConstraint:
            columnDataType: ${boolean.type}
            tableName: table_privileges
            columnName: insert
            defaultNullValue: false
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-046
      author: noahmoss
      comment: Add default value to table_privileges.insert
      changes:
        - addDefaultValue:
            defaultValueBoolean: false
            tableName: table_privileges
            columnName: insert
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-047
      author: noahmoss
      comment: >-
        Added 0.49.0 - modify type of table_privileges.delete
        from boolean to ${boolean.type} on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - modifyDataType:
            tableName: table_privileges
            columnName: delete
            newDataType: ${boolean.type}
      rollback:
        - modifyDataType:
            tableName: table_privileges
            columnName: delete
            newDataType: boolean
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-048
      author: noahmoss
      comment: Add NOT NULL constraint to table_privileges.delete
      changes:
        - addNotNullConstraint:
            columnDataType: ${boolean.type}
            tableName: table_privileges
            columnName: delete
            defaultNullValue: false
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-049
      author: noahmoss
      comment: Add default value to table_privileges.delete
      changes:
        - addDefaultValue:
            defaultValueBoolean: false
            tableName: table_privileges
            columnName: delete
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-050
      author: noahmoss
      comment: >-
        Added 0.49.0 - modify type of query_execution.is_sandboxed
        from boolean to ${boolean.type} on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - modifyDataType:
            tableName: query_execution
            columnName: is_sandboxed
            newDataType: ${boolean.type}
      rollback:
        - modifyDataType:
            tableName: query_execution
            columnName: is_sandboxed
            newDataType: boolean
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-051
      author: noahmoss
      comment: >-
        Added 0.49.0 - modify type of view_log.has_access
        from boolean to ${boolean.type} on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - modifyDataType:
            tableName: view_log
            columnName: has_access
            newDataType: ${boolean.type}
      rollback:
        - modifyDataType:
            tableName: view_log
            columnName: has_access
            newDataType: boolean
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-052
      author: noahmoss
      comment: >-
        Added 0.49.0 - modify type of metabase_field.database_indexed
        from boolean to ${boolean.type} on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - modifyDataType:
            tableName: metabase_field
            columnName: database_indexed
            newDataType: ${boolean.type}
      rollback:
        - modifyDataType:
            tableName: metabase_field
            columnName: database_indexed
            newDataType: boolean
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-053
      author: noahmoss
      comment: >-
        Added 0.49.0 - modify type of metabase_table.database_require_filter
        from boolean to ${boolean.type} on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - modifyDataType:
            tableName: metabase_table
            columnName: database_require_filter
            newDataType: ${boolean.type}
      rollback:
        - modifyDataType:
            tableName: metabase_table
            columnName: database_require_filter
            newDataType: boolean
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.00-059
      author: qnkhuat
      comment: Added 0.49.0 - unify type of time columns
      validCheckSum: ANY
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.UnifyTimeColumnsType"

  - changeSet:
      id: v49.00-060
      author: qnkhuat
      comment: >-
        Added 0.49.0 - modify type of metabase_field.database_partitioned
        from boolean to ${boolean.type} on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - modifyDataType:
            tableName: metabase_field
            columnName: database_partitioned
            newDataType: ${boolean.type}
      rollback:
        - modifyDataType:
            tableName: metabase_field
            columnName: database_partitioned
            newDataType: boolean
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2023-01-24T12:00:00
      author: piranha
      comment: >-
        This significantly speeds up api.database/autocomplete-fields query
        and is an improvement for issue 30588.
        H2 does not support this: https://github.com/h2database/h2database/issues/3535
        Mariadb does not support this.
        Mysql says it does, but reports an error during migration.
      dbms: postgresql
      changes:
        - createIndex:
            tableName: metabase_field
            indexName: idx_field_name_lower
            columns:
              - column:
                  name: lower(name)
                  computed: true
      rollback:
        - dropIndex:
            tableName: metabase_field
            indexName: idx_field_name_lower

  - changeSet:
      id: v49.2024-01-22T11:50:00
      author: qnkhuat
      comment: Add `report_card.type`
      changes:
        - addColumn:
            tableName: report_card
            columns:
              - column:
                  remarks: The type of card, could be 'question', 'model', 'metric'
                  name: type
                  type: varchar(16)
                  defaultValue: "question"
                  constraints:
                    nullable: false

  - changeSet:
      id: v49.2024-01-22T11:51:00
      author: qnkhuat
      comment: Backfill `report_card.type`
      changes:
        - sql:
            sql: >-
              UPDATE report_card
              SET type = 'model'
              WHERE dataset is true
      rollback: # no need, the column will be dropped

  - changeSet:
      id: v49.2024-01-22T11:52:00
      author: qnkhuat
      comment: Backfill `report_card.type`
      validCheckSum: ANY
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.CardRevisionAddType"

  - changeSet:
      id: v49.2024-01-29T19:26:40
      author: adam-james
      comment: Add width setting to Dashboards
      changes:
        - addColumn:
            tableName: report_dashboard
            columns:
              - column:
                  name: width
                  type: varchar(16)
                  defaultValue: "fixed"
                  remarks: "The value of the dashboard's width setting can be fixed or full. New dashboards will be set to fixed"

  - changeSet:
      id: v49.2024-01-29T19:30:00
      author: adam-james
      comment: Update existing report_dashboard width values to full
      changes:
        - update:
            tableName: report_dashboard
            columns:
              - column:
                  name: width
                  value: "full"
      rollback: []

  - changeSet:
      id: v49.2024-01-29T19:56:40
      author: adam-james
      comment: Dashboard width setting must have a value
      changes:
        - addNotNullConstraint:
            tableName: report_dashboard
            columnName: width
            columnDatatype: varchar(16)
            defaultNullvalue: "full"
            remarks: "If for some reason an existing dashboard has null width value it is set to full"

  - changeSet:
      id: v49.2024-01-29T19:59:12
      author: adam-james
      comment: Add default value to report_dashboard.width for mysql and mariadb
      changes:
        - addDefaultValue:
            defaultValue: "fixed"
            tableName: report_dashboard
            columnName: width
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2024-02-02T11:27:49
      author: oisincoveney
      comment: >-
        Add report_card.initially_published_at
      changes:
        - addColumn:
            tableName: report_card
            columns:
              - column:
                  name: initially_published_at
                  type: ${timestamp_type}
                  constraints:
                    nullable: true
                  remarks: The timestamp when the card was first published in a static embed

  - changeSet:
        id: v49.2024-02-02T11:28:36
        author: oisincoveney
        comment: >-
          Add report_dashboard.initially_published_at
        changes:
          - addColumn:
              tableName: report_dashboard
              columns:
                - column:
                    name: initially_published_at
                    type: ${timestamp_type}
                    constraints:
                      nullable: true
                    remarks: The timestamp when the dashboard was first published in a static embed

  - changeSet:
      id: v49.2024-02-07T21:52:01
      author: noahmoss
      comment: Added 0.49.0 - updated view v_view_log
      changes:
        - sqlFile:
            dbms: postgresql
            path: instance_analytics_views/view_log/v2/postgres-view_log.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: instance_analytics_views/view_log/v2/mysql-view_log.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: instance_analytics_views/view_log/v2/h2-view_log.sql
            relativeToChangelogFile: true
      rollback:
        - sqlFile:
            dbms: postgresql
            path: instance_analytics_views/view_log/v1/postgres-view_log.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: instance_analytics_views/view_log/v1/mysql-view_log.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: instance_analytics_views/view_log/v1/h2-view_log.sql
            relativeToChangelogFile: true

  - changeSet:
      id: v49.2024-02-07T21:52:02
      author: noahmoss
      comment: Added 0.49.0 - updated view v_audit_log
      changes:
        - sqlFile:
            dbms: postgresql
            path: instance_analytics_views/audit_log/v2/postgres-audit_log.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: instance_analytics_views/audit_log/v2/mysql-audit_log.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: instance_analytics_views/audit_log/v2/h2-audit_log.sql
            relativeToChangelogFile: true
      rollback:
        - sqlFile:
            dbms: postgresql
            path: instance_analytics_views/audit_log/v1/postgres-audit_log.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: instance_analytics_views/audit_log/v1/mysql-audit_log.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: instance_analytics_views/audit_log/v1/h2-audit_log.sql
            relativeToChangelogFile: true

  - changeSet:
      id: v49.2024-02-07T21:52:03
      author: noahmoss
      comment: Added 0.49.0 - updated view v_group_members
      changes:
        - sqlFile:
            path: instance_analytics_views/group_members/v2/group_members.sql
            relativeToChangelogFile: true
      rollback:
        - sqlFile:
            dbms: postgresql
            path: instance_analytics_views/group_members/v1/group_members.sql
            relativeToChangelogFile: true

  - changeSet:
      id: v49.2024-02-07T21:52:04
      author: noahmoss
      comment: Added 0.49.0 - updated view v_query_log
      changes:
        - sqlFile:
            dbms: postgresql
            path: instance_analytics_views/query_log/v2/postgres-query_log.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: instance_analytics_views/query_log/v2/mysql-query_log.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: instance_analytics_views/query_log/v2/h2-query_log.sql
            relativeToChangelogFile: true
      rollback:
        - sqlFile:
            dbms: postgresql
            path: instance_analytics_views/query_log/v1/postgres-query_log.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: instance_analytics_views/query_log/v1/mysql-query_log.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: instance_analytics_views/query_log/v1/h2-query_log.sql
            relativeToChangelogFile: true

  - changeSet:
      id: v49.2024-02-07T21:52:05
      author: noahmoss
      comment: Added 0.49.0 - updated view v_users
      changes:
        - sqlFile:
            dbms: postgresql
            path: instance_analytics_views/users/v2/postgres-users.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: instance_analytics_views/users/v2/mysql-users.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: instance_analytics_views/users/v2/h2-users.sql
            relativeToChangelogFile: true
      rollback:
        - sqlFile:
            dbms: postgresql
            path: instance_analytics_views/users/v1/postgres-users.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: instance_analytics_views/users/v1/mysql-users.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: instance_analytics_views/users/v1/h2-users.sql
            relativeToChangelogFile: true

  - changeSet:
      id: v49.2024-02-09T13:55:26
      author: noahmoss
      comment: Set default value for enable-public-sharing to `false` for existing instances with users, if not already set
      preConditions:
        - onFail: MARK_RAN
        - and:
            - or:
                - and:
                    - dbms:
                        type: postgresql
                    - sqlCheck:
                        expectedResult: 0
                        sql: SELECT count(*) FROM setting WHERE key = 'enable-public-sharing';
                - and:
                    - dbms:
                        type: h2
                    - sqlCheck:
                        expectedResult: 0
                        sql: SELECT count(*) FROM setting WHERE "KEY" = 'enable-public-sharing';
                - and:
                    - dbms:
                        type: mysql,mariadb
                    - sqlCheck:
                        expectedResult: 0
                        sql: SELECT count(*) FROM setting WHERE `key` = 'enable-public-sharing';
            - sqlCheck:
                expectedResult: 1
                sql: >
                  SELECT CASE WHEN COUNT(*) > 0 THEN 1 ELSE 0 END FROM core_user;
      changes:
        - sql:
            dbms: postgresql
            sql: INSERT INTO setting (key, value) VALUES ('enable-public-sharing', 'false');
        - sql:
            dbms: mysql,mariadb
            sql: INSERT INTO setting (`key`, value) VALUES ('enable-public-sharing', 'false');
        - sql:
            dbms: h2
            sql: INSERT INTO setting ("KEY", "VALUE") VALUES ('enable-public-sharing', 'false');
      rollback: # not needed

  - changeSet:
      id: v49.2024-03-26T10:23:12
      author: adam-james
      comment: Add pulse_card.format_rows
      changes:
        - addColumn:
            tableName: pulse_card
            columns:
              - column:
                  name: format_rows
                  type: ${boolean.type}
                  defaultValue: true
                  remarks: Whether or not to apply formatting to the rows of the export

  - changeSet:
      id: v49.2024-04-09T10:00:00
      author: qnkhuat
      comment: Drop not null constraint on metabase_database.cache_field_values_schedule
      changes:
        - dropNotNullConstraint:
            tableName: metabase_database
            columnName: cache_field_values_schedule
            columnDataType: varchar(254)
      # nothing because it should always be like this
      rollback:

  - changeSet:
      id: v49.2024-04-09T10:00:01
      author: qnkhuat
      comment: Drop default value on metabase_database.cache_field_values_schedule
      changes:
        - dropDefaultValue:
            tableName: metabase_database
            columnName: cache_field_values_schedule
      # nothing because it should always be like this
      rollback:

  - changeSet:
      id: v49.2024-04-09T10:00:02
      author: qnkhuat
      comment: Add null as default value for metabase_database.cache_field_values_schedule
      changes:
        - addDefaultValue:
            defaultValue: "null"
            tableName: metabase_database
            columnName: cache_field_values_schedule
      # nothing because it should always be like this
      rollback:

  - changeSet:
      id: v49.2024-04-09T10:00:03
      author: qnkhuat
      comment: This clears the schedule for caching field values for databases with period scanning disabled.
      validCheckSum: ANY
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.DeleteScanFieldValuesTriggerForDBThatTurnItOff"

  - changeSet:
      id: v49.2024-05-07T10:00:00
      author: qnkhuat
      comment: Set revision.most_recent = true to latest revision and false to others. A redo of v48.00-008 for mysql
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb
      changes:
        - sql:
            dbms: mysql,mariadb
            sql: >-
              UPDATE revision AS r
              JOIN (
                  SELECT inner_revision.id,
                        ROW_NUMBER() OVER (PARTITION BY inner_revision.model, inner_revision.model_id ORDER BY inner_revision.timestamp DESC, inner_revision.id DESC) AS row_num
                    FROM revision AS inner_revision
                    JOIN (
                          SELECT model, model_id
                          FROM revision
                          WHERE most_recent = true
                          GROUP BY model, model_id
                          HAVING count(*) > 1
                        ) AS infected_revision ON inner_revision.model = infected_revision.model AND inner_revision.model_id = infected_revision.model_id
              ) AS n ON r.id = n.id
              SET r.most_recent = (n.row_num = 1);
      rollback: # nothing

  - changeSet:
      id: v49.2024-05-20T19:10:34
      author: johnswanson
      comment: >-
        Modify type of report_card.collection_preview to ${boolean.type} on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - modifyDataType:
            tableName: report_card
            columnName: collection_preview
            newDataType: ${boolean.type}
      rollback:
        - modifyDataType:
            tableName: report_card
            columnName: collection_preview
            newDataType: boolean
            defaultValueBoolean: true
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2024-05-20T20:37:55
      author: johnswanson
      comment: Add NOT NULL constraint to report_card.collection_preview
      changes:
        - addNotNullConstraint:
            columnDataType: ${boolean.type}
            tableName: report_card
            columnName: collection_preview
            defaultNullValue: true
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb
  - changeSet:
      id: v49.2024-05-20T20:38:34
      author: johnswanson
      comment: Add default value to report_card.collection_preview
      changes:
        - addDefaultValue:
            defaultValueBoolean: true
            tableName: report_card
            columnName: collection_preview
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2024-05-29T09:26:20
      author: johnswanson
      comment: >-
        Modify type of report_card.dataset to ${boolean.type} on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - modifyDataType:
            tableName: report_card
            columnName: dataset
            newDataType: ${boolean.type}
      rollback:
        - modifyDataType:
            tableName: report_card
            columnName: dataset
            newDataType: boolean
            defaultValueBoolean: false
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2024-05-29T09:27:15
      author: johnswanson
      dbms: mysql,mariadb
      comment: Add NOT NULL constraint to report_card.dataset
      changes:
        - addNotNullConstraint:
            columnDataType: ${boolean.type}
            tableName: report_card
            columnName: dataset
            defaultNullValue: false
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2024-05-29T09:28:25
      author: johnswanson
      dbms: mysql,mariadb
      comment: Add default value to report_card.dataset
      changes:
        - addDefaultValue:
            defaultValueBoolean: false
            tableName: report_card
            columnName: dataset
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2024-06-05T09:01:01
      author: johnswanson
      comment: >-
        Modify type of core_user.is_datasetnewb to ${boolean.type} on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - modifyDataType:
            tableName: core_user
            columnName: is_datasetnewb
            newDataType: ${boolean.type}
      rollback:
        - modifyDataType:
            tableName: core_user
            columnName: is_datasetnewb
            newDataType: boolean
            defaultValueBoolean: true
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2024-06-05T09:01:02
      author: johnswanson
      comment: >-
        Add NOT NULL constraint to core_user.is_datasetnewb on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - addNotNullConstraint:
            tableName: core_user
            columnName: is_datasetnewb
            columnDataType: ${boolean.type}
            defaultNullValue: true
      rollback:
        - dropNotNullConstraint:
            tableName: core_user
            columnName: is_datasetnewb
            columnDataType: boolean
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2024-06-05T09:01:03
      author: johnswanson
      comment: >-
        Add default value to core_user.is_datasetnewb on mysql,mariadb
      changes:
        - addDefaultValue:
            tableName: core_user
            columnName: is_datasetnewb
            defaultValueBoolean: true
      dbms: mysql,mariadb
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2024-06-05T09:02:01
      author: johnswanson
      comment: >-
        Modify type of metabase_field.database_required to ${boolean.type} on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - modifyDataType:
            tableName: metabase_field
            columnName: database_required
            newDataType: ${boolean.type}
      rollback:
        - modifyDataType:
            tableName: metabase_field
            columnName: database_required
            newDataType: boolean
            defaultValueBoolean: false
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2024-06-05T09:02:02
      author: johnswanson
      comment: >-
        Add NOT NULL constraint to metabase_field.database_required on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - addNotNullConstraint:
            tableName: metabase_field
            columnName: database_required
            columnDataType: ${boolean.type}
            defaultNullValue: false
      rollback:
        - dropNotNullConstraint:
            tableName: metabase_field
            columnName: database_required
            columnDataType: boolean
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2024-06-05T09:02:03
      author: johnswanson
      comment: >-
        Add default value to metabase_field.database_required on mysql,mariadb
      changes:
        - addDefaultValue:
            tableName: metabase_field
            columnName: database_required
            defaultValueBoolean: false
      dbms: mysql,mariadb
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2024-06-05T09:03:01
      author: johnswanson
      comment: >-
        Modify type of metabase_fieldvalues.has_more_values to ${boolean.type} on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - modifyDataType:
            tableName: metabase_fieldvalues
            columnName: has_more_values
            newDataType: ${boolean.type}
      rollback:
        - modifyDataType:
            tableName: metabase_fieldvalues
            columnName: has_more_values
            newDataType: boolean
            defaultValueBoolean: false
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2024-06-05T09:03:03
      author: johnswanson
      comment: >-
        Add default value to metabase_fieldvalues.has_more_values on mysql,mariadb
      changes:
        - addDefaultValue:
            tableName: metabase_fieldvalues
            columnName: has_more_values
            defaultValueBoolean: false
      dbms: mysql,mariadb
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2024-06-05T09:04:01
      author: johnswanson
      comment: >-
        Modify type of permissions_group_membership.is_group_manager to ${boolean.type} on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - modifyDataType:
            tableName: permissions_group_membership
            columnName: is_group_manager
            newDataType: ${boolean.type}
      rollback:
        - modifyDataType:
            tableName: permissions_group_membership
            columnName: is_group_manager
            newDataType: boolean
            defaultValueBoolean: false
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2024-06-05T09:04:02
      author: johnswanson
      comment: >-
        Add NOT NULL constraint to permissions_group_membership.is_group_manager on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - addNotNullConstraint:
            tableName: permissions_group_membership
            columnName: is_group_manager
            columnDataType: ${boolean.type}
            defaultNullValue: false
      rollback:
        - dropNotNullConstraint:
            tableName: permissions_group_membership
            columnName: is_group_manager
            columnDataType: boolean
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2024-06-05T09:04:03
      author: johnswanson
      comment: >-
        Add default value to permissions_group_membership.is_group_manager on mysql,mariadb
      changes:
        - addDefaultValue:
            tableName: permissions_group_membership
            columnName: is_group_manager
            defaultValueBoolean: false
      dbms: mysql,mariadb
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2024-06-05T09:05:01
      author: johnswanson
      comment: >-
        Modify type of persisted_info.active to ${boolean.type} on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - modifyDataType:
            tableName: persisted_info
            columnName: active
            newDataType: ${boolean.type}
      rollback:
        - modifyDataType:
            tableName: persisted_info
            columnName: active
            newDataType: boolean
            defaultValueBoolean: false
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2024-06-05T09:05:02
      author: johnswanson
      comment: >-
        Add NOT NULL constraint to persisted_info.active on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - addNotNullConstraint:
            tableName: persisted_info
            columnName: active
            columnDataType: ${boolean.type}
            defaultNullValue: false
      rollback:
        - dropNotNullConstraint:
            tableName: persisted_info
            columnName: active
            columnDataType: boolean
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2024-06-05T09:05:03
      author: johnswanson
      comment: >-
        Add default value to persisted_info.active on mysql,mariadb
      changes:
        - addDefaultValue:
            tableName: persisted_info
            columnName: active
            defaultValueBoolean: false
      dbms: mysql,mariadb
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2024-06-05T09:06:01
      author: johnswanson
      comment: >-
        Modify type of report_card.dataset to ${boolean.type} on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - modifyDataType:
            tableName: report_card
            columnName: dataset
            newDataType: ${boolean.type}
      rollback:
        - modifyDataType:
            tableName: report_card
            columnName: dataset
            newDataType: boolean
            defaultValueBoolean: false
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2024-06-05T09:06:02
      author: johnswanson
      comment: >-
        Add NOT NULL constraint to report_card.dataset on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - addNotNullConstraint:
            tableName: report_card
            columnName: dataset
            columnDataType: ${boolean.type}
            defaultNullValue: false
      rollback:
        - dropNotNullConstraint:
            tableName: report_card
            columnName: dataset
            columnDataType: boolean
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2024-06-05T09:06:03
      author: johnswanson
      comment: >-
        Add default value to report_card.dataset on mysql,mariadb
      changes:
        - addDefaultValue:
            tableName: report_card
            columnName: dataset
            defaultValueBoolean: false
      dbms: mysql,mariadb
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2024-06-05T09:07:01
      author: johnswanson
      comment: >-
        Modify type of timeline.archived to ${boolean.type} on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - modifyDataType:
            tableName: timeline
            columnName: archived
            newDataType: ${boolean.type}
      rollback:
        - modifyDataType:
            tableName: timeline
            columnName: archived
            newDataType: boolean
            defaultValueBoolean: false
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2024-06-05T09:07:02
      author: johnswanson
      comment: >-
        Add NOT NULL constraint to timeline.archived on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - addNotNullConstraint:
            tableName: timeline
            columnName: archived
            columnDataType: ${boolean.type}
            defaultNullValue: false
      rollback:
        - dropNotNullConstraint:
            tableName: timeline
            columnName: archived
            columnDataType: boolean
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2024-06-05T09:07:03
      author: johnswanson
      comment: >-
        Add default value to timeline.archived on mysql,mariadb
      changes:
        - addDefaultValue:
            tableName: timeline
            columnName: archived
            defaultValueBoolean: false
      dbms: mysql,mariadb
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2024-06-05T09:08:01
      author: johnswanson
      comment: >-
        Modify type of timeline.default to ${boolean.type} on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - modifyDataType:
            tableName: timeline
            columnName: default
            newDataType: ${boolean.type}
      rollback:
        - modifyDataType:
            tableName: timeline
            columnName: default
            newDataType: boolean
            defaultValueBoolean: false
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2024-06-05T09:08:02
      author: johnswanson
      comment: >-
        Add NOT NULL constraint to timeline.default on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - addNotNullConstraint:
            tableName: timeline
            columnName: default
            columnDataType: ${boolean.type}
            defaultNullValue: false
      rollback:
        - dropNotNullConstraint:
            tableName: timeline
            columnName: default
            columnDataType: boolean
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2024-06-05T09:08:03
      author: johnswanson
      comment: >-
        Add default value to timeline.default on mysql,mariadb
      changes:
        - addDefaultValue:
            tableName: timeline
            columnName: default
            defaultValueBoolean: false
      dbms: mysql,mariadb
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2024-06-05T09:09:01
      author: johnswanson
      comment: >-
        Modify type of timeline_event.archived to ${boolean.type} on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - modifyDataType:
            tableName: timeline_event
            columnName: archived
            newDataType: ${boolean.type}
      rollback:
        - modifyDataType:
            tableName: timeline_event
            columnName: archived
            newDataType: boolean
            defaultValueBoolean: false
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2024-06-05T09:09:02
      author: johnswanson
      comment: >-
        Add NOT NULL constraint to timeline_event.archived on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - addNotNullConstraint:
            tableName: timeline_event
            columnName: archived
            columnDataType: ${boolean.type}
            defaultNullValue: false
      rollback:
        - dropNotNullConstraint:
            tableName: timeline_event
            columnName: archived
            columnDataType: boolean
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2024-06-05T09:09:03
      author: johnswanson
      comment: >-
        Add default value to timeline_event.archived on mysql,mariadb
      changes:
        - addDefaultValue:
            tableName: timeline_event
            columnName: archived
            defaultValueBoolean: false
      dbms: mysql,mariadb
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2024-06-05T09:10:01
      author: johnswanson
      comment: >-
        Modify type of timeline_event.time_matters to ${boolean.type} on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - modifyDataType:
            tableName: timeline_event
            columnName: time_matters
            newDataType: ${boolean.type}
      rollback:
        - modifyDataType:
            tableName: timeline_event
            columnName: time_matters
            newDataType: boolean
            defaultValueBoolean: NULL
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  - changeSet:
      id: v49.2024-06-05T09:10:02
      author: johnswanson
      comment: >-
        Add NOT NULL constraint to timeline_event.time_matters on mysql,mariadb
      dbms: mysql,mariadb
      changes:
        - addNotNullConstraint:
            tableName: timeline_event
            columnName: time_matters
            columnDataType: ${boolean.type}
            defaultNullValue: false
      rollback:
        - dropNotNullConstraint:
            tableName: timeline_event
            columnName: time_matters
            columnDataType: boolean
      preConditions:
        - onFail: MARK_RAN
        - dbms:
            type: mysql,mariadb

  # The changesets from v49.2024-06-27T00:00:00 to v49.2024-06-27T00:00:08 prevent duplicate fields from being
  # created on MySQL and H2. See #44866 for details. Below is an index of the changesets:
  # - v49.2024-06-27T00:00:00: Make metabase_field.name use case-sensitive collation for MySQL
  # - v49.2024-06-27T00:00:01: Add metabase_field.is_defective_duplicate
  # - v49.2024-06-27T00:00:02: Populate metabase_field.is_defective_duplicate
  # - v49.2024-06-27T00:00:03: Drop fk_field_parent_ref_field_id constraint with ON DELETE CASCADE
  # - v49.2024-06-27T00:00:04: Add fk_field_parent_ref_field_id constraint with ON DELETE RESTRICT
  # - v49.2024-06-27T00:00:05: Remove idx_uniq_field_table_id_parent_id_name because it is redundant with idx_unique_field
  # - v49.2024-06-27T00:00:06: Remove the idx_uniq_field_table_id_parent_id_name_2col unique index because it blocks load-from-h2
  # - v49.2024-06-27T00:00:07: Add unique_field_helper column to metabase_field
  # - v49.2024-06-27T00:00:08: Add unique constraint on metabase_field's (name, table_id, unique_field_helper)

  # This is necessary to make unique indexes using metabase_field.name case-sensitive for MySQL.
  - changeSet:
      id: v49.2024-06-27T00:00:00
      author: calherries
      dbms: mysql,mariadb
      comment: Make metabase_field.name use case-sensitive collation for MySQL
      changes:
        - sql:
            sql: >-
              ALTER TABLE metabase_field MODIFY
              name VARCHAR(254)
              CHARACTER SET utf8mb4
              COLLATE utf8mb4_bin;
      rollback:
        - sql:
            sql: >-
              ALTER TABLE metabase_field MODIFY
              name VARCHAR(254)
              CHARACTER SET utf8mb4
              COLLATE utf8mb4_unicode_ci;

  # metabase_field.is_defective_duplicate is a new column that indicates whether a field is a defective duplicate field
  # that should never have been created under Postgres' `idx_uniq_field_table_id_parent_id_name_2col` constraint, but
  # was allowed to be created in MySQL or H2.
  - changeSet:
      id: v49.2024-06-27T00:00:01
      author: calherries
      comment: Add metabase_field.is_defective_duplicate
      changes:
        - addColumn:
            tableName: metabase_field
            columns:
              - column:
                  name: is_defective_duplicate
                  type: ${boolean.type}
                  remarks: "Indicates whether column is a defective duplicate field that should never have been created."
                  constraints:
                    nullable: false
                  defaultValue: false

  - changeSet:
      id: v49.2024-06-27T00:00:02
      author: calherries
      comment: Populate metabase_field.is_defective_duplicate
      changes:
        - sql:
            # idx_uniq_field_table_id_parent_id_name_2col would prevent defective duplicates with Postgres but it
            # can be removed by upgrading from 49 and downgrading again. We need to populate is_defective_duplicate
            # in that case.
            sql: >-
              UPDATE metabase_field mf
              SET is_defective_duplicate = TRUE
              WHERE mf.id IN (
                  SELECT id
                  FROM (
                      SELECT
                          mf.id,
                          ROW_NUMBER() OVER (
                              PARTITION BY mf.table_id, mf.name, mf.parent_id
                              ORDER BY
                                  CASE WHEN mf.active THEN 0 ELSE 1 END,
                                  CASE WHEN mf.nfc_path IS NULL THEN 0 ELSE 1 END,
                                  mf.created_at
                          ) AS rn
                      FROM metabase_field mf
                  ) x
                  WHERE x.rn > 1
              );
      rollback: # No rollback needed since is_defective_duplicate is introduced in 49

  # The next two changesets replace ON DELETE CASCADE with ON DELETE RESTRICT on fk_field_parent_ref_field_id.
  # We need to do this for MySQL because it doesn't support ON DELETE CASCADE in a stored generated column, and we
  # want to use parent_id in the unique_field_helper generated column. Cascading deletes are handled in the
  # application instead.
  - changeSet:
      id: v49.2024-06-27T00:00:03
      author: calherries
      comment: Drop fk_field_parent_ref_field_id constraint with ON DELETE CASCADE
      changes:
        - dropForeignKeyConstraint:
            baseTableName: metabase_field
            constraintName: fk_field_parent_ref_field_id
      rollback:
        - addForeignKeyConstraint:
            baseTableName: metabase_field
            baseColumnNames: parent_id
            referencedTableName: metabase_field
            referencedColumnNames: id
            constraintName: fk_field_parent_ref_field_id
            onDelete: CASCADE

  - changeSet:
      id: v49.2024-06-27T00:00:04
      author: calherries
      comment: Add fk_field_parent_ref_field_id constraint with ON DELETE RESTRICT
      changes:
        - addForeignKeyConstraint:
            baseTableName: metabase_field
            baseColumnNames: parent_id
            referencedTableName: metabase_field
            referencedColumnNames: id
            constraintName: fk_field_parent_ref_field_id
            onDelete: RESTRICT
      rollback:
        - dropForeignKeyConstraint:
            baseTableName: metabase_field
            constraintName: fk_field_parent_ref_field_id

  - changeSet:
      id: v49.2024-06-27T00:00:05
      author: calherries
      comment: Remove idx_uniq_field_table_id_parent_id_name because it is redundant with idx_unique_field
      changes:
        - dropUniqueConstraint:
            tableName: metabase_field
            constraintName: idx_uniq_field_table_id_parent_id_name
      rollback:
        - addUniqueConstraint:
            tableName: metabase_field
            columnNames: table_id, parent_id, name
            constraintName: idx_uniq_field_table_id_parent_id_name

  - changeSet:
      id: v49.2024-06-27T00:00:06
      author: calherries
      dbms: postgresql
      comment: Remove the idx_uniq_field_table_id_parent_id_name_2col unique index because it blocks load-from-h2
      changes:
        - sql:
            sql: DROP INDEX IF EXISTS idx_uniq_field_table_id_parent_id_name_2col;
      rollback: # We deliberately don't restore this constraint because otherwise it can block downgrading to 48 after load-from-h2

  # Previously we had two unique constraints on metabase_field's name, table_id, and parent_id columns.
  #
  # 1. `idx_uniq_field_table_id_parent_id_name` is a unique constraint on (name, table_id, parent_id)
  #    Since NULL <> NULL, it only applies to fields where parent_id IS NOT NULL.
  #    Worse, the constraint was not case-sensitive for MySQL.
  #
  # 2. `idx_uniq_field_table_id_parent_id_name_2col` is a Postgres-only unique constraint on
  #    `(name, table_id) WHERE parent_id IS NULL`. There was no equivalent constraint for H2 or MySQL because only
  #    Postgres supports partial indexes. The following changesets introduce an equivalent constraint for H2 and
  #    MySQL by adding a constraint that uses a generated column to handle NULL parent_id values.
  #
  # At the same time, we exclude fields where is_defective_duplicate=TRUE from the above constraints.
  #
  # The following two changesets add a new column `unique_field_helper` to `metabase_field` and a unique constraint
  # `idx_unique_field`.
  # The combination of `unique_field_helper` and `idx_unique_field` achieves two things:
  # 1. It enforces the conditional constraints:
  #   - if parent_id IS NULL, then (table_id, name) is unique. (like idx_uniq_field_table_id_parent_id_name_col2)
  #   - if parent_id IS NOT NULL, then (table_id, name, parent_id) is unique. (like idx_uniq_field_table_id_parent_id_name)
  # 2. It only enforces the constraints when is_defective_duplicate = FALSE

  - changeSet:
      id: v49.2024-06-27T00:00:07
      author: calherries
      comment: Add unique_field_helper column to metabase_field
      changes:
        - sql:
            dbms: postgresql
            sql: >-
              ALTER TABLE metabase_field ADD COLUMN unique_field_helper INTEGER GENERATED ALWAYS AS (
                CASE WHEN is_defective_duplicate = TRUE THEN NULL ELSE (CASE WHEN parent_id IS NULL THEN 0 ELSE parent_id END) END
              ) STORED;
        - sql:
            dbms: h2
            sql: >-
              ALTER TABLE metabase_field ADD COLUMN unique_field_helper INTEGER GENERATED ALWAYS AS (
                CASE WHEN is_defective_duplicate = TRUE THEN NULL ELSE (CASE WHEN parent_id IS NULL THEN 0 ELSE parent_id END) END
              );
        - sql:
            dbms: mysql,mariadb
            sql: >-
              ALTER TABLE metabase_field ADD COLUMN unique_field_helper INTEGER GENERATED ALWAYS AS (
                CASE WHEN is_defective_duplicate = TRUE THEN NULL ELSE (CASE WHEN parent_id IS NULL THEN 0 ELSE parent_id END) END
              ) STORED;
      rollback:
        - sql:
            dbms: postgresql,h2,mysql,mariadb
            sql: ALTER TABLE metabase_field DROP COLUMN unique_field_helper;

  - changeSet:
      id: v49.2024-06-27T00:00:08
      author: calherries
      comment: Add unique constraint on metabase_field's (name, table_id, unique_field_helper)
      changes:
        - addUniqueConstraint:
            tableName: metabase_field
            constraintName: idx_unique_field
            columnNames: name, table_id, unique_field_helper
      rollback:
        - dropUniqueConstraint:
            tableName: metabase_field
            constraintName: idx_unique_field

  - changeSet:
      id: v49.2024-06-27T00:00:09
      author: calherries
      comment: Set is_defective_duplicate=TRUE fields that shouldn't exist to have active=FALSE
      changes:
        - sql:
            sql: >-
              UPDATE metabase_field
              SET active = false
              WHERE is_defective_duplicate AND (nfc_path = concat('["', name, '"]') OR nfc_path IS NULL);
      rollback: # No rollback needed since this is backward compatible

  - changeSet:
      id: v49.2024-08-21T08:33:06
      author: johnswanson
      comment: Add permissions.perm_value
      changes:
        - addColumn:
            columns:
              - column:
                  name: perm_value
                  type: varchar(64)
                  remarks: The value of the permission
                  constraints:
                    nullable: true
            tableName: permissions

  - changeSet:
      id: v49.2024-08-21T08:33:07
      author: johnswanson
      comment: Add permissions.perm_type
      changes:
        - addColumn:
            columns:
              - column:
                  name: perm_type
                  type: varchar(64)
                  remarks: The type of the permission
                  constraints:
                    nullable: true
            tableName: permissions

  - changeSet:
      id: v49.2024-08-21T08:33:08
      author: johnswanson
      comment: Add permissions.collection_id
      changes:
        - addColumn:
            tableName: permissions
            columns:
              - column:
                  name: collection_id
                  type: int
                  remarks: The linked collection, if applicable
                  constraints:
                    nullable: true

  # FK constraint is added separately because deleteCascade doesn't work in addColumn -- see #14321
  - changeSet:
      id: v49.2024-08-21T08:33:09
      author: johnswanson
      comment: Add `permissions.collection_id` foreign key constraint
      changes:
        - addForeignKeyConstraint:
            baseTableName: permissions
            baseColumnNames: collection_id
            referencedTableName: collection
            referencedColumnNames: id
            constraintName: fk_permissions_ref_collection_id
            onDelete: CASCADE

  - changeSet:
      id: v49.2024-08-21T08:33:10
      author: johnswanson
      comment: Populate `perm_value`, `perm_type`, and `collection_id` on permissions
      rollback: # not needed.
      changes:
        - sqlFile:
            dbms: postgresql
            path: permissions/collection-access.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: permissions/collection-access-mariadb.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: permissions/collection-access-h2.sql
            relativeToChangelogFile: true

  - changeSet:
      id: v49.2024-08-21T08:33:11
      author: johnswanson
      comment: Create index on `permissions.collection_id`
      rollback: # deleted with the column
      changes:
        - createIndex:
            tableName: permissions
            columns:
              - column:
                  name: collection_id
            indexName: idx_permissions_collection_id


  - changeSet:
      id: v49.2024-08-21T08:33:12
      author: johnswanson
      comment: Index on `permissions.perm_type`
      rollback: # deleted with the column
      changes:
        - createIndex:
            tableName: permissions
            columns:
              - column:
                  name: perm_type
            indexName: idx_permissions_perm_type

  - changeSet:
      id: v49.2024-08-21T08:33:13
      author: johnswanson
      comment: Index on `permissions.perm_value`
      rollback: # deleted with the column
      changes:
        - createIndex:
            tableName: permissions
            columns:
              - column:
                  name: perm_value
            indexName: idx_permissions_perm_value

  - changeSet:
      id: v50.2024-01-04T13:52:51
      author: noahmoss
      comment: Data permissions table
      changes:
        - createTable:
            tableName: data_permissions
            remarks: A table to store database and table permissions
            columns:
              - column:
                  remarks: The ID of the permission
                  name: id
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  remarks: The ID of the associated permission group
                  name: group_id
                  type: int
                  constraints:
                    nullable: false
                    referencedTableName: permissions_group
                    referencedColumnNames: id
                    foreignKeyName: fk_data_permissions_ref_permissions_group
                    deleteCascade: true
              - column:
                  remarks: The type of the permission (e.g. "data", "collection", "download"...)
                  name: perm_type
                  type: varchar(64)
                  constraints:
                    nullable: false
              - column:
                  remarks: A database ID, for DB and table-level permissions
                  name: db_id
                  type: int
                  constraints:
                    nullable: false
                    referencedTableName: metabase_database
                    referencedColumnNames: id
                    foreignKeyName: fk_data_permissions_ref_db_id
                    deleteCascade: true
              - column:
                  remarks: A schema name, for table-level permissions
                  name: schema_name
                  type: varchar(254)
                  constraints:
                    nullable: true
              - column:
                  remarks: A table ID
                  name: table_id
                  type: int
                  constraints:
                    nullable: true
                    referencedTableName: metabase_table
                    referencedColumnNames: id
                    foreignKeyName: fk_data_permissions_ref_table_id
                    deleteCascade: true
              - column:
                  remarks: The value this permission is set to.
                  name: perm_value
                  type: varchar(64)
                  constraints:
                    nullable: false

  - changeSet:
      id: v50.2024-01-09T13:52:21
      author: noahmoss
      comment: Index on data_permissions.table_id
      rollback: # not necessary, will be removed with the table
      changes:
        - createIndex:
            tableName: data_permissions
            columns:
              - column:
                  name: table_id
            indexName: idx_data_permissions_table_id

  - changeSet:
      id: v50.2024-01-09T13:53:50
      author: noahmoss
      comment: Index on data_permissions.db_id
      rollback: # not necessary, will be removed with the table
      changes:
        - createIndex:
            tableName: data_permissions
            columns:
              - column:
                  name: db_id
            indexName: idx_data_permissions_db_id

  - changeSet:
      id: v50.2024-01-09T13:53:54
      author: noahmoss
      comment: Index on data_permissions.group_id
      rollback: # not necessary, will be removed with the table
      changes:
        - createIndex:
            tableName: data_permissions
            columns:
              - column:
                  name: group_id
            indexName: idx_data_permissions_group_id

  - changeSet:
      id: v50.2024-01-10T03:27:20
      author: noahmoss
      comment: Analyze permissions table in preparation for subsequent migrations
      validCheckSum: ANY
      runInTransaction: false
      changes:
        - sql:
            sql: ANALYZE permissions;
            dbms: postgresql
        - sql:
            sql: ANALYZE TABLE permissions;
            dbms: mysql,mariadb
      rollback: # not needed

  - changeSet:
      id: v50.2024-01-10T03:27:29
      author: noahmoss
      comment: Drop foreign key constraint on sandboxes.permissions_id
      changes:
        - dropForeignKeyConstraint:
            baseTableName: sandboxes
            constraintName: fk_sandboxes_ref_permissions
      rollback:
        - addForeignKeyConstraint:
            baseTableName: sandboxes
            baseColumnNames: permission_id
            referencedTableName: permissions
            referencedColumnNames: id
            constraintName: fk_sandboxes_ref_permissions
            onDelete: CASCADE

  - changeSet:
      id: v50.2024-01-10T03:27:30
      author: noahmoss
      comment: Migrate data-access permissions from `permissions` to `data_permissions`
      validCheckSum: ANY
      runInTransaction: false
      changes:
        - sqlFile:
            dbms: postgresql
            path: permissions/data_access.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: permissions/h2_data_access.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: permissions/mysql_data_access.sql
            relativeToChangelogFile: true
      rollback:
        - sqlFile:
            dbms: postgresql,h2
            path: permissions/rollback/data_access.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: permissions/rollback/mysql_data_access.sql
            relativeToChangelogFile: true

  - changeSet:
      id: v50.2024-01-10T03:27:31
      author: noahmoss
      comment: Migrate native-query-editing permissions from `permissions` to `data_permissions`
      changes:
        - sqlFile:
            path: permissions/native_query_editing.sql
            relativeToChangelogFile: true
      rollback:
        - sqlFile:
            path: permissions/rollback/native_query_editing.sql
            relativeToChangelogFile: true

  - changeSet:
      id: v50.2024-01-10T03:27:32
      author: noahmoss
      comment: Migrate download-results permissions from `permissions` to `data_permissions`
      validCheckSum: ANY
      runInTransaction: false
      changes:
        - sqlFile:
            dbms: postgresql
            path: permissions/download_results.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: permissions/h2_download_results.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: permissions/mysql_download_results.sql
            relativeToChangelogFile: true
      rollback:
        - sqlFile:
            dbms: postgresql,h2
            path: permissions/rollback/download_results.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: permissions/rollback/mysql_download_results.sql
            relativeToChangelogFile: true

  - changeSet:
      id: v50.2024-01-10T03:27:33
      author: noahmoss
      comment: Migrate manage-data-metadata permissions from `permissions` to `data_permissions`
      validCheckSum: ANY
      runInTransaction: false
      changes:
        - sqlFile:
            dbms: postgresql
            path: permissions/manage_table_metadata.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: permissions/h2_manage_table_metadata.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: permissions/mysql_manage_table_metadata.sql
            relativeToChangelogFile: true
      rollback:
        - sqlFile:
            dbms: postgresql,h2
            path: permissions/rollback/manage_table_metadata.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: permissions/rollback/mysql_manage_table_metadata.sql
            relativeToChangelogFile: true

  - changeSet:
      id: v50.2024-01-10T03:27:34
      author: noahmoss
      comment: Migrate manage-database permissions from `permissions` to `data_permissions`
      changes:
        - sqlFile:
            path: permissions/manage_database.sql
            relativeToChangelogFile: true
      rollback:
        - sqlFile:
            path: permissions/rollback/manage_database.sql
            relativeToChangelogFile: true

  - changeSet:
      id: v50.2024-02-19T21:32:04
      author: noahmoss
      comment: Clear data permission paths
      changes:
        - sql: >-
            DELETE FROM permissions WHERE object LIKE '%/db/%';
      rollback: # not needed; handled by the permission migrations above

  - changeSet:
      id: v50.2024-02-20T19:21:04
      author: camsaul
      comment: Drop v1 version of v_content view since it references report_card.dataset which we are dropping in next migration
      changes:
        - sql:
            sql: >
              DROP VIEW IF EXISTS v_content;
      rollback:
        - sqlFile:
            dbms: postgresql
            path: instance_analytics_views/content/v1/postgres-content.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: instance_analytics_views/content/v1/mysql-content.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: instance_analytics_views/content/v1/h2-content.sql
            relativeToChangelogFile: true

  - changeSet:
      id: v50.2024-02-20T19:25:40
      author: camsaul
      comment: Remove report_card.dataset (indicated whether Card was a Model; migrated to report_card.type in 49)
      changes:
        - dropColumn:
            tableName: report_card
            columnName: dataset
      rollback:
        - addColumn:
            tableName: report_card
            columns:
              - column:
                  name: dataset
                  type: boolean
                  remarks: "Indicate whether question is a model"
                  constraints:
                    nullable: false
                  defaultValue: false
        - sql:
            sql: >-
              UPDATE report_card
              SET dataset = true
              WHERE type = 'model';

  - changeSet:
      id: v50.2024-02-20T19:26:38
      author: camsaul
      comment: Add new v2 version of v_content view which uses report_card.type instead of report_card.dataset (removed in previous migration)
      changes:
        - sqlFile:
            dbms: postgresql
            path: instance_analytics_views/content/v2/postgres-content.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: instance_analytics_views/content/v2/mysql-content.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: instance_analytics_views/content/v2/h2-content.sql
            relativeToChangelogFile: true
      rollback:
        - sql:
            sql: >-
              DROP VIEW IF EXISTS v_content;

  - changeSet:
      id: v50.2024-02-26T22:15:52
      author: noahmoss
      comment: Add index on data_permissions(group_id, db_id, perm_value)
      changes:
        - createIndex:
            tableName: data_permissions
            indexName: idx_data_permissions_group_id_db_id_perm_value
            columns:
              - column:
                  name: group_id
              - column:
                  name: db_id
              - column:
                  name: perm_value
      rollback: # not needed

  - changeSet:
      id: v50.2024-02-26T22:15:53
      author: noahmoss
      comment: Add index on data_permissions(group_id, db_id, table_id, perm_value)
      changes:
        - createIndex:
            tableName: data_permissions
            indexName: idx_data_permissions_group_id_db_id_table_id_perm_value
            columns:
              - column:
                  name: group_id
              - column:
                  name: db_id
              - column:
                  name: table_id
              - column:
                  name: perm_value
      rollback: # not needed

  - changeSet:
      id: v50.2024-02-26T22:15:54
      author: noahmoss
      comment: New `view-data` permission
      validCheckSum: ANY
      changes:
        - sqlFile:
            dbms: postgresql,h2
            path: permissions/view_data.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: permissions/mysql_view_data.sql
            relativeToChangelogFile: true
      rollback:
        - sqlFile:
            path: permissions/rollback/view_data.sql
            relativeToChangelogFile: true

  - changeSet:
      id: v50.2024-02-26T22:15:55
      author: noahmoss
      comment: New `create_queries` permission
      validCheckSum: 9:7c2bc517b6def4e3278394b0399c3d4b
      changes:
        - sqlFile:
            path: permissions/create_queries.sql
            relativeToChangelogFile: true
      rollback:
        - sqlFile:
            path: permissions/rollback/create_queries.sql
            relativeToChangelogFile: true

  - changeSet:
      id: v50.2024-02-29T15:06:43
      author: tsmacdonald
      comment: Add the query_field join table
      changes:
        - createTable:
            tableName: query_field
            remarks: Fields used by a card's query
            columns:
              - column:
                  name: id
                  remarks: PK
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: card_id
                  remarks: referenced card
                  type: int
                  constraints:
                    nullable: false
                    referencedTableName: report_card
                    referencedColumnNames: id
                    foreignKeyName: fk_query_field_card_id
                    deleteCascade: true
              - column:
                  name: field_id
                  remarks: referenced field
                  type: int
                  constraints:
                    nullable: false
                    referencedTableName: metabase_field
                    referencedColumnNames: id
                    foreignKeyName: fk_query_field_field_id
                    deleteCascade: true

  - changeSet:
      id: v50.2024-02-29T15:07:43
      author: tsmacdonald
      comment: Index query_field.card_id
      rollback: # not necessary, will be removed with the table
      changes:
        - createIndex:
            tableName: query_field
            columns:
              - column:
                  name: card_id
            indexName: idx_query_field_card_id

  - changeSet:
      id: v50.2024-02-29T15:08:43
      author: tsmacdonald
      comment: Index query_field.field_id
      rollback: # not necessary, will be removed with the table
      changes:
        - createIndex:
            tableName: query_field
            columns:
              - column:
                  name: field_id
            indexName: idx_query_field_field_id

  - changeSet:
      id: v50.2024-03-12T17:16:38
      author: noahmoss
      comment: Drops the `activity` table which is now unused
      changes:
        - dropTable:
            tableName: activity
      rollback:
        - createTable:
            tableName: activity
            columns:
              - column:
                  name: id
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: topic
                  type: varchar(32)
                  constraints:
                    nullable: false
              - column:
                  name: timestamp
                  type: DATETIME
                  constraints:
                    nullable: false
              - column:
                  name: user_id
                  type: int
                  constraints:
                    nullable: true
                    referencedTableName: core_user
                    referencedColumnNames: id
                    foreignKeyName: fk_activity_ref_user_id
                    deferrable: false
                    initiallyDeferred: false
              - column:
                  name: model
                  type: varchar(16)
                  constraints:
                    nullable: true
              - column:
                  name: model_id
                  type: int
                  constraints:
                    nullable: true
              - column:
                  name: database_id
                  type: int
                  constraints:
                    nullable: true
              - column:
                  name: table_id
                  type: int
                  constraints:
                    nullable: true
              - column:
                  name: custom_id
                  type: varchar(48)
                  constraints:
                    nullable: true
              - column:
                  name: details
                  type: ${text.type}
                  constraints:
                    nullable: false
        - sql:
            dbms: mysql
            sql: >
              CREATE index idx_activity_entity_qualified_id ON activity (
                (
                  CASE
                    WHEN model = 'Dataset' THEN (concat('card_', model_id))
                    WHEN model_id IS NULL THEN NULL
                    ELSE (concat(lower(model), '_', model_id))
                  END
                )
              );

  - changeSet:
      id: v50.2024-03-18T16:00:00
      author: piranha
      comment: 'Effective caching #36847'
      changes:
        - createTable:
            tableName: cache_config
            remarks: Cache Configuration
            columns:
              - column:
                  name: id
                  remarks: Unique ID
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: model
                  remarks: Name of an entity model
                  type: varchar(32)
                  constraints:
                    nullable: false
              - column:
                  name: model_id
                  remarks: ID of the said entity
                  type: int
                  constraints:
                    nullable: false
              - column:
                  name: created_at
                  remarks: Timestamp when the config was inserted
                  type: ${timestamp_type}
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false
              - column:
                  name: updated_at
                  remarks: Timestamp when the config was updated
                  type: ${timestamp_type}
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false
              - column:
                  name: strategy
                  remarks: caching strategy name
                  type: ${text.type}
                  constraints:
                    nullable: false
              - column:
                  name: config
                  remarks: caching strategy configuration
                  type: ${text.type}
                  constraints:
                    nullable: false
              - column:
                  name: state
                  remarks: state for strategies needing to keep some data between runs
                  type: ${text.type}
                  constraints:
                    nullable: true
              - column:
                  name: invalidated_at
                  remarks: indicates when a cache was invalidated last time for schedule-based strategies
                  type: ${timestamp_type}
                  constraints:
                    nullable: true
              - column:
                  name: next_run_at
                  remarks: keeps next time to run for schedule-based strategies
                  type: ${timestamp_type}
                  constraints:
                    nullable: true

  - changeSet:
      id: v50.2024-03-18T16:00:01
      author: piranha
      comment: 'Effective caching #36847'
      rollback: # will be removed with the table
      changes:
        - addUniqueConstraint:
            remarks: Unique config for cache_config (model, model_id)
            tableName: cache_config
            constraintName: idx_cache_config_unique_model
            columnNames: model, model_id

  - changeSet:
      id: v50.2024-03-21T17:41:00
      author: qnkhuat
      comment: Add metabase_table.estimated_row_count
      changes:
        - addColumn:
            tableName: metabase_table
            columns:
              - column:
                  name: estimated_row_count
                  type: bigint
                  remarks: The estimated row count

  - changeSet:
      id: v50.2024-03-22T00:38:28
      author: qnkhuat
      comment: Add field_usage table
      changes:
        - createTable:
            tableName: field_usage
            remarks: Used to store field usage during query execution
            columns:
              - column:
                  name: id
                  remarks: Unique ID
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: field_id
                  remarks: ID of the field
                  type: int
                  constraints:
                    nullable: false
                    referencedTableName: metabase_field
                    referencedColumnNames: id
                    foreignKeyName: fk_field_usage_field_id_metabase_field_id
                    deleteCascade: true
              - column:
                  name: query_execution_id
                  remarks: referenced query execution
                  type: int
                  constraints:
                    nullable: false
                    referencedTableName: query_execution
                    referencedColumnNames: id
                    foreignKeyName: fk_field_usage_query_execution_id
                    deleteCascade: true
              - column:
                  name: used_in
                  remarks: which part of the query the field was used in
                  type: varchar(25)
                  constraints:
                    nullable: false
              - column:
                  name: filter_op
                  remarks: filter's operator that applied to the field
                  type: varchar(25)
                  constraints:
                    nullable: true
              - column:
                  name: aggregation_function
                  remarks: the aggregation function that field applied to
                  type: varchar(25)
                  constraints:
                    nullable: true
              - column:
                  name: breakout_temporal_unit
                  remarks: temporal unit options of the breakout
                  type: varchar(25)
                  constraints:
                    nullable: true
              - column:
                  name: breakout_binning_strategy
                  remarks: the strategy of breakout
                  type: varchar(25)
                  constraints:
                    nullable: true
              - column:
                  name: breakout_binning_num_bins
                  remarks: The numbin option of breakout
                  type: int
                  constraints:
                    nullable: true
              - column:
                  name: breakout_binning_bin_width
                  remarks: The numbin option of breakout
                  type: int
                  constraints:
                    nullable: true
              - column:
                  name: created_at
                  type: ${timestamp_type}
                  remarks: The time a field usage was recorded
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false

  - changeSet:
      id: v50.2024-03-22T00:39:28
      author: qnkhuat
      comment: Index field_usage.field_id
      rollback: # not necessary, will be removed with the table
      changes:
        - createIndex:
            tableName: field_usage
            indexName: idx_field_usage_field_id
            columns:
              column:
                name: field_id

  - changeSet:
      id: v50.2024-03-24T19:34:11
      author: noahmoss
      comment: Clean up deprecated view-data and native-query-editing permissions
      rollback: # handled by the rollbacks for `v50.2024-02-26T22:15:54` and `v50.2024-02-26T22:15:55`
      changes:
        - sql:
            sql: >
              DELETE FROM data_permissions where perm_type = 'perms/data-access' OR perm_type = 'perms/native-query-editing';

  - changeSet:
      id: v50.2024-03-25T14:53:00
      author: tsmacdonald
      comment: Add query_field.direct_reference
      changes:
        - addColumn:
            tableName: query_field
            columns:
              - column:
                  name: direct_reference
                  type: ${boolean.type}
                  remarks: "Is the Field referenced directly or via a wildcard"
                  constraints:
                    nullable: false
                  defaultValue: true

  - changeSet:
      id: v50.2024-03-28T16:30:35
      author: calherries
      comment: Create internal user
      validCheckSum: ANY
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.CreateInternalUser"

  - changeSet:
      id: v50.2024-03-29T10:00:00
      author: piranha
      comment: 'Granular cache invalidation'
      changes:
        - addColumn:
            tableName: report_card
            columns:
              - column:
                  name: cache_invalidated_at
                  type: ${timestamp_type}
                  remarks: 'An invalidation time that can supersede cache_config.invalidated_at'
                  constraints:
                    nullable: true

  - changeSet:
      id: v50.2024-04-09T15:55:19
      author: calherries
      comment: Add collection.is_sample column
      changes:
        - addColumn:
            tableName: collection
            columns:
              - column:
                  name: is_sample
                  type: ${boolean.type}
                  remarks: "Is the collection part of the sample content?"
                  constraints:
                    nullable: false
                  defaultValue: false

  - changeSet:
      id: v50.2024-04-15T16:30:35
      author: qnkhuat
      comment: Add report_card.last_used_at
      changes:
        - addColumn:
            tableName: report_card
            columns:
              - column:
                  name: last_used_at
                  type: ${timestamp_type}
                  remarks: The timestamp of when the card is last used
                  constraints:
                    nullable: true

  - changeSet:
      id: v50.2024-04-19T17:04:04
      author: noahmoss
      comment: Clean up deprecated view-data and native-query-editing permissions (again)
      rollback: # handled by the rollbacks for `v50.2024-02-26T22:15:54` and `v50.2024-02-26T22:15:55`
      changes:
        - sql:
            sql: >
              DELETE FROM data_permissions where perm_type = 'perms/data-access' OR perm_type = 'perms/native-query-editing';

  - changeSet:
      id: v50.2024-04-25T01:04:05
      author: qnkhuat
      comment: Delete the old SendPulses job and trigger
      validCheckSum: ANY
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.DeleteSendPulsesTask"

  - changeSet:
      id: v50.2024-04-25T01:04:06
      author: qnkhuat
      comment: Delete SendPulse Job on downgrade
      validCheckSum: ANY
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.DeleteSendPulseTaskOnDowngrade"

  - changeSet:
      id: v50.2024-04-25T01:04:07
      author: qnkhuat
      comment: Delete InitSendPulseTriggers Job on downgrade
      validCheckSum: ANY
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.DeleteInitSendPulseTriggersOnDowngrade"

  - changeSet:
      id: v50.2024-04-25T03:15:01
      author: noahmoss
      comment: Add entity_id to core_user
      changes:
        - addColumn:
            columns:
              - column:
                  remarks: NanoID tag for each user
                  name: entity_id
                  type: char(21)
                  constraints:
                    nullable: true
                    unique: true
            tableName: core_user

  - changeSet:
      id: v50.2024-04-25T03:15:02
      author: noahmoss
      comment: Add entity_id to permissions_group
      changes:
        - addColumn:
            columns:
              - column:
                  remarks: NanoID tag for each user
                  name: entity_id
                  type: char(21)
                  constraints:
                    nullable: true
                    unique: true
            tableName: permissions_group

  - changeSet:
      id: v50.2024-04-25T16:29:31
      author: calherries
      comment: Add report_card.view_count
      changes:
        - addColumn:
            columns:
              - column:
                  name: view_count
                  type: integer
                  defaultValueNumeric: 0
                  remarks: Keeps a running count of card views
                  constraints:
                    nullable: false
            tableName: report_card

  - changeSet:
      id: v50.2024-04-25T16:29:32
      author: calherries
      comment: Populate report_card.view_count
      changes:
        - sql:
            dbms: mysql,mariadb
            sql: >-
              UPDATE report_card c
              SET c.view_count = (
                  SELECT COUNT(*)
                  FROM view_log v
                  WHERE v.model = 'card'
                  AND v.model_id = c.id
              );
        - sql:
            dbms: postgresql,h2
            sql: >-
              UPDATE report_card c
              SET view_count = (
                  SELECT count(*)
                  FROM view_log v
                  WHERE v.model = 'card'
                  AND v.model_id = c.id
              );
      rollback: # nothing to do, since view_count didn't exist in v49

  - changeSet:
      id: v50.2024-04-25T16:29:33
      author: calherries
      comment: Add report_dashboard.view_count
      changes:
        - addColumn:
            columns:
              - column:
                  name: view_count
                  type: integer
                  defaultValueNumeric: 0
                  remarks: Keeps a running count of dashboard views
                  constraints:
                    nullable: false
            tableName: report_dashboard

  - changeSet:
      id: v50.2024-04-25T16:29:34
      author: calherries
      comment: Populate report_dashboard.view_count
      changes:
        - sql:
            dbms: mysql,mariadb
            sql: >-
              UPDATE report_dashboard c
              SET c.view_count = (
                  SELECT COUNT(*)
                  FROM view_log v
                  WHERE v.model = 'dashboard'
                  AND v.model_id = c.id
              );
        - sql:
            dbms: postgresql,h2
            sql: >-
              UPDATE report_dashboard c
              SET view_count = (
                  SELECT count(*)
                  FROM view_log v
                  WHERE v.model = 'dashboard'
                  AND v.model_id = c.id
              );
      rollback: # nothing to do, since view_count didn't exist in v49

  - changeSet:
      id: v50.2024-04-25T16:29:35
      author: calherries
      comment: Add metabase_table.view_count
      changes:
        - addColumn:
            columns:
              - column:
                  name: view_count
                  type: integer
                  defaultValueNumeric: 0
                  remarks: Keeps a running count of card views
                  constraints:
                    nullable: false
            tableName: metabase_table

  - changeSet:
      id: v50.2024-04-25T16:29:36
      author: calherries
      comment: Populate metabase_table.view_count
      changes:
        - sql:
            dbms: mysql,mariadb
            sql: >-
              UPDATE metabase_table t
              SET t.view_count = (
                  SELECT count(*)
                  FROM view_log v
                  WHERE v.model = 'table'
                  AND v.model_id = t.id
              );
        - sql:
            dbms: postgresql,h2
            sql: >-
              UPDATE metabase_table t
              SET view_count = (
                  SELECT count(*)
                  FROM view_log v
                  WHERE v.model = 'table'
                  AND v.model_id = t.id
              );
      rollback: # nothing to do, since view_count didn't exist in v49

  - changeSet:
      id: v50.2024-04-26T09:19:00
      author: adam-james
      comment: Added 0.50.0 - Per-user Dashboard Parameter values table
      changes:
        - createTable:
            tableName: user_parameter_value
            remarks: Table holding last set value of a parameter per user
            columns:
              - column:
                  name: id
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: user_id
                  type: int
                  remarks: 'ID of the User who has set the parameter value'
                  constraints:
                    nullable: false
                    references: core_user(id)
                    foreignKeyName: fk_user_parameter_value_user_id
                    deleteCascade: true
              - column:
                  name: parameter_id
                  type: varchar(36)
                  remarks: "The parameter ID"
                  constraints:
                    nullable: false
              - column:
                  name: value
                  type: ${text.type}
                  remarks: Value of the parameter
                  constraints:
                    nullable: true

  - changeSet:
      id: v50.2024-04-26T09:25:00
      author: adam-james
      comment: Index user_parameter_value.user_id
      rollback: # not necessary, will be removed with the table
      changes:
        - createIndex:
            tableName: user_parameter_value
            indexName: idx_user_parameter_value_user_id
            columns:
              column:
                name: user_id

  - changeSet:
      id: v50.2024-04-30T23:57:23
      author: noahmoss
      comment: Add `scope` column to api_key to support SCIM authentication
      changes:
        - addColumn:
            columns:
              - column:
                  name: scope
                  type: varchar(64)
                  remarks: The scope of the API key, if applicable
                  constraints:
                    nullable: true
            tableName: api_key

  - changeSet:
      id: v50.2024-04-30T23:58:24
      author: noahmoss
      comment: Drop NOT NULL constraint on api_key.user_id to support SCIM-scoped API keys
      changes:
        - dropNotNullConstraint:
            tableName: api_key
            columnName: user_id
            columnDataType: integer
      rollback: # we can't reliably add back the constraint while downgrading

  - changeSet:
      id: v50.2024-05-08T09:00:00
      author: qnkhuat
      comment: Add task_history.status
      changes:
        - addColumn:
            tableName: task_history
            columns:
              - column:
                  name: status
                  type: varchar(21)
                  remarks: "the status of task history, could be started, failed, success, unknown"
                  constraints:
                    nullable: false
                  defaultValue: "unknown"

  - changeSet:
      id: v50.2024-05-08T09:00:01
      author: qnkhuat
      comment: Drop default value task_history.status
      changes:
        - dropDefaultValue:
            tableName: task_history
            columnName: status
      # the column will be dropped
      rollback:

  - changeSet:
      id: v50.2024-05-08T09:00:02
      author: qnkhuat
      comment: Add "started" as default value for task_history.status, now that backfill is done.
      changes:
        - addDefaultValue:
            defaultValue: "started"
            tableName: task_history
            columnName: status
      # the column will be dropped
      rollback:

  - changeSet:
      id: v50.2024-05-08T09:00:03
      author: qnkhuat
      comment: Drop not null constraint for task_history.ended_at
      changes:
        - dropNotNullConstraint:
            tableName: task_history
            columnDataType: ${timestamp_type}
            columnName: ended_at
      rollback: # we can't reliably add back the constraint while downgrading

  - changeSet:
      id: v50.2024-05-08T09:00:04
      author: qnkhuat
      comment: Drop not null constraint for task_history.duration
      changes:
        - dropNotNullConstraint:
            tableName: task_history
            columnDataType: int
            columnName: duration
      rollback: # we can't reliably add back the constraint while downgrading

  - changeSet:
      id: v50.2024-05-08T09:00:05
      author: qnkhuat
      comment: Drop default value task_history.ended_at
      changes:
        - dropDefaultValue:
            tableName: task_history
            columnName: ended_at
      rollback:
        - addDefaultValue:
            tableName: task_history
            columnName: ended_at
            defaultValueComputed: current_timestamp

  - changeSet:
      id: v50.2024-05-08T09:00:06
      author: qnkhuat
      comment: Add null as default value for task_history.ended_at
      changes:
        - addDefaultValue:
            defaultValue: "null"
            tableName: task_history
            columnName: ended_at
      # the migration above will add one
      rollback:

  - changeSet:
      id: v50.2024-05-13T16:00:00
      author: filipesilva
      comment: Create cloud migration
      changes:
        - createTable:
            tableName: cloud_migration
            remarks: Migrate to cloud directly from Metabase
            columns:
              - column:
                  name: id
                  remarks: Unique ID
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: external_id
                  remarks: Matching ID in Cloud for this migration
                  type: ${text.type}
                  constraints:
                    nullable: false
              - column:
                  name: upload_url
                  remarks: URL where the backup will be uploaded to
                  type: ${text.type}
                  constraints:
                    nullable: false
              - column:
                  name: state
                  remarks: 'Current state of the migration: init, setup, dump, upload, done, error, cancelled'
                  type: varchar(32)
                  defaultValue: init
                  constraints:
                    nullable: false
              - column:
                  name: progress
                  remarks: Number between 0 to 100 representing progress as a percentage
                  type: int
                  defaultValue: 0
                  constraints:
                    nullable: false
              - column:
                  name: created_at
                  remarks: Timestamp when the config was inserted
                  type: ${timestamp_type}
                  constraints:
                    nullable: false
              - column:
                  name: updated_at
                  remarks: Timestamp when the config was updated
                  type: ${timestamp_type}
                  constraints:
                    nullable: false

  - changeSet:
      id: v50.2024-05-14T12:42:42
      author: johnswanson
      comment: Create the Trash collection
      changes:
        - sql:
            sql: >-
              INSERT INTO collection (name, slug, entity_id, type) VALUES ('Trash', 'trash', 'trashtrashtrashtrasht', 'trash');
              INSERT INTO permissions (object, group_id)
              SELECT CONCAT('/collection/', c.id, '/'), pg.id
              FROM collection c
              CROSS JOIN permissions_group pg
              WHERE c.type = 'trash' AND pg.name != 'Administrators';

      rollback:
        - sql:
            sql: >-
              DELETE
              FROM permissions
              WHERE permissions.object IN (
                SELECT CONCAT('/collection/', collection.id, '/') FROM collection WHERE collection.type = 'trash'
              );
              DELETE FROM collection WHERE type = 'trash';

  - changeSet:
      id: v50.2024-05-15T13:13:13
      author: adam-james
      comment: Fix visualization settings for stacked area/bar/combo displays
      validCheckSum: ANY
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.MigrateStackedAreaBarComboDisplaySettings"

  - changeSet:
      id: v50.2024-05-17T19:54:23
      author: calherries
      comment: Add metabase_database.uploads_enabled column
      changes:
        - addColumn:
            tableName: metabase_database
            columns:
              - column:
                  name: uploads_enabled
                  type: ${boolean.type}
                  defaultValueBoolean: false
                  remarks: Whether uploads are enabled for this database
                  constraints:
                    nullable: false

  - changeSet:
      id: v50.2024-05-17T19:54:24
      author: calherries
      comment: Add metabase_database.uploads_schema_name column
      changes:
        - addColumn:
            tableName: metabase_database
            columns:
              - column:
                  name: uploads_schema_name
                  type: ${text.type}
                  remarks: The schema name for uploads

  - changeSet:
      id: v50.2024-05-17T19:54:25
      author: calherries
      comment: Add metabase_database.uploads_table_prefix column
      changes:
        - addColumn:
            tableName: metabase_database
            columns:
              - column:
                  name: uploads_table_prefix
                  type: ${text.type}
                  remarks: The prefix for upload table names

  - changeSet:
      id: v50.2024-05-17T19:54:26
      author: calherries
      comment: Update metabase_database.uploads_enabled value
      validCheckSum: ANY
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.MigrateUploadsSettings"

  # This migration has been moved.
  - changeSet:
      id: v50.2024-05-27T15:55:22
      author: calherries
      comment: Create sample content
      validCheckSum: ANY
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.CreateSampleContent"

  - changeSet:
      id: v50.2024-05-29T14:04:47
      author: johnswanson
      comment: Add `report_dashboard.archived_directly`
      changes:
        - addColumn:
            tableName: report_dashboard
            columns:
              - column:
                  name: archived_directly
                  type: ${boolean.type}
                  defaultValueBoolean: false
                  remarks: "Was this thing trashed directly"
                  constraints:
                    nullable: false

  - changeSet:
      id: v50.2024-05-29T14:04:53
      author: johnswanson
      comment: Add `report_card.archived_directly`
      changes:
        - addColumn:
            tableName: report_card
            columns:
              - column:
                  name: archived_directly
                  type: ${boolean.type}
                  remarks: "Was this thing trashed directly"
                  defaultValueBoolean: false
                  constraints:
                    nullable: false

  - changeSet:
      id: v50.2024-05-29T14:04:58
      author: johnswanson
      comment: Add `collection.archive_operation_id`
      changes:
        - addColumn:
            tableName: collection
            columns:
              - column:
                  name: archive_operation_id
                  type: char(36)
                  remarks: "The UUID of the trash operation. Each time you trash a collection subtree, you get a unique ID."
                  constraints:
                    nullable: true

  - changeSet:
      id: v50.2024-05-29T14:05:01
      author: johnswanson
      comment: Add `collection.archived_directly`
      changes:
        - addColumn:
            tableName: collection
            columns:
              - column:
                  name: archived_directly
                  type: ${boolean.type}
                  remarks: "Whether the item was trashed independently or as a subcollection"
                  constraints:
                    nullable: true

  - changeSet:
      id: v50.2024-05-29T14:05:03
      author: johnswanson
      dbms: postgresql
      comment: Populate `archived_directly` and `archive_operation_id` (Postgres)
      changes:
        - sqlFile:
            path: trash/postgres.sql
            relativeToChangelogFile: true
      rollback: # not needed, columns will be deleted

  - changeSet:
      id: v50.2024-05-29T18:42:13
      author: johnswanson
      dbms: h2
      comment: Populate `archived_directly` and `archive_operation_id` (H2)
      changes:
        - sqlFile:
            path: trash/h2.sql
            relativeToChangelogFile: true
      rollback: # not needed, columns will be deleted

  - changeSet:
      id: v50.2024-05-29T18:42:14
      author: johnswanson
      dbms: mysql
      comment: Populate `archived_directly` and `archive_operation_id` (MySQL)
      validCheckSum: ANY
      changes:
        - sqlFile:
            path: trash/mysql.sql
            relativeToChangelogFile: true
      rollback: # not needed, columns will be deleted

  - changeSet:
      id: v50.2024-05-29T18:42:15
      author: johnswanson
      dbms: mariadb
      comment: Populate `archived_directly` and `archive_operation_id` (MariaDB)
      changes:
        - sqlFile:
            path: trash/mariadb.sql
            relativeToChangelogFile: true
      rollback: # not needed, columns will be deleted

  - changeSet:
      id: v50.2024-05-30T16:04:20
      author: escherize
      comment: Add context to recent views table
      changes:
        - addColumn:
            tableName: recent_views
            columns:
              - column:
                  name: context
                  remarks: The contextual action that netted a recent view.
                  type: varchar(256)
                  defaultValue: "view"
                  constraints:
                    nullable: false

  - changeSet:
      id: v50.2024-06-12T12:33:07
      author: piranha
      comment: 'Decrypt some settings so the next migration runs well'
      validCheckSum: ANY
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.DecryptCacheSettings"
      rollback: # no rollback necessary, they'll be encrypted if you downgrade and touch them

  - changeSet:
      # this had id `v50.2024-04-12T12:33:09` before #44048
      id: v50.2024-06-12T12:33:08
      author: piranha
      comment: 'Copy old cache configurations to cache_config table'
      validCheckSum: ANY
      changes:
        - sqlFile:
            dbms: postgresql
            path: custom_sql/fill_cache_config.pg.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: custom_sql/fill_cache_config.my.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: custom_sql/fill_cache_config.h2.sql
            relativeToChangelogFile: true
      rollback: # no rollback necessary, we're not removing the columns yet

  - changeSet:
      id: v50.2024-06-12T12:33:09
      author: piranha
      comment: 'Fix root cache config for mysql if it is wrong'
      dbms: mysql,mariadb
      validCheckSum: ANY
      changes:
        - sqlFile:
            path: custom_sql/fill_cache_config_root_fix.my.sql
            relativeToChangelogFile: true
      rollback: # no rollback necessary here too

  - changeSet:
      id: v50.2024-06-20T13:21:30
      author: noahmoss
      comment: 'Drop permission_id column on sandboxes table to fix down migrations'
      changes:
        - dropColumn:
            tableName: sandboxes
            columnName: permission_id
      rollback:
        - addColumn:
            tableName: sandboxes
            columns:
              - column:
                  name: permission_id
                  type: int
                  remarks: 'The ID of the corresponding permissions path for this sandbox (deprecated)'
                  constraints:
                    nullable: true
                  defaultValue: null

  - changeSet:
      id: v50.2024-06-28T12:35:50
      author: piranha
      comment: 'Clean databasechangelog table of migration that was once deleted'
      changes:
        - sql: "DELETE FROM ${databasechangelog.name} WHERE id = 'v50.2024-04-12T12:33:09'"
      rollback: # nothing to do here

  - changeSet:
      id: v50.2024-07-02T16:48:21
      author: adam-james
      comment: Remove existing user_parameter_value entries as we want to add dashboard_id, and can't easily backfill
      rollback: # none, entries already removed and are non-critical to app functionality
      changes:
        - delete:
           tableName: user_parameter_value

  - changeSet:
      id: v50.2024-07-02T16:49:29
      author: adam-james
      comment: Add dashboard_id column to user_parameter_value to keep values unique per dashboard
      changes:
        - addColumn:
            columns:
              - column:
                  name: dashboard_id
                  type: int
                  remarks: The ID of the dashboard
            tableName: user_parameter_value

  - changeSet:
      id: v50.2024-07-02T16:55:42
      author: adam-james
      comment: Add fk constraint to user_parameter_value.dashboard_id
      changes:
        - addForeignKeyConstraint:
            baseTableName: user_parameter_value
            baseColumnNames: dashboard_id
            referencedTableName: report_dashboard
            referencedColumnNames: id
            constraintName: fk_user_parameter_value_dashboard_id
            nullable: false
            deleteCascade: true

  - changeSet:
      id: v50.2024-07-02T17:07:15
      author: adam-james
      comment: Index user_parameter_value.dashboard_id
      rollback: # not necessary, will be removed with the table
      changes:
        - createIndex:
            tableName: user_parameter_value
            indexName: idx_user_parameter_value_dashboard_id
            columns:
              column:
                name: dashboard_id

  # After this migration, last_used_at becomes the lowest timestamp after which we know that
  # the card has not been used. last_used_at will be used to determine if a report
  # card is stale and should be cleaned up if the card is imported with serialization.
  # Because we weren't collecting last_used_at before, we have to populate all existing cards
  # with the current timestamp to provide a "lower bound" after which the card has not been used.
  - changeSet:
      id: v50.2024-07-09T20:04:00
      author: calherries
      comment: Populate default value for report_card.last_used_at
      changes:
        - sql:
            sql: UPDATE report_card SET last_used_at = current_timestamp
      rollback: # nothing to do, since this is backwards compatible

  - changeSet:
      id: v50.2024-07-09T20:04:02
      author: calherries
      comment: Add not null constraint for report_card.last_used_at
      changes:
        - addNotNullConstraint:
            tableName: report_card
            columnName: last_used_at
            columnDataType: ${timestamp_type}

  # addDefaultValue with defaultValueComputed doesn't work for MySQL/MariaDB so we have to do this the hard way.
  - changeSet:
      id: v50.2024-07-09T20:04:03
      author: calherries
      comment: Set default for report_card.last_used_at
      changes:
        - sql:
            dbms: postgresql,h2
            sql: ALTER TABLE report_card ALTER COLUMN last_used_at SET DEFAULT CURRENT_TIMESTAMP;
        - sql:
            dbms: mysql,mariadb
            sql: >-
              ALTER TABLE report_card
              CHANGE last_used_at
              last_used_at timestamp(6) NOT NULL DEFAULT current_timestamp(6);
      rollback: # nothing to do, since this is backwards compatible

  - changeSet:
      id: v50.2024-08-08T20:04:03
      author: qnkhuat
      comment: Added 0.50.0 - Add index on user_parameter_value(user_id, parameter_id, dashboard_id)
      changes:
        - createIndex:
            tableName: user_parameter_value
            indexName: idx_user_parameter_value_user_id_dashboard_id_parameter_id
            columns:
              - column:
                  name: user_id
              - column:
                  name: dashboard_id
              - column:
                  name: parameter_id

  - changeSet:
      id: v50.2024-08-27T00:00:00
      author: devurandom
      comment: Add is_attached_dwh to metabase_database
      changes:
        - addColumn:
            tableName: metabase_database
            columns:
              - column:
                  name: is_attached_dwh
                  type: ${boolean.type}
                  defaultValueBoolean: false
                  remarks: 'This is an attached data warehouse, do not serialize it and hide its details from the UI'
                  constraints:
                    nullable: false

  - changeSet:
      id: v51.2024-05-13T15:30:57
      author: metamben
      comment: Backup of dataset_query rewritten by the metrics v2 migration
      changes:
        - addColumn:
            tableName: report_card
            columns:
              - column:
                  name: dataset_query_metrics_v2_migration_backup
                  remarks: The copy of dataset_query before the metrics v2 migration
                  type: ${text.type}

  - changeSet:
      id: v51.2024-05-13T16:00:00
      author: metamben
      comment: Migrate v1 metrics to v2 metrics
      validCheckSum: ANY
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.MigrateMetricsToV2"

  - changeSet:
      id: v51.2024-06-07T12:37:36
      author: crisptrutski
      comment: Rename query_field.direct_reference to query_field.indirect_reference
      changes:
        - renameColumn:
            tableName: query_field
            columnDataType: ${boolean.type}
            oldColumnName: direct_reference
            newColumnName: explicit_reference

  - changeSet:
      id: v51.2024-06-12T18:53:02
      author: noahmoss
      comment: Drop incorrect index on login_history
      changes:
        - dropIndex:
            tableName: login_history
            indexName: idx_user_id_device_id
      rollback:
        - createIndex:
            tableName: login_history
            indexName: idx_user_id_device_id
            columns:
              - column:
                  name: session_id
              - column:
                  name: device_id

  - changeSet:
      id: v51.2024-06-12T18:53:03
      author: noahmoss
      comment: Create index on login_history (user_id, device_id)
      changes:
        - createIndex:
            tableName: login_history
            indexName: idx_user_id_device_id
            columns:
              - column:
                  name: user_id
              - column:
                  name: device_id
      rollback:
        - dropIndex:
            tableName: login_history
            indexName: idx_user_id_device_id

  - changeSet:
      id: v51.2024-07-08T10:00:00
      author: qnkhuat
      comment: Create channel table
      changes:
        - createTable:
            tableName: channel
            remarks: Channel configurations
            columns:
              - column:
                  name: id
                  remarks: Unique ID
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: name
                  remarks: channel name
                  type: varchar(254)
                  constraints:
                    nullable: false
                    unique: true
              - column:
                  name: description
                  remarks: channel description
                  type: ${text.type}
                  constraints:
                    nullable: true
              - column:
                  name: type
                  remarks: Channel type
                  type: varchar(32)
                  constraints:
                    nullable: false
              - column:
                  name: details
                  remarks: Channel details, used to store authentication information or channel-specific settings
                  type: ${text.type}
                  constraints:
                    nullable: false
              - column:
                  name: active
                  type: ${boolean.type}
                  defaultValueBoolean: true
                  remarks: whether the channel is active
                  constraints:
                    nullable: false
              - column:
                  name: created_at
                  remarks: Timestamp when the channel was inserted
                  type: ${timestamp_type}
                  constraints:
                    nullable: false
              - column:
                  name: updated_at
                  remarks: Timestamp when the channel was updated
                  type: ${timestamp_type}
                  constraints:
                    nullable: false

  - changeSet:
      id: v51.2024-07-08T10:00:01
      author: qnkhuat
      comment: Create pulse_channel.channel_id
      changes:
        - addColumn:
            tableName: pulse_channel
            columns:
              - column:
                  name: channel_id
                  type: integer
                  remarks: The channel ID

  - changeSet:
      id: v51.2024-07-08T10:00:02
      author: qnkhuat
      comment: Add fk constraint to pulse_channel.channel_id
      changes:
        - addForeignKeyConstraint:
            baseTableName: pulse_channel
            baseColumnNames: channel_id
            referencedTableName: channel
            referencedColumnNames: id
            constraintName: fk_pulse_channel_channel_id
            nullable: true
            deleteCascade: true

  - changeSet:
      id: v51.2024-07-09T17:15:43
      author: tsmacdonald
      comment: Fix default boolean value for query_field.explicit_reference
      dbms: mysql,mariadb
      changes:
        - addDefaultValue:
            tableName: query_field
            columnName: explicit_reference
            defaultValueBoolean: true

  - changeSet:
      id: v51.2024-07-10T12:28:10
      author: johnswanson
      comment: Add `last_viewed_at` to dashboards
      changes:
        - addColumn:
            tableName: report_dashboard
            columns:
              - column:
                  name: last_viewed_at
                  type: ${timestamp_type}
                  remarks: Timestamp of when this dashboard was last viewed
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false

  - changeSet:
      id: v51.2024-07-22T15:49:37
      author: escherize
      comment: Add embedding_client column to query_execution for metabase embedding SDK analytics
      changes:
        - addColumn:
            tableName: query_execution
            columns:
              - column:
                  name: embedding_client
                  remarks: Used by the embedding team to track SDK usage
                  type: varchar(254)
                  constraints:
                    nullable: true

  - changeSet:
      id: v51.2024-07-22T15:49:38
      author: escherize
      comment: Add embedding_version column to query_execution for metabase embedding SDK analytics
      changes:
        - addColumn:
            tableName: query_execution
            columns:
              - column:
                  name: embedding_version
                  remarks: Used by the embedding team to track SDK version usage
                  type: varchar(254)
                  constraints:
                    nullable: true

  - changeSet:
      id: v51.2024-07-22T15:49:39
      author: escherize
      comment: Add embedding_client column to view_log for metabase embedding SDK analytics
      changes:
        - addColumn:
            tableName: view_log
            columns:
              - column:
                  name: embedding_client
                  remarks: Used by the embedding team to track SDK usage
                  type: varchar(254)
                  constraints:
                    nullable: true

  - changeSet:
      id: v51.2024-07-22T15:49:40
      author: escherize
      comment: Add embedding_version column to view_log for metabase embedding SDK analytics
      changes:
        - addColumn:
            tableName: view_log
            columns:
              - column:
                  name: embedding_version
                  remarks: Used by the embedding team to track SDK version usage
                  type: varchar(254)
                  constraints:
                    nullable: true

  - changeSet:
      id: v51.2024-07-25T11:56:27
      author: crisptrutski
      comment: Wipe stale query fields, so we can add new non-nullable columns
      rollback: # none, entries will be recreated by sweeper
      changes:
        - delete:
            tableName: query_field
            remarks: remove stale analysis, so the new fields can be non-nullable

  - changeSet:
      id: v51.2024-07-25T11:57:27
      author: crisptrutski
      comment: Add `column` column to query fields
      changes:
        - addColumn:
            tableName: query_field
            columns:
              - column:
                  name: column
                  type: varchar(254) # matching metabase_field.name
                  remarks: name of the table or card being referenced
                  constraints:
                    nullable: false

  - changeSet:
      id: v51.2024-07-25T11:58:27
      author: crisptrutski
      comment: Add `table` column to query fields
      changes:
        - addColumn:
            tableName: query_field
            columns:
              - column:
                  name: table
                  type: varchar(254) # matching metabase_table.name
                  remarks: name of the table or card being referenced
                  constraints:
                    nullable: false

  - changeSet:
      id: v51.2024-07-25T12:02:21
      validCheckSum: ANY
      author: crisptrutski
      comment: Make `field_id` nullable on query fields
      rollback:
        - delete:
            tableName: query_field
            where: query_field.field_id is NULL
            remarks: remove stale analysis, so the fields can be non-nullable
      changes:
        - dropNotNullConstraint:
            tableName: query_field
            columnDataType: int
            columnName: field_id
            remarks: This value is null if the field does not exist, or is created within a model

  - changeSet:
      id: v51.2024-07-26T11:56:27
      author: crisptrutski
      comment: Add `table_id` column to query fields
      changes:
        - addColumn:
            tableName: query_field
            columns:
              - column:
                  name: table_id
                  type: int
                  remarks: track the table directly, in case the field does not exist
                  constraints:
                    nullable: true

  - changeSet:
      id: v51.2024-07-29T09:22:12
      author: crisptrutski
      comment: Add the query_analysis table
      changes:
        - createTable:
            tableName: query_analysis
            remarks: Parent node for query analysis records
            columns:
              - column:
                  name: id
                  remarks: PK
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: card_id
                  remarks: referenced card
                  type: int
                  constraints:
                    nullable: false
                    referencedTableName: report_card
                    referencedColumnNames: id
                    foreignKeyName: fk_query_analysis_card_id
                    deleteCascade: true
              - column:
                  remarks: The timestamp of when the analysis was created
                  name: created_at
                  type: ${timestamp_type}
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false
              - column:
                  remarks: The timestamp of when the analysis was updated
                  name: updated_at
                  type: ${timestamp_type}
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false

  - changeSet:
      id: v51.2024-07-29T09:23:12
      author: crisptrutski
      comment: Index query_analysis.card_id
      rollback: # not necessary, will be removed with the table
      changes:
        - createIndex:
            tableName: query_analysis
            indexName: idx_query_analysis_card_id
            columns:
              column:
                name: card_id

  - changeSet:
      id: v51.2024-07-29T09:24:13
      author: crisptrutski
      comment: Add the query_table join table
      changes:
        - createTable:
            tableName: query_table
            remarks: Tables used by a card's query
            columns:
              - column:
                  name: id
                  remarks: PK
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: card_id
                  remarks: referenced card
                  type: int
                  constraints:
                    nullable: false
                    referencedTableName: report_card
                    referencedColumnNames: id
                    foreignKeyName: fk_query_table_card_id
                    deleteCascade: true
              - column:
                  name: analysis_id
                  remarks: round of analysis
                  type: int
                  constraints:
                    nullable: false
                    referencedTableName: query_analysis
                    referencedColumnNames: id
                    foreignKeyName: fk_query_table_analysis_id
                    deleteCascade: true
              - column:
                  name: table_id
                  remarks: referenced field
                  type: int
                  constraints:
                    nullable: true
                    referencedTableName: metabase_table
                    referencedColumnNames: id
                    foreignKeyName: fk_query_table_table_id
                    deleteCascade: true
              - column:
                  name: schema
                  type: varchar(254) # matching metabase_table.schema
                  remarks: name of the schema of the table being referenced
                  constraints:
                    nullable: true
              - column:
                  name: table
                  type: varchar(254) # matching metabase_table.name
                  remarks: name of the table or card being referenced
                  constraints:
                    nullable: false

  - changeSet:
      id: v51.2024-07-29T09:25:13
      author: crisptrutski
      comment: Index query_table.card_id
      rollback: # not necessary, will be removed with the table
      changes:
        - createIndex:
            tableName: query_table
            indexName: idx_query_table_card_id
            columns:
              column:
                name: card_id

  - changeSet:
      id: v51.2024-07-29T09:25:14
      author: crisptrutski
      comment: Index query_table.analysis_id
      rollback: # not necessary, will be removed with the table
      changes:
        - createIndex:
            tableName: query_table
            indexName: idx_query_table_analysis_id
            columns:
              column:
                name: analysis_id

  - changeSet:
      id: v51.2024-07-29T09:25:15
      author: crisptrutski
      comment: Index query_table.table_id
      rollback: # not necessary, will be removed with the table
      changes:
        - createIndex:
            tableName: query_table
            indexName: idx_query_table_table_id
            columns:
              column:
                name: table_id

  - changeSet:
      id: v51.2024-07-29T10:03:27
      author: crisptrutski
      comment: Wipe stale query fields, so we can add new non-nullable columns
      rollback: # none, entries will be recreated by sweeper
      changes:
        - delete:
            tableName: query_field
            remarks: remove stale analysis, so the new fields can be non-nullable

  - changeSet:
      id: v51.2024-07-29T10:04:13
      author: crisptrutski
      comment: Put Query Fields under a parent Query Analysis record
      changes:
        - addColumn:
            tableName: query_field
            columns:
              - column:
                  name: analysis_id
                  remarks: round of analysis
                  type: int
                  constraints:
                    nullable: false
                    referencedTableName: query_analysis
                    referencedColumnNames: id
                    foreignKeyName: fk_query_field_analysis_id
                    deleteCascade: true
                    deleteCascadeForce: true # its safe as we have truncated the table
      rollback:
        - dropForeignKeyConstraint:
            baseTableName: query_field
            constraintName: fk_query_field_analysis_id
        - dropColumn:
            tableName: query_field
            columnName: analysis_id

  - changeSet:
      id: v51.2024-07-29T11:25:13
      author: crisptrutski
      comment: Index query_field.analysis_id
      rollback: # not necessary, will be removed with the table
      changes:
        - createIndex:
            tableName: query_field
            indexName: idx_query_field_analysis_id
            columns:
              column:
                name: analysis_id

  - changeSet:
      id: v51.2024-08-02T11:56:27
      author: crisptrutski
      comment: Add `schema` column to query fields
      changes:
        - addColumn:
            tableName: query_field
            columns:
              - column:
                  name: schema
                  type: varchar(254) # matching metabase_table.schema
                  remarks: name of the schema of the table being referenced
                  constraints:
                    nullable: true

  - changeSet:
      id: v51.2024-08-02T12:02:21
      validCheckSum: ANY
      author: crisptrutski
      comment: Make `table` nullable on query fields
      rollback: # we don't need one, the column will be dropped
      changes:
        - dropNotNullConstraint:
            tableName: query_field
            columnDataType: varchar(254) # matching metabase_table.name
            columnName: table
            remarks: This value is null if the field does not exist, and macaw could not determine the table

  - changeSet:
      id: v51.2024-08-05T16:00:00
      author: metamben
      comment: Add source card reference to report_card to support metrics based models and questions
      changes:
        - addColumn:
            tableName: report_card
            columns:
              - column:
                  name: source_card_id
                  remarks: The ID of the model or question this card is based on
                  type: int

  - changeSet:
      id: v51.2024-08-05T16:00:01
      author: metamben
      comment: Add FK constraint to report_card.source_card_id
      changes:
        - addForeignKeyConstraint:
            baseTableName: report_card
            baseColumnNames: source_card_id
            referencedTableName: report_card
            referencedColumnNames: id
            constraintName: fk_report_card_source_card_id_ref_report_card_id
            nullable: true
            deleteCascade: true

  - changeSet:
      id: v51.2024-08-05T16:00:02
      author: metamben
      comment: Index report_card.source_card_id
      rollback: # not necessary, will be removed with the table
      changes:
        - createIndex:
            tableName: report_card
            indexName: idx_report_card_source_card_id
            columns:
              column:
                name: source_card_id


  - changeSet:
      id: v51.2024-08-07T10:00:00
      author: ranquild
      comment: Remove field refs from report_card.visualization_settings.column_settings
      validCheckSum: ANY
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.MigrateLegacyColumnKeysInCardVizSettings"

  - changeSet:
      id: v51.2024-08-07T11:00:00
      author: ranquild
      comment: Remove field refs from report_dashboardcard.visualization_settings.column_settings
      validCheckSum: ANY
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.MigrateLegacyColumnKeysInDashboardCardVizSettings"

  - changeSet:
      id: v51.2024-08-26T08:53:46
      author: crisptrutski
      comment: Add a status column to track the progress and outcome of query analysis
      changes:
        - addColumn:
            tableName: query_analysis
            columns:
              - column:
                  name: status
                  type: ${text.type}
                  remarks: running, failed, or completed

  - changeSet:
      id: v51.2024-09-03T16:54:18
      author: adam-james
      comment: Add pivot_results to pulse_card
      changes:
        - addColumn:
            tableName: pulse_card
            columns:
              - column:
                  name: pivot_results
                  type: ${boolean.type}
                  defaultValue: false
                  remarks: Whether or not to apply pivot processing to the rows of the export

  - changeSet:
      id: v51.2024-09-09T15:11:16
      author: johnswanson
      comment: add an index for `collection.type`
      changes:
        - createIndex:
            tableName: collection
            columns:
              - column:
                  name: type
            indexName: idx_collection_type

  - changeSet:
      id: v51.2024-09-26T03:01:00
      author: escherize
      comment: iff enable-embedding is set, copy -> enable-embedding-interactive
      preConditions:
        - onFail: MARK_RAN
        - or:
            - and:
                - dbms:
                    type: postgresql
                - sqlCheck:
                    expectedResult: 1
                    sql: SELECT count(*) FROM setting WHERE key = 'enable-embedding';
            - and:
                - dbms:
                    type: mysql,mariadb
                - sqlCheck:
                    expectedResult: 1
                    sql: SELECT count(*) FROM setting WHERE `key` = 'enable-embedding';
            - and:
                - dbms:
                    type: h2
                - sqlCheck:
                    expectedResult: 1
                    sql: SELECT count(*) FROM setting WHERE "KEY" = 'enable-embedding';
      changes:
        - sql:
            dbms: postgresql
            sql: >-
              INSERT INTO setting (key, value)
              SELECT 'enable-embedding-interactive', value
              FROM setting
              WHERE key = 'enable-embedding';
        - sql:
            dbms: mysql,mariadb
            sql: >-
              INSERT INTO setting (`key`, `value`)
              SELECT 'enable-embedding-interactive', value
              FROM setting
              WHERE `key` = 'enable-embedding';
        - sql:
            dbms: h2
            sql: >-
              INSERT INTO setting ("KEY", "VALUE")
              SELECT 'enable-embedding-interactive', "VALUE"
              FROM setting
              WHERE "KEY" = 'enable-embedding';
      rollback: # not needed

  - changeSet:
      id: v51.2024-09-26T03:02:00
      author: escherize
      comment: iff enable-embedding is set, copy -> enable-embedding-static
      preConditions:
        - onFail: MARK_RAN
        - or:
            - and:
                - dbms:
                    type: postgresql
                - sqlCheck:
                    expectedResult: 1
                    sql: SELECT count(*) FROM setting WHERE key = 'enable-embedding';
            - and:
                - dbms:
                    type: mysql,mariadb
                - sqlCheck:
                    expectedResult: 1
                    sql: SELECT count(*) FROM setting WHERE `key` = 'enable-embedding';
            - and:
                - dbms:
                    type: h2
                - sqlCheck:
                    expectedResult: 1
                    sql: SELECT count(*) FROM setting WHERE "KEY" = 'enable-embedding';
      changes:
        - sql:
            dbms: postgresql
            sql: >-
              INSERT INTO setting (key, value)
              SELECT 'enable-embedding-static', value
              FROM setting
              WHERE key = 'enable-embedding';
        - sql:
            dbms: mysql,mariadb
            sql: >-
              INSERT INTO setting (`key`, `value`)
              SELECT 'enable-embedding-static', value
              FROM setting
              WHERE `key` = 'enable-embedding';
        - sql:
            dbms: h2
            sql: >-
              INSERT INTO setting ("KEY", "VALUE")
              SELECT 'enable-embedding-static', "VALUE"
              FROM setting
              WHERE "KEY" = 'enable-embedding';
      rollback: # not needed

  - changeSet:
      id: v51.2024-09-26T03:03:00
      author: escherize
      comment: iff enable-embedding is set, copy -> enable-embedding-sdk
      preConditions:
        - onFail: MARK_RAN
        - or:
            - and:
                - dbms:
                    type: postgresql
                - sqlCheck:
                    expectedResult: 1
                    sql: SELECT count(*) FROM setting WHERE key = 'enable-embedding';
            - and:
                - dbms:
                    type: mysql,mariadb
                - sqlCheck:
                    expectedResult: 1
                    sql: SELECT count(*) FROM setting WHERE `key` = 'enable-embedding';
            - and:
                - dbms:
                    type: h2
                - sqlCheck:
                    expectedResult: 1
                    sql: SELECT count(*) FROM setting WHERE "KEY" = 'enable-embedding';
      changes:
        - sql:
            dbms: postgresql
            sql: >-
              INSERT INTO setting (key, value)
              SELECT 'enable-embedding-sdk', value
              FROM setting
              WHERE key = 'enable-embedding';
        - sql:
            dbms: mysql,mariadb
            sql: >-
              INSERT INTO setting (`key`, `value`)
              SELECT 'enable-embedding-sdk', value
              FROM setting
              WHERE `key` = 'enable-embedding';
        - sql:
            dbms: h2
            sql: >-
              INSERT INTO setting ("KEY", "VALUE")
              SELECT 'enable-embedding-sdk', "VALUE"
              FROM setting
              WHERE "KEY" = 'enable-embedding';
      rollback: # not needed

  - changeSet:
      id: v51.2024-09-26T03:04:00
      author: escherize
      comment: iff embedding-app-origin is set, copy -> embedding-app-origins-interactive
      preConditions:
        - onFail: MARK_RAN
        - or:
            - and:
                - dbms:
                    type: postgresql
                - sqlCheck:
                    expectedResult: 1
                    sql: SELECT count(*) FROM setting WHERE key = 'embedding-app-origin';
            - and:
                - dbms:
                    type: mysql,mariadb
                - sqlCheck:
                    expectedResult: 1
                    sql: SELECT count(*) FROM setting WHERE `key` = 'embedding-app-origin';
            - and:
                - dbms:
                    type: h2
                - sqlCheck:
                    expectedResult: 1
                    sql: SELECT count(*) FROM setting WHERE "KEY" = 'embedding-app-origin';
      changes:
        - sql:
            dbms: postgresql
            sql: >-
              INSERT INTO setting (key, value)
              SELECT 'embedding-app-origins-interactive', value
              FROM setting
              WHERE key = 'embedding-app-origin';
        - sql:
            dbms: mysql,mariadb
            sql: >-
              INSERT INTO setting (`key`, `value`)
              SELECT 'embedding-app-origins-interactive', value
              FROM setting
              WHERE `key` = 'embedding-app-origin';
        - sql:
            dbms: h2
            sql: >-
              INSERT INTO setting ("KEY", "VALUE")
              SELECT 'embedding-app-origins-interactive', "VALUE"
              FROM setting
              WHERE "KEY" = 'embedding-app-origin';
      rollback: # not needed

  - changeSet:
      id: v51.2024-10-24T14:23:58
      author: noahmoss
      comment: Drop not null constraint on persisted_info.card_id
      changes:
        - dropNotNullConstraint:
            tableName: persisted_info
            columnName: card_id
            columnDataType: int
      rollback:
        - addNotNullConstraint:
            tableName: persisted_info
            columnName: card_id
            columnDataType: int

  - changeSet:
      id: v51.2024-10-24T14:24:59
      author: noahmoss
      comment: Drop foreign key constraint on persisted_info.card_id
      changes:
        - dropForeignKeyConstraint:
            constraintName: fk_persisted_info_card_id
            baseTableName: persisted_info
      rollback:
        - addForeignKeyConstraint:
            baseTableName: persisted_info
            baseColumnNames: card_id
            referencedTableName: report_card
            referencedColumnNames: id
            constraintName: fk_persisted_info_card_id
            onDelete: CASCADE

  - changeSet:
      id: v51.2024-10-24T14:25:01
      author: noahmoss
      comment: Re-add nullable foreign key constraint on persisted_info.card_id
      changes:
        - addForeignKeyConstraint:
            baseTableName: persisted_info
            baseColumnNames: card_id
            referencedTableName: report_card
            referencedColumnNames: id
            constraintName: fk_persisted_info_card_id
            onDelete: SET NULL
      rollback:
        - dropForeignKeyConstraint:
            constraintName: fk_persisted_info_card_id
            baseTableName: persisted_info

  - changeSet:
      id: v52.2024-09-05T08:00:00
      author: qnkhuat
      comment: Create the notification table
      changes:
        - createTable:
            tableName: notification
            remarks: join table that connect notification subscriptions and notification handlers
            columns:
              - column:
                  name: id
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: payload_type
                  remarks: the type of the payload
                  type: varchar(64)
                  constraints:
                    nullable: false
              - column:
                  name: active
                  remarks: whether the notification is active
                  type: ${boolean.type}
                  constraints:
                    nullable: false
                  defaultValueBoolean: true
              - column:
                  remarks: The timestamp of when the notification was created
                  name: created_at
                  type: ${timestamp_type}
                  constraints:
                    nullable: false
              - column:
                  name: updated_at
                  remarks: The timestamp of when the notification was updated
                  type: ${timestamp_type}
                  constraints:
                    nullable: false

  - changeSet:
      id: v52.2024-09-05T08:00:01
      author: qnkhuat
      comment: Create the notification_subscription table
      changes:
        - createTable:
            remarks: which type of trigger a notification is subscribed to
            tableName: notification_subscription
            columns:
              - column:
                  name: id
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: notification_id
                  remarks: the notification that the subscription is connected to
                  type: int
                  constraints:
                    nullable: false
                    referencedTableName: notification
                    referencedColumnNames: id
                    foreignKeyName: fk_notification_subscription_notification_id
                    deleteCascade: true
              - column:
                  name: type
                  remarks: the type of the subscription
                  type: varchar(64)
                  constraints:
                    nullable: false
              - column:
                  name: event_name
                  remarks: the event name of subscriptions with type :notification-subscription/system-event
                  type: varchar(64)
                  constraints:
                    nullable: true
              - column:
                  name: created_at
                  remarks: The timestamp of when the subscription was created
                  type: ${timestamp_type}
                  constraints:
                    nullable: false

  - changeSet:
      id: v52.2024-09-05T08:00:02
      author: qnkhuat
      comment: index on notification_subscription.notification_id
      rollback: # no need, will be dropped with the table
      changes:
        - createIndex:
            tableName: notification_subscription
            columns:
              - column:
                  name: notification_id
            indexName: idx_notification_subscription_notification_id

  - changeSet:
      id: v52.2024-09-05T08:00:03
      author: qnkhuat
      comment: Create the channel_template table
      changes:
        - createTable:
            tableName: channel_template
            remarks: custom template for the channel
            columns:
              - column:
                  name: id
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: name
                  type: varchar(64)
                  remarks: the name of the template
                  constraints:
                    nullable: false
              - column:
                  name: channel_type
                  type: varchar(64)
                  remarks: the channel type of the template
                  constraints:
                    nullable: false
              - column:
                  name: details
                  type: ${text.type}
                  remarks: the details of the template
                  constraints:
                    nullable: true
              - column:
                  name: entity_id
                  type: char(21)
                  remarks: Random NanoID tag for unique identity.
                  constraints:
                    nullable: true
                    unique: true
              - column:
                  name: created_at
                  type: ${timestamp_type}
                  remarks: The timestamp of when the template was created
                  constraints:
                    nullable: false
              - column:
                  name: updated_at
                  type: ${timestamp_type}
                  remarks: The timestamp of when the template was last updated
                  constraints:
                    nullable: false

  - changeSet:
      id: v52.2024-09-05T08:00:04
      author: qnkhuat
      comment: Create the notification_handler table
      validCheckSum: ANY
      changes:
        - createTable:
            tableName: notification_handler
            remarks: which channel to send the notification to
            columns:
              - column:
                  name: id
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              # TODO: can be removed once emails and slack configuration are fully migrated to be stored in channel table.
              - column:
                  name: channel_type
                  type: varchar(64)
                  remarks: the type of the channel, like :channel/email, :channel/slack
                  constraints:
                    nullable: false
              - column:
                  name: notification_id
                  type: int
                  remarks: the notification that the handler is connected to
                  constraints:
                    nullable: false
                    referencedTableName: notification
                    referencedColumnNames: id
                    foreignKeyName: fk_notification_handler_notification_id
                    deleteCascade: true
              - column:
                  name: channel_id
                  type: int
                  remarks: the channel that the handler is connected to
                  constraints:
                    nullable: true # temporarily nullable, because we need to support email and slack channels as global configuration
                    referencedTableName: channel
                    referencedColumnNames: id
                    foreignKeyName: fk_notification_handler_channel_id
                    deleteCascade: true
              - column:
                  name: template_id
                  type: int
                  remarks: the template that the handler is connected to
                  constraints:
                    nullable: true
              - column:
                  name: active
                  type: ${boolean.type}
                  remarks: whether the handler is active
                  defaultValueBoolean: true
                  constraints:
                    nullable: false
              - column:
                  name: created_at
                  type: ${timestamp_type}
                  remarks: The timestamp of when the handler was created
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false
              - column:
                  name: updated_at
                  type: ${timestamp_type}
                  remarks: The timestamp of when the handler was updated
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false
  - changeSet:
      id: v52.2024-09-05T08:00:05
      author: qnkhuat
      comment: Add fk constraint to notification_handler.template_id
      changes:
        - addForeignKeyConstraint:
            baseTableName: notification_handler
            baseColumnNames: template_id
            referencedTableName: channel_template
            referencedColumnNames: id
            constraintName: fk_notification_handler_template_id
            onDelete: SET NULL

  - changeSet:
      id: v52.2024-09-05T08:00:06
      author: qnkhuat
      comment: index on notification_handler.notification_id
      rollback: # not necessary, will be removed with the table
      changes:
        - createIndex:
            tableName: notification_handler
            columns:
              - column:
                  name: notification_id
            indexName: idx_notification_handler_notification_id

  - changeSet:
      id: v52.2024-09-05T08:00:07
      author: qnkhuat
      comment: index on notification_handler.channel_id
      rollback: # not necessary, will be removed with the table
      changes:
        - createIndex:
            tableName: notification_handler
            columns:
              - column:
                  name: channel_id
            indexName: idx_notification_handler_channel_id

  - changeSet:
      id: v52.2024-09-05T08:00:08
      author: qnkhuat
      comment: index on notification_handler.template_id
      rollback: # not necessary, will be removed with the table
      changes:
        - createIndex:
            tableName: notification_handler
            columns:
              - column:
                  name: template_id
            indexName: idx_notification_handler_template_id

  - changeSet:
      id: v52.2024-09-05T08:00:09
      author: qnkhuat
      comment: Create the notification_recipient table
      changes:
        - createTable:
            tableName: notification_recipient
            remarks: who should receive the notification
            columns:
              - column:
                  name: id
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: notification_handler_id
                  type: int
                  remarks: the handler that the recipient is connected to
                  constraints:
                    nullable: false
                    referencedTableName: notification_handler
                    referencedColumnNames: id
                    foreignKeyName: fk_notification_recipient_notification_handler_id
                    deleteCascade: true
              - column:
                  name: type
                  type: varchar(64)
                  remarks: the type of the recipient
                  constraints:
                    nullable: false
              - column:
                  name: user_id
                  type: int
                  remarks: a user if the recipient has type user
                  constraints:
                    nullable: true
                    referencedTableName: core_user
                    referencedColumnNames: id
                    foreignKeyName: fk_notification_recipient_user_id
                    deleteCascade: true
              - column:
                  name: permissions_group_id
                  type: int
                  remarks: a permissions group if the recipient has type permissions_group
                  constraints:
                    nullable: true
                    referencedTableName: permissions_group
                    referencedColumnNames: id
                    foreignKeyName: fk_notification_recipient_permissions_group_id
                    deleteCascade: true
              - column:
                  name: details
                  type: ${text.type}
                  remarks: custom details for the recipient
                  constraints:
                    nullable: true
              - column:
                  name: created_at
                  type: ${timestamp_type}
                  remarks: The timestamp of when the recipient was created
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false
              - column:
                  name: updated_at
                  type: ${timestamp_type}
                  remarks: The timestamp of when the recipient was updated
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false

  - changeSet:
      id: v52.2024-09-05T08:00:10
      author: qnkhuat
      comment: index on notification_recipient.notification_handler_id
      rollback: # not necessary, will be removed with the table
      changes:
        - createIndex:
            tableName: notification_recipient
            columns:
              - column:
                  name: notification_handler_id
            indexName: idx_notification_recipient_notification_handler_id

  - changeSet:
      id: v52.2024-09-05T08:00:11
      author: qnkhuat
      comment: index on notification_recipient.user_id
      rollback: # not necessary, will be removed with the table
      changes:
        - createIndex:
            tableName: notification_recipient
            columns:
              - column:
                  name: user_id
            indexName: idx_notification_recipient_user_id

  - changeSet:
      id: v52.2024-09-05T08:00:12
      author: qnkhuat
      comment: index on notification_recipient.permissions_group_id
      rollback: # not necessary, will be removed with the table
      changes:
        - createIndex:
            tableName: notification_recipient
            columns:
              - column:
                  name: permissions_group_id
            indexName: idx_notification_recipient_permissions_group_id

  - changeSet:
      id: v52.2024-09-05T08:00:13
      author: qnkhuat
      comment: Drop the channel_template.entity_id column
      changes:
        - dropColumn:
            tableName: channel_template
            columnName: entity_id
      rollback: # not necessary, will be removed with the table

  - changeSet:
      id: v52.2024-10-15T08:00:00
      author: qnkhuat
      comment: add notification_subscription.cron_schedule
      changes:
        - addColumn:
            tableName: notification_subscription
            columns:
              - column:
                  name: cron_schedule
                  type: varchar(128)
                  remarks: the cron schedule for the subscription
                  constraints:
                    nullable: true

  - changeSet:
      id: v52.2024-10-26T18:42:42
      author: metamben
      comment: Add stage-number to dimension targets in parameter_mappings
      validCheckSum: ANY
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.AddStageNumberToParameterMappingTargets"

  - changeSet:
      id: v52.2024-11-12T15:13:18
      author: metamben
      comment: Add stage-number to dimension targets in visualization_settings
      validCheckSum: ANY
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.AddStageNumberToVizSettingsParameterMappingTargets"

  # This migration should be changed to a no-op and a new migration inserted that does the load from edn whenever the
  # sample content is updated, so that it matches when the version that the sample content was updated from. See
  # metabase#50829 for an example where the content was updated.
  - changeSet:
      id: v52.2024-12-03T15:55:22
      author: escherize
      comment: Create New and improved Sample Content
      validCheckSum: ANY
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.CreateSampleContentV2"

  - changeSet:
      id: v52.2024-12-10T10:28:16
      author: johnswanson
      comment: Add `report_card.dashboard_id`
      changes:
        - addColumn:
            tableName: report_card
            columns:
              - column:
                  name: dashboard_id
                  type: int
                  remarks: The dashboard that owns the card, if it is a dashboard-internal card.
                  constraints:
                    nullable: true

  - changeSet:
      id: v52.2024-12-10T10:28:21
      author: johnswanson
      comment: Make `report_card.dashboard_id` a foreign key
      changes:
        - addForeignKeyConstraint:
            baseTableName: report_card
            baseColumnNames: dashboard_id
            referencedTableName: report_dashboard
            referencedColumnNames: id
            constraintName: fk_report_card_ref_dashboard_id
            onDelete: CASCADE

  - changeSet:
      id: v52.2024-12-10T10:28:24
      author: johnswanson
      comment: Add an index for `report_card.dashboard_id`
      rollback: # will be removed with the column
      changes:
        - createIndex:
            indexName: idx_report_card_dashboard_id
            tableName: report_card
            columns:
              - column:
                  name: dashboard_id

  - changeSet:
      id: v52.2024-12-16T09:19:00
      author: crisptrutski
      comment: Metadata about search indexes
      changes:
        - createTable:
            tableName: search_index_metadata
            remarks: Each entry corresponds to some queryable index, and contains metadata about it.
            columns:
              - column:
                  name: id
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: engine
                  type: varchar(64)
                  remarks: 'The kind of search engine which this index belongs to.'
                  constraints:
                    nullable: false
              - column:
                  name: version
                  type: varchar(254)
                  remarks: 'Used to determine metabase compatibility. Format may depend on engine in future.'
                  constraints:
                    nullable: false
              - column:
                  name: index_name
                  type: varchar(254)
                  remarks: "The name by which the given engine refers to this particular index, e.g. table name."
                  constraints:
                    nullable: false
                    unique: true
              - column:
                  name: status
                  type: varchar(32)
                  remarks: One of 'pending', 'active', or 'retired'
                  constraints:
                    nullable: true
              - column:
                  remarks: The timestamp of when the index was created
                  name: created_at
                  type: ${timestamp_type}
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false
              - column:
                  remarks: The timestamp of when the index status was updated
                  name: updated_at
                  type: ${timestamp_type}
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false

  - changeSet:
      id: v52.2024-12-16T09:20:00
      author: crisptrutski
      comment: 'Protection against concurrent creation or promotion of indexes.'
      rollback: # will be removed with the table
      changes:
        - addUniqueConstraint:
            remarks: Unique entry for each status, from any given metabase instance's perspective.
            tableName: search_index_metadata
            constraintName: idx_search_index_metadata_unique_status
            columnNames: engine, version, status

  - changeSet:
      id: v52.2025-01-05T00:00:01
      author: escherize
      comment: set enable-embedding-sdk false when embedding-app-origins-sdk value exists
      preConditions:
        - onFail: MARK_RAN
        - or:
            - and:
                - dbms:
                    type: postgresql
                - sqlCheck:
                    expectedResult: 0
                    sql: SELECT count(*) FROM setting WHERE key = 'embedding-app-origins-sdk';
            - and:
                - dbms:
                    type: mysql,mariadb
                - sqlCheck:
                    expectedResult: 0
                    sql: SELECT count(*) FROM setting WHERE `key` = 'embedding-app-origins-sdk';
            - and:
                - dbms:
                    type: h2
                - sqlCheck:
                    expectedResult: 0
                    sql: SELECT count(*) FROM setting WHERE "KEY" = 'embedding-app-origins-sdk';
      changes:
        - sql:
            dbms: postgresql
            sql: >-
              update setting set value = 'false' where key = 'enable-embedding-sdk';
        - sql:
            dbms: mysql,mariadb
            sql: >-
              UPDATE setting set `value` = 'false' where `key` = 'enable-embedding-sdk';
        - sql:
            dbms: h2
            sql: >-
              UPDATE setting set "VALUE" = 'false' where "KEY" = 'enable-embedding-sdk';
      rollback: # not needed

  - changeSet:
      id: v52.2025-05-28T00:00:01
      author: edpaget
      comment: set perms/download-results to no when a table has perms/view-data blocked
      changes:
         - sql:
            dbms: postgresql,h2
            sql: >-
              UPDATE data_permissions as update_dp SET perm_value = 'no'
              WHERE update_dp.perm_type = 'perms/download-results'
                  AND update_dp.perm_value <> 'no'
                  AND EXISTS (
                  SELECT 1 FROM data_permissions as dp
                  WHERE dp.group_id = update_dp.group_id
                      AND dp.db_id = update_dp.db_id
                      AND dp.table_id = update_dp.table_id
                      AND dp.perm_type = 'perms/view-data'
                      AND dp.perm_value = 'blocked'
                  )
         - sql:
            dbms: mariadb,mysql
            sql: >-
              UPDATE data_permissions as update_dp
              INNER JOIN data_permissions as dp
                  ON dp.group_id = update_dp.group_id
                  AND dp.db_id = update_dp.db_id
                  AND dp.table_id = update_dp.table_id
                  AND dp.perm_type = 'perms/view-data'
                  AND dp.perm_value = 'blocked'
              SET update_dp.perm_value = 'no'
              WHERE update_dp.perm_type = 'perms/download-results'
                  AND update_dp.perm_value <> 'no'
      rollback: # not needed

  - changeSet:
      id: v53.2024-12-02T16:21:15
      author: noahmoss
      comment: Add cache_config.refresh_automatically column
      changes:
        - addColumn:
            tableName: cache_config
            columns:
              - column:
                  name: refresh_automatically
                  type: ${boolean.type}
                  remarks: Whether or not we should automatically refresh cache results when a cache expires
                  defaultValueBoolean: false
                  constraints:
                    nullable: false

  - changeSet:
      id: v53.2024-12-02T17:21:16
      validCheckSum:
        - 9:209a494b250a08f022114249697cbc1b
        - 9:8adcf08936200cc74153d0c306452e0c
      author: noahmoss
      comment: Add query_execution.parameterized column
      changes:
        - addColumn:
            tableName: query_execution
            columns:
              - column:
                  name: parameterized
                  type: ${boolean.type}
                  remarks: Whether or not the query has parameters with non-nil values
                  constraints:
                    nullable: true

  - changeSet:
      id: v53.2024-12-10T10:00:00
      author: qnkhuat
      comment: add notification.internal_id
      changes:
        - addColumn:
            tableName: notification
            columns:
              - column:
                  name: internal_id
                  type: varchar(254)
                  remarks: the internal id of the notification
                  constraints:
                    nullable: true
                    unique: true

  # Prior to this, we used to truncate then insert notifications on startup (#50127)
  # But we can't do that anymore because pulses are migated to notification, so moving forward
  # we'll insert/replace notifications on startup (see metabase.notification.seed)
  # We need to do another truncate here so we have a clean slate for the new notifications
  - changeSet:
      id: v53.2024-12-10T10:00:10
      author: qnkhuat
      comment: Truncate the notification tables
      rollback: # not needed
      changes:
        - sql:
            dbms: postgresql
            sql: >-
              TRUNCATE TABLE notification RESTART IDENTITY CASCADE;
              TRUNCATE TABLE notification_handler RESTART IDENTITY CASCADE;
              TRUNCATE TABLE notification_subscription RESTART IDENTITY CASCADE;
              TRUNCATE TABLE notification_recipient RESTART IDENTITY CASCADE;
              TRUNCATE TABLE channel_template RESTART IDENTITY CASCADE;
        - sql:
            dbms: mysql,mariadb
            sql: >-
              DELETE FROM notification;
              ALTER TABLE notification AUTO_INCREMENT = 1;
              DELETE FROM notification_handler;
              ALTER TABLE notification_handler AUTO_INCREMENT = 1;
              DELETE FROM notification_subscription;
              ALTER TABLE notification_subscription AUTO_INCREMENT = 1;
              DELETE FROM notification_recipient;
              ALTER TABLE notification_recipient AUTO_INCREMENT = 1;
              DELETE FROM channel_template;
              ALTER TABLE channel_template AUTO_INCREMENT = 1;

        - sql:
            dbms: h2
            sql: >-
              DELETE FROM notification;
              DELETE FROM notification_handler;
              DELETE FROM notification_subscription;
              DELETE FROM notification_recipient;
              DELETE FROM channel_template;
              ALTER TABLE notification ALTER COLUMN id RESTART WITH 1;
              ALTER TABLE notification_handler ALTER COLUMN id RESTART WITH 1;
              ALTER TABLE notification_subscription ALTER COLUMN id RESTART WITH 1;
              ALTER TABLE notification_recipient ALTER COLUMN id RESTART WITH 1;
              ALTER TABLE channel_template ALTER COLUMN id RESTART WITH 1;

  - changeSet:
      id: v53.2024-12-20T19:53:50
      author: johnswanson
      comment: >
        add a table for user-level KV. This is intended for use as a lightweight mechanism for the frontend to be able
        to mark things as seen, unseen, dismissed, etc
      changes:
        - createTable:
            tableName: user_key_value
            remarks: A simple key value store for each user.
            columns:
              - column:
                  name: id
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: user_id
                  type: int
                  remarks: 'The ID of the user this KV-pair is for'
                  constraints:
                    nullable: false
                    referencedTableName: core_user
                    referencedColumnNames: id
                    foreignKeyName: fk_user_key_value_user_id
              - column:
                  name: namespace
                  type: varchar(254)
                  remarks: 'The namespace for this KV, e.g. "dashboard-filters" or "nobody-knows"'
                  constraints:
                    nullable: false
              - column:
                  name: key
                  remarks: 'The key'
                  type: varchar(254)
                  constraints:
                    nullable: false
              - column:
                  name: value
                  remarks: 'The value, serialized JSON'
                  type: ${text.type}
                  constraints:
                    nullable: true
              - column:
                  name: created_at
                  remarks: 'When this row was created'
                  type: ${timestamp_type}
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false
              - column:
                  name: updated_at
                  remarks: 'When this row was last updated'
                  type: ${timestamp_type}
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false
              - column:
                  name: expires_at
                  remarks: 'If set, when this row expires'
                  type: ${timestamp_type}
                  defaultValue: null

  - changeSet:
      id: v53.2024-12-20T19:53:59
      author: johnswanson
      comment: Add a unique constraint for user_id,namespace,key
      changes:
        - addUniqueConstraint:
            tableName: user_key_value
            columnNames: user_id, namespace, key
            constraintName: unique_user_key_value_user_id_namespace_key
      rollback: # will be deleted with table

  - changeSet:
      id: v53.2024-12-27T17:33:54
      author: nvoxland
      comment: Adds encryption-check setting to encryption management
      changes:
        - insert:
            tableName: setting
            columns:
              - column:
                  name: key
                  value: encryption-check
              - column:
                  name: value
                  value: "unencrypted"
      rollback:
        - sql:
            sql: "delete from setting where \"key\"='encryption-check'"
            dbms: postgresql
        - sql:
            sql: "delete from setting where `key`='encryption-check'"
            dbms: mysql,mariadb
        - sql:
            sql: "delete from setting where \"KEY\"='encryption-check'"
            dbms: h2

  - changeSet:
      id: v53.2024-12-27T20:17:23
      author: noahmoss
      comment: Drop unnecessary NOT NULL constraint from cache_config.refresh_automatically column
      changes:
        - dropNotNullConstraint:
            tableName: cache_config
            columnName: refresh_automatically
            columnDataType: ${boolean.type}
      rollback:
        - addNotNullConstraint:
            tableName: cache_config
            columnName: refresh_automatically
            columnDataType: ${boolean.type}
            defaultNullValue: false

  - changeSet:
      id: v53.2025-01-03T19:07:39
      author: noahmoss
      comment: Add `deactivated_at` column to the `core_user` table
      changes:
        - addColumn:
            tableName: core_user
            columns:
              - column:
                  name: deactivated_at
                  type: ${timestamp_type}
                  remarks: The timestamp at which a user was deactivated

  - changeSet:
      id: v53.2025-02-20T04:49:39
      author: johnswanson
      comment: remove unused cards in usage analytics
      changes:
        - sql: |
            DELETE FROM report_card WHERE entity_id IN (
              'Y0ZykgQ64HHwAW_MYx-dW',
              '3CtVT_JDxNvMM5aFLtEHR',
              'hFpp3c-7Y-CtMOrs3zeyn',
              'PkIueKBME3DfRFwBsYjuE',
              '4DlO-I7ry2OaVQy7-RGPU',
              'lh0sbjKcm9BhiiHPpPxRa',
              '9shJ0y29V5o1lOSDL4ImJ',
              'WoQnk12nwOaJ1pcb1wsr4',
              '-_XgVaPuz7MY8jlG0wSEC',
              'LXu_IZa1EDg3QOhlwunGy',
              'Fnu5Kh0gYPN6P8A_fvICu'
            );
      rollback: # not needed, these are created on startup using deserialization

  - changeSet:
      id: v53.2025-04-02T15:25:04
      author: edpaget
      comment: create new cluster lock table for instance coordination
      changes:
        - createTable:
            tableName: metabase_cluster_lock
            remarks: A table to allow metabase instances to take locks across a cluster
            columns:
              - column:
                  name: lock_name
                  type: varchar(254)
                  remarks: a single column that can be used to a lock across a cluster
                  constraints:
                    primaryKey: true
                    nullable: false

  - changeSet:
      id: v53.2025-05-06T16:03:19
      author: nvoxland
      comment: Support indexing of values with bigint ids
      changes:
        - modifyDataType:
            tableName: model_index_value
            columnName: model_pk
            newDataType: bigint
      rollback:
        - modifyDataType:
            tableName: model_index_value
            columnName: model_pk
            newDataType: int

  - changeSet:
      id: v54.2025-01-30T16:10:55
      author: bshepherdson
      comment: Add `entity_id` column to the `metabase_database` table
      changes:
        - addColumn:
            tableName: metabase_database
            columns:
              - column:
                  remarks: Random NanoID tag for unique identity.
                  name: entity_id
                  type: char(21)
                  constraints:
                    nullable: true
                    unique: true

  - changeSet:
      id: v54.2025-01-30T16:13:20
      author: bshepherdson
      comment: Add `entity_id` column to the `metabase_table` table
      changes:
        - addColumn:
            tableName: metabase_table
            columns:
              - column:
                  remarks: Random NanoID tag for unique identity.
                  name: entity_id
                  type: char(21)
                  constraints:
                    nullable: true
                    unique: true

  - changeSet:
      id: v54.2025-01-30T16:14:02
      author: bshepherdson
      comment: Add `entity_id` column to the `metabase_field` table
      changes:
        - addColumn:
            tableName: metabase_field
            columns:
              - column:
                  remarks: Random NanoID tag for unique identity.
                  name: entity_id
                  type: char(21)
                  constraints:
                    nullable: true
                    unique: true

  - changeSet:
      id: v54.2025-02-14T08:00:00
      author: qnkhuat
      comment: add notification.payload_id
      changes:
        - addColumn:
            tableName: notification
            columns:
              - column:
                  name: payload_id
                  type: int
                  remarks: the internal id of the notification
                  constraints:
                    nullable: true

  - changeSet:
      id: v54.2025-02-14T08:01:00
      author: qnkhuat
      comment: create the notification_card table
      changes:
        - createTable:
            tableName: notification_card
            remarks: Card related notifications
            columns:
              - column:
                  name: id
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: card_id
                  type: int
                  remarks: the card that the alert is connected to
                  constraints:
                    nullable: true
                    referencedTableName: report_card
                    referencedColumnNames: id
                    foreignKeyName: fk_notification_card_card_id
                    deleteCascade: true
              - column:
                  name: send_once
                  type: ${boolean.type}
                  remarks: whether the alert should only run once
                  defaultValueBoolean: false
                  constraints:
                    nullable: false
              - column:
                  name: send_condition
                  type: varchar(32)
                  remarks: the condition of the alert
                  constraints:
                    nullable: false
              - column:
                  name: created_at
                  type: ${timestamp_type}
                  remarks: The timestamp of when the recipient was created
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false
              - column:
                  name: updated_at
                  type: ${timestamp_type}
                  remarks: The timestamp of when the recipient was updated
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false

  - changeSet:
      id: v54.2025-02-14T08:03:00
      author: qnkhuat
      comment: add notification.creator_id
      changes:
        - addColumn:
            tableName: notification
            columns:
              - column:
                  name: creator_id
                  type: int
                  remarks: the id of the creator
                  constraints:
                    nullable: true

  - changeSet:
      id: v54.2025-02-14T08:04:00
      author: qnkhuat
      comment: add fk constraint to notification.creator_id
      changes:
        - addForeignKeyConstraint:
            baseTableName: notification
            baseColumnNames: creator_id
            referencedTableName: core_user
            referencedColumnNames: id
            constraintName: fk_notification_creator_id
            onDelete: CASCADE
            nullable: true

  - changeSet:
      id: v54.2025-02-14T08:04:01
      author: qnkhuat
      comment: Add an index for `notification.creator_id`
      rollback: # will be removed with the column
      changes:
        - createIndex:
            indexName: idx_notification_creator_id
            tableName: notification
            columns:
              - column:
                  name: creator_id

  - changeSet:
      id: v54.2025-02-14T08:04:02
      author: qnkhuat
      comment: Add an index for `notification_card.card_id`
      rollback: # will be removed with the column
      changes:
        - createIndex:
            indexName: idx_notification_card_card_id
            tableName: notification_card
            columns:
              - column:
                  name: card_id

  - changeSet:
      id: v54.2025-02-14T08:05:00
      author: qnkhuat
      comment: Migrate alert to notification
      validCheckSum: ANY
      changes:
        - customChange:
            class: "metabase.app_db.custom_migrations.MigrateAlertToNotification"

  - changeSet:
      id: v54.2025-02-14T08:06:00
      author: qnkhuat
      comment: Delete all the migrated alerts from notification table
      changes:
        - sql: select 1;
      rollback:
        # delete all migrated notification on rollback so we can re-run the migration
        # no need to delete notification_card because the table will be dropped
        - sql:
            sql: >-
              DELETE FROM notification WHERE payload_type = 'notification/card';

  - changeSet:
      id: v54.2025-02-14T08:07:00
      author: qnkhuat
      comment: Update view v_alerts to read from notification tables
      changes:
        - sqlFile:
            dbms: postgresql
            path: instance_analytics_views/alerts/v2/postgres-alerts.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: instance_analytics_views/alerts/v2/mysql-alerts.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: instance_analytics_views/alerts/v2/h2-alerts.sql
            relativeToChangelogFile: true
      rollback:
        - sqlFile:
            dbms: postgresql
            path: instance_analytics_views/alerts/v1/postgres-alerts.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: instance_analytics_views/alerts/v1/mysql-alerts.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: instance_analytics_views/alerts/v1/h2-alerts.sql
            relativeToChangelogFile: true

  - changeSet:
      id: v54.2025-03-06T16:55:15
      author: nvoxland
      comment: Replacing storing the session key in the "id" column in favor of storing a new hashed version
      changes:
        - addColumn:
            tableName: core_session
            columns:
              - column:
                  name: key_hashed
                  type: varchar(254)
                  value: "upgrade placeholder"
                  remarks: Hashed version of the session key
                  constraints:
                    nullable: false

  - changeSet:
      id: v54.2025-03-06T16:55:16
      author: nvoxland
      comment: Creating index on the hashed session key
      changes:
        - createIndex:
            tableName: core_session
            columns:
              - column:
                  name: key_hashed
            indexName: idx_core_session_key_hashed

  - changeSet:
      id: v54.2025-03-11T16:00:00
      author: qnkhuat
      comment: add notification_subscription.ui_display_type
      changes:
        - addColumn:
            tableName: notification_subscription
            columns:
              - column:
                  name: ui_display_type
                  type: varchar(32)
                  remarks: the display of the subscription, used for the UI only
                  constraints:
                    nullable: true

  - changeSet:
      id: v54.2025-03-17T18:52:44
      author: noahmoss
      comment: Migrating zh site locales to zh_CN
      changes:
        - sql:
            dbms: postgresql
            sql: >-
              UPDATE setting SET value = 'zh_CN' where key = 'site-locale' AND value = 'zh';
        - sql:
            dbms: mysql,mariadb
            sql: >-
              UPDATE setting SET `value` = 'zh_CN' where `key` = 'site-locale' AND `value` = 'zh';
        - sql:
            dbms: h2
            sql: >-
              UPDATE setting SET "VALUE" = 'zh_CN' where "KEY" = 'site-locale' AND "VALUE" = 'zh';
      rollback: # nothing to do; zh_CN is backwards compatible

  - changeSet:
      id: v54.2025-03-17T18:52:59
      author: noahmoss
      comment: Migrating zh user locales to zh_CN
      changes:
        - sql:
            sql: >-
              UPDATE core_user SET locale = 'zh_CN' WHERE locale = 'zh';
      rollback: # nothing to do; zh_CN is backwards compatible

  - changeSet:
      id: v54.2025-03-25T16:34:12
      author: edpaget
      comment: Add index to field_usage query_execution_id column to support faster deletes
      rollback: # cannot rollback an index on a fk in mysql
      changes:
        - createIndex:
            tableName: field_usage
            columns:
              - column:
                  name: query_execution_id
            indexName: idx_field_usage_query_execution_id

  - changeSet:
      id: v54.2025-03-27T17:52:01
      author: luizarakaki
      comment: updating v_tasks to add new `status` field
      changes:
        - sqlFile:
            dbms: postgresql
            path: instance_analytics_views/tasks/v2/postgres-tasks.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: instance_analytics_views/tasks/v2/mysql-tasks.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: instance_analytics_views/tasks/v2/h2-tasks.sql
            relativeToChangelogFile: true
      rollback:
        - sqlFile:
            dbms: postgresql
            path: instance_analytics_views/tasks/v1/postgres-tasks.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: instance_analytics_views/tasks/v1/mysql-tasks.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: instance_analytics_views/tasks/v1/h2-tasks.sql
            relativeToChangelogFile: true

  - changeSet:
      id: v54.2025-03-28T11:22:01
      author: luizarakaki
      comment: updating v_content to add new `is_verified` field
      changes:
        - sqlFile:
            dbms: postgresql
            path: instance_analytics_views/content/v3/postgres-content.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: instance_analytics_views/content/v3/mysql-content.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: instance_analytics_views/content/v3/h2-content.sql
            relativeToChangelogFile: true
      rollback:
        - sqlFile:
            dbms: postgresql
            path: instance_analytics_views/content/v2/postgres-content.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: instance_analytics_views/content/v2/mysql-content.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: instance_analytics_views/content/v2/h2-content.sql
            relativeToChangelogFile: true

  - changeSet:
      id: v54.2025-05-13T21:46:53
      author: nvoxland
      comment: Add language to index metadata
      changes:
        - addColumn:
            tableName: search_index_metadata
            columns:
              - column:
                  name: lang_code
                  type: varchar(10)
                  remarks: Language code the data in the index is in
                  defaultValue: en
                  constraints:
                    nullable: false


  - changeSet:
      id: v54.2025-05-13T21:46:54
      author: nvoxland
      comment: Preparing to replace index
      changes:
        - dropUniqueConstraint:
            tableName: search_index_metadata
            constraintName: idx_search_index_metadata_unique_status
      rollback:
        - addUniqueConstraint:
            remarks: Unique entry for each status, from any given metabase instance's perspective.
            tableName: search_index_metadata
            constraintName: idx_search_index_metadata_unique_status
            columnNames: engine, version, status

  - changeSet:
      id: v54.2025-05-13T21:46:55
      author: nvoxland
      comment: 'Protection against concurrent creation or promotion of indexes.'
      changes:
        - addUniqueConstraint:
            remarks: Unique entry for each status, from any given metabase instance's perspective.
            tableName: search_index_metadata
            constraintName: idx_search_index_metadata_unique_status
            columnNames: engine, version, lang_code, status

  - changeSet:
      id: v54.2025-05-26T20:00:00
      author: qnkhuat
      comment: Update view v_alerts to correectly classify by the minute and custom schedule
      changes:
        - sqlFile:
            dbms: postgresql
            path: instance_analytics_views/alerts/v3/postgres-alerts.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: instance_analytics_views/alerts/v3/mysql-alerts.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: instance_analytics_views/alerts/v3/h2-alerts.sql
            relativeToChangelogFile: true
      rollback:
        - sqlFile:
            dbms: postgresql
            path: instance_analytics_views/alerts/v2/postgres-alerts.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: instance_analytics_views/alerts/v2/mysql-alerts.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: instance_analytics_views/alerts/v2/h2-alerts.sql
            relativeToChangelogFile: true

  - changeSet:
      id: v55.2025-03-24T16:28:41
      author: bshepherdson
      comment: Add report_card.card_schema
      changes:
        - addColumn:
            tableName: report_card
            columns:
              - column:
                  name: card_schema
                  type: int
                  remarks: Arbitrary revision number for how we store queries in report_card
                  defaultValue: 20
                  constraints:
                    nullable: false

  - changeSet:
      id: v55.2025-03-24T16:36:19
      author: bshepherdson
      comment: Creating index on the card_schema
      changes:
        - createIndex:
            tableName: report_card
            columns:
              - column:
                  name: card_schema
            indexName: idx_report_card_card_schema

  - changeSet:
      id: v55.2025-04-01T07:17:52
      author: johnswanson
      comment: Add `db_router` table
      changes:
        - createTable:
            tableName: db_router
            remarks: |
              Configuration for Database Routers. Currently just holds which user attribute each
              configured router database should use to choose a mirror database to route to.
            columns:
              - column:
                  name: id
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: database_id
                  type: int
                  remarks: 'The ID of the database this is for.'
                  constraints:
                    unique: true
                    nullable: false
                    referencedTableName: metabase_database
                    referencedColumnNames: id
                    foreignKeyName: fk_db_router_database_id
              - column:
                  name: user_attribute
                  type: varchar(254)
                  remarks: 'The user attribute used to redirect users to a different database.'
                  constraints:
                    nullable: false


  - changeSet:
      id: v55.2025-04-01T07:18:02
      author: johnswanson
      comment: Add self-referential foreign key `router_database_id` to metabase_database
      changes:
        - addColumn:
            tableName: metabase_database
            columns:
              - column:
                  name: router_database_id
                  type: int
                  remarks: The ID of the primary database for this mirror database.
                  constraints:
                    unique: false
                    nullable: true

  - changeSet:
      id: v55.2025-04-01T07:18:47
      author: johnswanson
      comment: add an index for `metabase_database.router_database_id`
      changes:
        - addUniqueConstraint:
            tableName: metabase_database
            constraintName: idx_unique_metabase_database_router_database_id_name
            columnNames: router_database_id, name

  - changeSet:
      id: v55.2025-04-01T07:18:52
      author: johnswanson
      comment: Add foreign key for `router_database_id`
      changes:
        - addForeignKeyConstraint:
            baseTableName: metabase_database
            baseColumnNames: router_database_id
            referencedTableName: metabase_database
            referencedColumnNames: id
            constraintName: fk_metabase_database_metabase_database_id
            onDelete: RESTRICT


  - changeSet:
      id: v55.2025-04-17T08:44:39
      author: johnswanson
      comment: Add permissions_group.magic_group_type
      changes:
        - addColumn:
            tableName: permissions_group
            columns:
              - column:
                  name: magic_group_type
                  type: varchar(254)
                  remarks: The magic_group_type of the permissions_group
                  constraints:
                    unique: true
                    nullable: true

  - changeSet:
      id: v55.2025-04-17T08:47:19
      author: johnswanson
      comment: Set type on existing permissions groups
      rollback: #
      changes:
        - sql:
            sql: |
              UPDATE permissions_group SET magic_group_type='all-internal-users' WHERE name='All Users';
              UPDATE permissions_group SET magic_group_type='admin' WHERE name='Administrators';

  - changeSet:
      id: v55.2025-04-22T05:42:48
      author: johnswanson
      comment: Add `permissions_group.is_tenant_group`
      changes:
        - addColumn:
            tableName: permissions_group
            columns:
              - column:
                  name: is_tenant_group
                  type: ${boolean.type}
                  defaultValueBoolean: false
                  remarks: "true iff this is a Tenant Group"
                  constraints:
                    nullable: false

  - changeSet:
      id: v55.2025-04-22T05:54:51
      author: johnswanson
      comment: Add `core_user.tenant_id`
      changes:
        - addColumn:
            tableName: core_user
            columns:
              - column:
                  name: tenant_id
                  type: int
                  remarks: The ID of the tenant for this user
                  constraints:
                    unique: false
                    nullable: true

  - changeSet:
      id: v55.2025-05-02T08:21:44
      author: lbrdnk
      comment: Migrate hacked semantic types
      rollback:
        - update:
            tableName: metabase_field
            # set columns to NULL
            columns:
              - column:
                  name: coercion_strategy
              - column:
                  name: effective_type
            where: coercion_strategy = 'Coercion/String->Float'
      changes:
        - update:
            tableName: metabase_field
            columns:
              - column:
                  name: coercion_strategy
                  value: 'Coercion/String->Float'
              - column:
                  name: effective_type
                  value: 'type/Float'
            where: |
              (
                select metabase_database.engine
                from metabase_table
                join metabase_database on metabase_table.db_id = metabase_database.id
                where metabase_field.table_id = metabase_table.id
              ) in (
                'mysql',
                'sqlite',
                'sqlserver',
                'snowflake',
                'h2',
                'oracle'
              )
              AND base_type = 'type/Text'
              AND semantic_type in (
                'type/Longitude',
                'type/Discount',
                'type/Currency',
                'type/Cost',
                'type/Quantity',
                'type/Duration',
                'type/Latitude',
                'type/Coordinate',
                'type/GrossMargin',
                'type/Percentage',
                'type/Share',
                'type/Price',
                'type/Income',
                'type/Score',
                'type/Number'
              )

  # Add a unique constraint on metabase_table(db_id, schema, name). Before, there was no constraint, so we need to
  # handle potential duplicates.
  # v55.2025-05-19T01:00:00 - Make metabase_table.name and schema case-sensitive for MySQL
  # v55.2025-05-19T02:00:00 - Add is_defective_duplicate, FALSE by default
  # v55.2025-05-19T03:00:00 - Compute is_defective_duplicate based on (db_id, schema, name) uniqueness. Active tables
  # take priority over inactive ones.
  # v55.2025-05-19T04:00:00 - Add unique_table_helper to create an index that ignores EXISTING duplicates. We need to
  # handle 3 cases - H2 doesn't support WHERE in indexes, metabase_table.schema is a nullable field and needs to
  # be coalesced to an empty string, ignore duplicate tables.
  # v55.2025-05-19T05:00:00 - Add a unique constraint (db_id, name, unique_table_helper)

  # This is necessary to make unique indexes using metabase_table.name and schema case-sensitive for MySQL.
  - changeSet:
      id: v55.2025-05-19T01:00:00
      validCheckSum: ANY
      author: ranquild
      dbms: mysql,mariadb
      comment: Make metabase_table.name and schema use case-sensitive collation for MySQL
      changes:
        - sql:
            sql: >-
              ALTER TABLE metabase_table MODIFY
              `name` varchar(254)
              CHARACTER SET utf8mb4
              COLLATE utf8mb4_bin;

              ALTER TABLE metabase_table MODIFY
              `schema` varchar(254)
              CHARACTER SET utf8mb4
              COLLATE utf8mb4_bin;
      rollback:
        - sql:
            sql: >-
              ALTER TABLE metabase_table MODIFY
              `name` VARCHAR(254)
              CHARACTER SET utf8mb4
              COLLATE utf8mb4_unicode_ci;

              ALTER TABLE metabase_table MODIFY
              `schema` varchar(254)
              CHARACTER SET utf8mb4
              COLLATE utf8mb4_unicode_ci;

  - changeSet:
      id: v55.2025-05-19T02:00:00
      validCheckSum: 9:85e9ad7b60db0cd795254ca52d6dd5a7
      author: ranquild
      comment: Add metabase_table.is_defective_duplicate
      changes:
        - addColumn:
            tableName: metabase_table
            columns:
              - column:
                  name: is_defective_duplicate
                  type: ${boolean.type}
                  remarks: "Indicates whether the table is a defective duplicate that should never have been created."
                  constraints:
                    nullable: false
                  defaultValue: false

  # metabase_table.schema is nullable
  - changeSet:
      id: v55.2025-05-19T03:00:00
      validCheckSum: 9:bece48e1dd30c59d4dae56346363f5b4
      author: ranquild
      comment: Compute metabase_table.is_defective_duplicate based on (db_id, schema, name) uniqueness
      changes:
        - sql:
            UPDATE metabase_table mt
            SET is_defective_duplicate = TRUE
            WHERE mt.id IN (
                SELECT id
                FROM (
                    SELECT
                        mt.id,
                        ROW_NUMBER() OVER (
                            PARTITION BY mt.db_id, COALESCE(mt.schema, ''), mt.name
                            ORDER BY
                                CASE WHEN mt.active THEN 0 ELSE 1 END,
                                mt.created_at
                        ) AS row_num
                    FROM metabase_table mt
                ) x
                WHERE x.row_num > 1
            );
      rollback:
        - sql:
            sql: >-
              UPDATE metabase_table
              SET is_defective_duplicate = FALSE;

  - changeSet:
      id: v55.2025-05-19T04:00:00
      validCheckSum: ANY
      author: ranquild
      comment: Add metabase_table.unique_table_helper to create an index that ignores EXISTING duplicates
      changes:
        - sql:
            dbms: postgresql
            sql: >-
              ALTER TABLE metabase_table ADD COLUMN unique_table_helper CHARACTER VARYING(254) GENERATED ALWAYS AS (
                CASE WHEN is_defective_duplicate = TRUE THEN NULL ELSE COALESCE(schema, '') END
              ) STORED;
        - sql:
            dbms: mysql,mariadb
            sql: >-
              ALTER TABLE metabase_table ADD COLUMN unique_table_helper VARCHAR(254) GENERATED ALWAYS AS (
                CASE WHEN is_defective_duplicate = TRUE THEN NULL ELSE COALESCE(`schema`, '') END
              ) STORED;
        - sql:
            dbms: h2
            sql: >-
              ALTER TABLE metabase_table ADD COLUMN unique_table_helper CHARACTER VARYING(254) GENERATED ALWAYS AS (
                CASE WHEN is_defective_duplicate = TRUE THEN NULL ELSE COALESCE(schema, '') END
              );
      rollback:
        - sql:
            sql: ALTER TABLE metabase_table DROP COLUMN unique_table_helper;

  - changeSet:
      id: v55.2025-05-19T05:00:00
      validCheckSum: 9:848d1cb748064b5de423139fbbbc2876
      author: ranquild
      comment: Add unique constraint on metabase_table(db_id, name, unique_table_helper)
      changes:
        - addUniqueConstraint:
            tableName: metabase_table
            constraintName: idx_unique_table
            columnNames: db_id, name, unique_table_helper
      rollback:
        - dropUniqueConstraint:
            tableName: metabase_table
            constraintName: idx_unique_table

  - changeSet:
      id: v55.2025-05-19T16:46:48
      author: edpaget
      comment: Add metabot table
      changes:
        - createTable:
            tableName: metabot
            remarks: Metabot configuration
            columns:
              - column:
                  name: id
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: name
                  type: varchar(254)
                  remarks: The name of the metabot
                  constraints:
                    nullable: false
              - column:
                  name: description
                  type: ${text.type}
                  remarks: Description of the metabot
                  constraints:
                    nullable: true
              - column:
                  name: entity_id
                  type: char(21)
                  remarks: Random NanoID tag for unique identity
                  constraints:
                    nullable: true
                    unique: true
              - column:
                  remarks: The timestamp of when the metabot was created
                  name: created_at
                  type: ${timestamp_type}
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false
              - column:
                  remarks: The timestamp of when the metabot was updated
                  name: updated_at
                  type: ${timestamp_type}
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false

  - changeSet:
      id: v55.2025-05-19T16:47:48
      author: edpaget
      comment: Add metabot entity table
      changes:
        - createTable:
            tableName: metabot_entity
            remarks: Entities associated with a metabot
            columns:
              - column:
                  name: id
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: metabot_id
                  type: int
                  remarks: The metabot this entity is associated with
                  constraints:
                    nullable: false
              - column:
                  name: model
                  type: varchar(32)
                  remarks: The type of model this entity references
                  constraints:
                    nullable: false
              - column:
                  name: model_id
                  type: int
                  remarks: The ID of the model this entity references
                  constraints:
                    nullable: false
              - column:
                  name: entity_id
                  type: char(21)
                  remarks: Random NanoID tag for unique identity
                  constraints:
                    nullable: true
                    unique: true
              - column:
                  remarks: The timestamp of when the entity was created
                  name: created_at
                  type: ${timestamp_type}
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false

  - changeSet:
      id: v55.2025-05-19T16:48:48
      author: edpaget
      comment: Add index on metabot_entity.metabot_id
      changes:
        - createIndex:
            tableName: metabot_entity
            indexName: idx_metabot_entity_metabot_id
            columns:
              - column:
                  name: metabot_id

  - changeSet:
      id: v55.2025-05-19T16:49:49
      author: edpaget
      comment: Add foreign key constraint on metabot_entity.metabot_id
      changes:
        - addForeignKeyConstraint:
            baseTableName: metabot_entity
            baseColumnNames: metabot_id
            referencedTableName: metabot
            referencedColumnNames: id
            constraintName: fk_metabot_entity_metabot_id
            onDelete: CASCADE

  - changeSet:
      id: v55.2025-05-19T16:50:49
      author: edpaget
      comment: Create the default metabot instances
      preConditions:
        - onFail: MARK_RAN
        - sqlCheck:
            expectedResult: 0
            sql: >-
              SELECT COUNT(*) FROM metabot WHERE entity_id IN ('metabotmetabotmetabot', 'embeddedmetabotmetabo');
      rollback:
        - sql:
            sql: >-
              DELETE FROM metabot WHERE entity_id IN ('metabotmetabotmetabot', 'embeddedmetabotmetabo');
      changes:
        - sql:
            sql: >-
              INSERT INTO metabot (
                  name
                  , description
                  , entity_id
                  , created_at
                  , updated_at
              ) VALUES (
                  'Metabot'
                  , 'Metabot instance for internal users.'
                  , 'metabotmetabotmetabot'
                  , now()
                  , now()
              );
              INSERT INTO metabot (
                  name
                  , description
                  , entity_id
                  , created_at
                  , updated_at
              ) VALUES (
                  'Embedded Metabot'
                  , 'Metabot instance for embedded metabase users.'
                  , 'embeddedmetabotmetabo'
                  , now()
                  , now()
              );

  - changeSet:
      id: v55.2025-05-20T10:00:00
      validCheckSum: 9:1ed306a6b2573b7b140275e5319fae2c
      author: ranquild
      comment: Drop metabase_database.entity_id
      changes:
        - dropColumn:
            tableName: metabase_database
            columnName: entity_id
      rollback:
        - addColumn:
            tableName: metabase_database
            columns:
              - column:
                  remarks: Random NanoID tag for unique identity.
                  name: entity_id
                  type: char(21)
                  constraints:
                    nullable: true
                    unique: true

  - changeSet:
      id: v55.2025-05-20T11:00:00
      validCheckSum: 9:b03020b86a754abc46edca465f91eb6f
      author: ranquild
      comment: Drop metabase_table.entity_id
      changes:
        - dropColumn:
            tableName: metabase_table
            columnName: entity_id
      rollback:
        - addColumn:
            tableName: metabase_table
            columns:
              - column:
                  remarks: Random NanoID tag for unique identity.
                  name: entity_id
                  type: char(21)
                  constraints:
                    nullable: true
                    unique: true

  - changeSet:
      id: v55.2025-05-20T12:00:00
      validCheckSum: 9:70285cb34c7e9e4dd25f322a46e21c04
      author: ranquild
      comment: Drop metabase_field.entity_id
      changes:
        - dropColumn:
            tableName: metabase_field
            columnName: entity_id
      rollback:
        - addColumn:
            tableName: metabase_field
            columns:
              - column:
                  remarks: Random NanoID tag for unique identity.
                  name: entity_id
                  type: char(21)
                  constraints:
                    nullable: true
                    unique: true

  - changeSet:
      id: v55.2025-06-03T16:52:38
      author: metamben
      comment: Add metabot prompt table
      changes:
        - createTable:
            tableName: metabot_prompt
            remarks: Prompts of a metabot entity
            columns:
              - column:
                  name: id
                  type: int
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: metabot_entity_id
                  type: int
                  remarks: The metabot this entity is associated with
                  constraints:
                    nullable: false
              - column:
                  name: model
                  type: varchar(32)
                  remarks: The type of the entity this prompt is about
                  constraints:
                    nullable: false
              - column:
                  name: card_id
                  type: int
                  remarks: The ID of the model or metric this prompt is about
                  constraints:
                    nullable: false
              - column:
                  name: entity_id
                  type: char(21)
                  remarks: Random NanoID tag for unique identity
                  constraints:
                    nullable: true
                    unique: true
              - column:
                  remarks: The text of the prompt
                  name: prompt
                  type: ${text.type}
                  constraints:
                    nullable: false
              - column:
                  remarks: The timestamp of when the prompt was created
                  name: created_at
                  type: ${timestamp_type}
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false
              - column:
                  remarks: The timestamp of when the prompt was updated
                  name: updated_at
                  type: ${timestamp_type}
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false

  - changeSet:
      id: v55.2025-06-03T16:52:48
      author: metamben
      comment: Add index on metabot_prompt.metabot_entity_id
      changes:
        - createIndex:
            tableName: metabot_prompt
            indexName: idx_metabot_prompt_metabot_entity_id
            columns:
              - column:
                  name: metabot_entity_id

  - changeSet:
      id: v55.2025-06-03T16:52:58
      author: metamben
      comment: Add foreign key constraint on metabot_prompt.metabot_entity_id
      changes:
        - addForeignKeyConstraint:
            baseTableName: metabot_prompt
            baseColumnNames: metabot_entity_id
            referencedTableName: metabot_entity
            referencedColumnNames: id
            constraintName: fk_metabot_prompt_metabot_entity_id
            onDelete: CASCADE

  - changeSet:
      id: v55.2025-06-03T16:53:08
      author: metamben
      comment: Add index on metabot_prompt.card_id
      changes:
        - createIndex:
            tableName: metabot_prompt
            indexName: idx_metabot_prompt_card_id
            columns:
              - column:
                  name: card_id

  - changeSet:
      id: v55.2025-06-03T16:53:18
      author: metamben
      comment: Add foreign key constraint on metabot_prompt.card_id
      changes:
        - addForeignKeyConstraint:
            baseTableName: metabot_prompt
            baseColumnNames: card_id
            referencedTableName: report_card
            referencedColumnNames: id
            constraintName: fk_metabot_prompt_card_id
            onDelete: CASCADE

  - changeSet:
      id: v55.2025-06-09T01:00:00
      author: metabase-dev
      comment: Add inline_parameters to report_dashboardcard for card-level parameter display
      changes:
        - addColumn:
            tableName: report_dashboardcard
            columns:
              - column:
                  name: inline_parameters
                  type: ${text.type}
                  remarks: JSON array of parameter IDs that should be displayed inline with this card
                  constraints:
                    nullable: true
      rollback:
        - dropColumn:
            tableName: report_dashboardcard
            columnName: inline_parameters

  - changeSet:
      id: v55.2025-06-16T17:36:06
      author: nvoxland
      comment: |
        In v55 we renamed the `metabase.app_db` namespace which changed checksums.
        The validCheckSum=ANY allows forward migration, but a rollback doesn't reset the checksums to the value old versions expect
      changes:
        - empty: #no-op on forward migration
      rollback:
        - sql:
            sql: >-
              update ${databasechangelog.name}
              set md5sum=null
              where id in (
                           'v46.00-080',
                           'v46.00-086',
                           'v47.00-016',
                           'v47.00-027',
                           'v47.00-028',
                           'v47.00-029',
                           'v47.00-033',
                           'v47.00-034',
                           'v47.00-043',
                           'v47.00-044',
                           'v47.00-045',
                           'v47.00-046',
                           'v48.00-001',
                           'v48.00-022',
                           'v48.00-023',
                           'v49.00-059',
                           'v49.2024-01-22T11:52:00',
                           'v49.2024-04-09T10:00:03',
                           'v50.2024-03-28T16:30:35',
                           'v50.2024-04-25T01:04:05',
                           'v50.2024-04-25T01:04:06',
                           'v50.2024-04-25T01:04:07',
                           'v50.2024-05-15T13:13:13',
                           'v50.2024-05-17T19:54:26',
                           'v50.2024-05-27T15:55:22',
                           'v50.2024-06-12T12:33:07',
                           'v51.2024-05-13T16:00:00',
                           'v51.2024-08-07T10:00:00',
                           'v51.2024-08-07T11:00:00',
                           'v52.2024-10-26T18:42:42',
                           'v52.2024-11-12T15:13:18',
                           'v52.2024-12-03T15:55:22',
                           'v54.2025-02-14T08:05:00'
                  );

  - changeSet:
      id: v55.2025-06-23T11:29:00
      author: bronsa
      comment: Added 0.55.0 -- add metabase_field_user_settings
      changes:
        - createTable:
            tableName: metabase_field_user_settings
            remarks: Mirror table of metabase_field to keep track of user-set values (only settable fields are mirrored)
            columns:
              - column:
                  remarks: The related Field
                  name: field_id
                  type: int
                  constraints:
                    primaryKey: true
                    nullable: false
                    referencedTableName: metabase_field
                    referencedColumnNames: id
                    foreignKeyName: fk_field_user_setting_field_id
                    deleteCascade: true
              - column:
                  name: created_at
                  remarks: The timestamp of when the user setting was created
                  type: ${timestamp_type}
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false
              - column:
                  name: updated_at
                  remarks: The timestamp of when the user setting was updated
                  type: ${timestamp_type}
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false
              - column:
                  remarks: User-set semantic_type for the Field
                  name: semantic_type
                  type: varchar(254)
              - column:
                  remarks: User-set description for the Field
                  name: description
                  type: longtext
              - column:
                  remarks: User-set display_name for the Field
                  name: display_name
                  type: varchar(254)
              - column:
                  remarks: User-set visibility_type for the Field
                  name: visibility_type
                  type: varchar(32)
              - column:
                  remarks: User-set fk_target_field_id for the Field
                  name: fk_target_field_id
                  type: int
              - column:
                  remarks: User-set has_field_values for the Field
                  name: has_field_values
                  type: longtext
              - column:
                  remarks: User-set effective_type for the Field
                  name: effective_type
                  type: varchar(255)
              - column:
                  remarks: User-set coercion_strategy for the Field
                  name: coercion_strategy
                  type: varchar(255)
              # the fields below are never updated by sync, but we keep them for completeness
              - column:
                  remarks: User-set caveats for the Field
                  name: caveats
                  type: longtext
              - column:
                  remarks: User-set points_of_interest for the Field
                  name: points_of_interest
                  type: longtext
              - column:
                  remarks: User-set nfc_path for the Field
                  name: nfc_path
                  type: varchar(254)
              - column:
                  remarks: User-set json_unfolding for the Field
                  name: json_unfolding
                  type: ${boolean.type}
              - column:
                  remarks: User-set settings for the Field
                  name: settings
                  type: longtext


  - changeSet:
      id: v55.2025-07-02T10:00:00
      author: ranquild
      comment: |
        Update `has_field_values` on FK fields to match PKs. Before this change, the FE always used the corresponding
        PKs fields for FKs fields in dashboards. Now the FE does not swap fields, and we need to set `has_field_values`
        to prevent any changes in behavior.
      changes:
        - sql:
            dbms: postgresql
            sql: >-
              UPDATE metabase_field AS fk
              SET has_field_values = pk.has_field_values
              FROM metabase_field AS pk
              WHERE
                pk.id = fk.fk_target_field_id AND
                pk.has_field_values IS NOT NULL AND
                pk.has_field_values <> fk.has_field_values AND
                fk.semantic_type = 'type/FK';
        - sql:
            dbms: mysql,mariadb
            sql: >-
              UPDATE metabase_field AS fk
              JOIN metabase_field AS pk ON pk.id = fk.fk_target_field_id
              SET fk.has_field_values = pk.has_field_values
              WHERE
                pk.has_field_values IS NOT NULL AND
                pk.has_field_values <> fk.has_field_values AND
                fk.semantic_type = 'type/FK';
        - sql:
            dbms: h2
            sql: >-
              UPDATE metabase_field AS fk
              SET has_field_values = (
                SELECT coalesce(pk.has_field_values, fk.has_field_values)
                FROM metabase_field AS pk
                WHERE pk.id = fk.fk_target_field_id
              )
              WHERE fk_target_field_id IS NOT NULL AND semantic_type = 'type/FK';
      rollback: # not necessary

  - changeSet:
      id: v55.2025-07-04T15:00:00
      author: qnkhuat
      comment: fix v_alerts where cron string contains slash (#60427)
      changes:
        - sqlFile:
            dbms: postgresql
            path: instance_analytics_views/alerts/v4/postgres-alerts.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: instance_analytics_views/alerts/v4/mysql-alerts.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: instance_analytics_views/alerts/v4/h2-alerts.sql
            relativeToChangelogFile: true
      rollback:
        - sqlFile:
            dbms: postgresql
            path: instance_analytics_views/alerts/v3/postgres-alerts.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: mysql,mariadb
            path: instance_analytics_views/alerts/v3/mysql-alerts.sql
            relativeToChangelogFile: true
        - sqlFile:
            dbms: h2
            path: instance_analytics_views/alerts/v3/h2-alerts.sql
            relativeToChangelogFile: true

  - changeSet:
      id: v55.2025-07-21T10:00:00
      author: ranquild
      comment: Remove semantic_type when base_type is type/Boolean and semantic_type is type/Category
      changes:
        - update:
            tableName: metabase_field
            columns:
              - column:
                  name: semantic_type
                  value: NULL
            where: base_type = 'type/Boolean' AND semantic_type = 'type/Category'
      rollback: # not necessary

  - changeSet:
      id: v55.2026-03-30T00:00:00
      author: bronsa
      comment: Create security_advisory table for Security Center
      preConditions:
        - onFail: MARK_RAN
        - not:
            - tableExists:
                tableName: security_advisory
      changes:
        - createTable:
            tableName: security_advisory
            remarks: Stores security advisories fetched from the advisory feed
            columns:
              - column:
                  name: id
                  type: int
                  remarks: Auto-incrementing primary key
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: advisory_id
                  type: varchar(255)
                  remarks: Unique advisory identifier (e.g. SC-2026-001)
                  constraints:
                    nullable: false
              - column:
                  name: severity
                  type: varchar(32)
                  remarks: "Severity level: critical, high, medium, or low"
                  constraints:
                    nullable: false
              - column:
                  name: title
                  type: varchar(255)
                  remarks: Human-readable advisory title
                  constraints:
                    nullable: false
              - column:
                  name: description
                  type: ${text.type}
                  remarks: Short summary of the advisory
                  constraints:
                    nullable: false
              - column:
                  name: advisory_url
                  type: varchar(2048)
                  remarks: Link to the full advisory
                  constraints:
                    nullable: true
              - column:
                  name: remediation
                  type: ${text.type}
                  remarks: Remediation instructions
                  constraints:
                    nullable: false
              - column:
                  name: affected_versions
                  type: ${text.type}
                  remarks: "JSON array of {min, fixed} version ranges"
                  constraints:
                    nullable: false
              - column:
                  name: matching_query
                  type: ${text.type}
                  remarks: JSON HoneySQL query keyed by dialect (null = affects all instances)
                  constraints:
                    nullable: true
              - column:
                  name: published_at
                  type: ${timestamp_type}
                  remarks: When the advisory was published
                  constraints:
                    nullable: false
              - column:
                  name: fetched_at
                  type: ${timestamp_type}
                  remarks: When Metabase fetched this advisory
                  defaultValueComputed: current_timestamp
                  constraints:
                    nullable: false
              - column:
                  name: match_status
                  type: varchar(32)
                  remarks: "Status: active, resolved, not_affected, or error"
                  constraints:
                    nullable: false
              - column:
                  name: last_evaluated_at
                  type: ${timestamp_type}
                  remarks: Last time the matching query was evaluated
                  constraints:
                    nullable: true
              - column:
                  name: acknowledged_by
                  type: int
                  remarks: FK to core_user.id — admin who acknowledged the advisory
                  constraints:
                    nullable: true
              - column:
                  name: acknowledged_at
                  type: ${timestamp_type}
                  remarks: When the advisory was acknowledged
                  constraints:
                    nullable: true
              - column:
                  name: last_notified_at
                  type: ${timestamp_type}
                  remarks: When the last notification was sent for this advisory
                  constraints:
                    nullable: true
              - column:
                  name: updated_at
                  type: ${timestamp_type}
                  remarks: When the advisory was last updated upstream (used as sync cursor)
                  constraints:
                    nullable: false

  - changeSet:
      id: v55.2026-03-30T00:00:01
      author: bronsa
      comment: Add unique constraint on security_advisory.advisory_id
      changes:
        - addUniqueConstraint:
            tableName: security_advisory
            constraintName: uq_security_advisory_advisory_id
            columnNames: advisory_id

  - changeSet:
      id: v55.2026-03-30T00:00:02
      author: bronsa
      comment: Add index on security_advisory.acknowledged_by FK
      preConditions:
        - onFail: MARK_RAN
        - not:
            - indexExists:
                indexName: idx_security_advisory_acknowledged_by
                tableName: security_advisory
      changes:
        - createIndex:
            tableName: security_advisory
            indexName: idx_security_advisory_acknowledged_by
            columns:
              - column:
                  name: acknowledged_by

  - changeSet:
      id: v55.2026-03-30T00:00:03
      author: bronsa
      comment: Add FK on security_advisory.acknowledged_by
      preConditions:
        - onFail: MARK_RAN
        - not:
            - foreignKeyConstraintExists:
                foreignKeyName: fk_security_advisory_acknowledged_by
                foreignKeyTableName: security_advisory
      changes:
        - addForeignKeyConstraint:
            baseTableName: security_advisory
            baseColumnNames: acknowledged_by
            referencedTableName: core_user
            referencedColumnNames: id
            constraintName: fk_security_advisory_acknowledged_by
            onDelete: SET NULL

  - changeSet:
      id: v55.2026-03-30T00:00:04
      author: bronsa
      comment: Add index on security_advisory.match_status
      preConditions:
        - onFail: MARK_RAN
        - not:
            - indexExists:
                indexName: idx_security_advisory_match_status
                tableName: security_advisory
      changes:
        - createIndex:
            tableName: security_advisory
            indexName: idx_security_advisory_match_status
            columns:
              - column:
                  name: match_status

  - changeSet:
      id: v55.2026-03-30T00:00:05
      author: egorgrushin
      comment: Add security_advisory.download_jar_urls for per-version download links
      preConditions:
        - onFail: MARK_RAN
        - not:
            - columnExists:
                tableName: security_advisory
                columnName: download_jar_urls
      changes:
        - addColumn:
            tableName: security_advisory
            columns:
              - column:
                  name: download_jar_urls
                  type: ${text.type}
                  remarks: "JSON array of {version, url} downloadable JARs"
                  constraints:
                    nullable: true

  # >>>>>>>>>> DO NOT ADD NEW MIGRATIONS BELOW THIS LINE! ADD THEM ABOVE <<<<<<<<<<

########################################################################################################################
#
# ADVICE:
#
# 1) Think through some of these points when writing a migration, learn from our past mistakes:
#    - Do you really need a migration? Could the feature work without it? Prefer not to if possible.
#      Data in the wild can be vastly different from what you expect, and it's hard to get right.
#    - Make sure your migration is backward compatible: it might not be possible to add a constraint back
#      if you drop it in a migration.
#    - Postgres, MySQL and H2 have their differences. Make sure your migration works for all.
#    - Database encryption is a major issue:
#      - Fields like `metabase_database.details` or `setting.value` can be encrypted, so you need to decrypt them in
#        your migration. See #42617, #44048.
#      - Database could be partially encrypted, see https://www.notion.so/72575933ef2a446bafd16909e05a7387
#    - Custom migrations:
#      - Prefer SQL migrations when possible.
#      - Never use application code: it can change and *will* break your migration.
#      - Do not use Toucan models - refer table names directly.
#      - If it's a big change, consider using Quartz, see #42279
#      - More in `metabase.app_db.custom_migrations` namespace doc.
#    - Never delete a migration: users won't be able to downgrade. If you really need to, see #44908
#    - Migration id (`vXX.<date>`) must match its earliest released version:
#      - Do not backport `v51....` to version 50, Metabase will try to downgrade it.
#      - Instead, write a migration with an oldest target you plan to backport to in mind.
#
# 2) Run ./bin/lint-migrations-file.sh to run core.spec checks against any changes you make here. Liquibase is pretty
#    forgiving and won't complain if you accidentally mix up things like deleteCascade and onDelete: CASCADE. CI runs
#    this check but it's nicer to know now instead of waiting for CI.
#
# 3) Migration IDs should follow the format
#
#    vMM.TIMESTAMP
#
#    Where
#
#    M         = major version
#    TIMESTAMP = the current timestamp with format `yyyy-MM-dd'T'HH:mm:ss`
#                To get this timestamp, evaluate this in your REPL: `(dev/migration-timestamp)`
#
#    E.g: You're adding a new migration for version 49, And it's 10:30:00AM on April 1, 2023 (UTC),
#    your migration id should be: `v49.2023-04-01T10:30:00`.
#
# PLEASE KEEP THIS MESSAGE AT THE BOTTOM OF THIS FILE!!!!! Add new migrations above the message.
#
########################################################################################################################