Skip to content

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

Archive deleted tables (#61592)

Nicola Mometto4c79e29ccad0
diff --git a/resources/migrations/056_update_migrations.yaml b/resources/migrations/056_update_migrations.yaml
index 0bc3f55561d..948a9ff90cd 100644
--- a/resources/migrations/056_update_migrations.yaml
+++ b/resources/migrations/056_update_migrations.yaml
@@ -235,6 +235,144 @@ databaseChangeLog:
SET login_attributes = jwt_attributes
WHERE sso_source = 'jwt';
+ - changeSet:
+ id: v56.2025-07-30T10:35:00
+ author: bronsa
+ comment: Add deactivated_at column to metabase_table
+ preConditions:
+ - onFail: MARK_RAN
+ - not:
+ - columnExists:
+ tableName: metabase_table
+ columnName: deactivated_at
+ changes:
+ - addColumn:
+ tableName: metabase_table
+ columns:
+ - column:
+ name: deactivated_at
+ type: ${timestamp_type}
+ remarks: The timestamp when the table was deactivated (active changed from true to false)
+ constraints:
+ nullable: true
+
+ - changeSet:
+ id: v56.2025-07-30T10:35:01
+ author: bronsa
+ comment: Add archived_at column to metabase_table
+ preConditions:
+ - onFail: MARK_RAN
+ - not:
+ - columnExists:
+ tableName: metabase_table
+ columnName: archived_at
+ changes:
+ - addColumn:
+ tableName: metabase_table
+ columns:
+ - column:
+ name: archived_at
+ type: ${timestamp_type}
+ remarks: The timestamp when the table was marked for archiving
+ constraints:
+ nullable: true
+
+ - changeSet:
+ id: v56.2025-07-30T10:41:00
+ author: bronsa
+ comment: Add composite index on metabase_table for unarchived deactivated tables by db_id (PostgreSQL)
+ dbms: postgresql
+ preConditions:
+ - onFail: MARK_RAN
+ - not:
+ - indexExists:
+ tableName: metabase_table
+ indexName: idx_metabase_table_db_deactivated
+ changes:
+ - sql:
+ sql: >-
+ CREATE INDEX idx_metabase_table_db_deactivated
+ ON metabase_table (db_id, deactivated_at)
+ WHERE active = false AND archived_at IS NULL AND deactivated_at IS NOT NULL;
+ rollback:
+ - dropIndex:
+ tableName: metabase_table
+ indexName: idx_metabase_table_db_deactivated
+
+ - changeSet:
+ id: v56.2025-07-30T10:43:00
+ author: bronsa
+ comment: Backfill deactivated_at for existing inactive tables
+ changes:
+ - sql:
+ sql: >-
+ UPDATE metabase_table
+ SET deactivated_at = updated_at
+ WHERE active = false
+ AND deactivated_at IS NULL;
+ rollback:
+ - sql:
+ sql: >-
+ UPDATE metabase_table
+ SET deactivated_at = NULL;
+
+ - changeSet:
+ id: v56.2025-08-01T11:11:00
+ author: bronsa
+ comment: Migration to allow rollbacking of archived tables when possible
+ changes:
+ - empty: #no-op on forward migration
+ rollback:
+ - sql:
+ dbms: postgresql
+ sql: >-
+ UPDATE metabase_table
+ SET
+ name = REGEXP_REPLACE(name, '__mbarchiv__\d+$', ''),
+ archived_at = NULL
+ WHERE archived_at IS NOT NULL
+ AND active = false
+ AND name ~ '__mbarchiv__\d+$'
+ AND NOT EXISTS (
+ SELECT 1 FROM metabase_table mt2
+ WHERE mt2.db_id = metabase_table.db_id
+ AND mt2.schema IS NOT DISTINCT FROM metabase_table.schema
+ AND mt2.name = REGEXP_REPLACE(metabase_table.name, '__mbarchiv__\d+$', '')
+ AND mt2.id != metabase_table.id);
+ - sql:
+ dbms: mysql,mariadb
+ sql: >-
+ UPDATE metabase_table mt1
+ LEFT JOIN metabase_table mt2 ON (
+ mt2.db_id = mt1.db_id
+ AND (mt2.schema = mt1.schema OR (mt2.schema IS NULL AND mt1.schema IS NULL))
+ AND mt2.name = SUBSTRING(mt1.name, 1, POSITION('__mbarchiv__' IN mt1.name) - 1)
+ AND mt2.id != mt1.id
+ )
+ SET
+ mt1.name = SUBSTRING(mt1.name, 1, POSITION('__mbarchiv__' IN mt1.name) - 1),
+ mt1.archived_at = NULL
+ WHERE mt1.archived_at IS NOT NULL
+ AND mt1.active = false
+ AND mt1.name LIKE '%__mbarchiv__%'
+ AND mt2.id IS NULL;
+ - sql:
+ dbms: h2
+ sql: >-
+ UPDATE metabase_table
+ SET
+ name = SUBSTRING(name, 1, POSITION('__mbarchiv__' IN name) - 1),
+ archived_at = NULL
+ WHERE archived_at IS NOT NULL
+ AND active = false
+ AND name LIKE '%__mbarchiv__%'
+ AND NOT EXISTS (
+ SELECT 1 FROM metabase_table mt2
+ WHERE mt2.db_id = metabase_table.db_id
+ AND (mt2.schema = metabase_table.schema OR (mt2.schema IS NULL AND metabase_table.schema IS NULL))
+ AND mt2.name = SUBSTRING(metabase_table.name, 1, POSITION('__mbarchiv__' IN metabase_table.name) - 1)
+ AND mt2.id != metabase_table.id);
+
# >>>>>>>>>> DO NOT ADD NEW MIGRATIONS BELOW THIS LINE! ADD THEM ABOVE <<<<<<<<<<
########################################################################################################################
diff --git a/src/metabase/sync/sync_metadata/tables.clj b/src/metabase/sync/sync_metadata/tables.clj
index 491dc895926..d54f0eb361d 100644
--- a/src/metabase/sync/sync_metadata/tables.clj
+++ b/src/metabase/sync/sync_metadata/tables.clj
@@ -3,7 +3,9 @@
(:require
[clojure.data :as data]
[clojure.set :as set]
+ [java-time.api :as t]
[medley.core :as m]
+ [metabase.app-db.core :as mdb]
[metabase.driver :as driver]
[metabase.driver.util :as driver.u]
[metabase.lib.schema.common :as lib.schema.common]
@@ -20,6 +22,8 @@
[metabase.util.malli.schema :as ms]
[toucan2.core :as t2]))
+(set! *warn-on-reflection* true)
+
;;; ------------------------------------------------ "Crufty" Tables -------------------------------------------------
;; Crufty tables are ones we know are from frameworks like Rails or Django and thus automatically mark as `:cruft`
@@ -268,6 +272,56 @@
:schema schema
{:schema new-schema})))
+(def ^:private
+ ^{:doc "threshold after which deactivated tables will be archived"}
+ archive-tables-threshold [-14 :day])
+
+(defn- archive-tables!
+ "Mark tables that have been deactivated for longer than the configured threshold as archived
+ and suffixes their names."
+ [database]
+ (let [;; we use UTC offset time for suffix, may not match db time but
+ ;; it doesn't matter much, the source of time truth is `archived_at`,
+ ;; we're just using this as a cheap namespace
+ suffix (str "__mbarchiv__" (.toEpochSecond (t/offset-date-time)))
+ threshold-expr (apply
+ (requiring-resolve 'metabase.driver.sql.query-processor/add-interval-honeysql-form)
+ (mdb/db-type) :%now archive-tables-threshold)
+ tables-to-archive (t2/select :model/Table
+ :db_id (u/the-id database)
+ :active false
+ :archived_at nil
+ :deactivated_at [:< threshold-expr])
+ archived (atom 0)]
+ (doseq [table tables-to-archive
+ :let [new-name (str (:name table) suffix)]]
+
+ (if (> (count new-name) 256)
+ (log/warnf "Cannot archive table %s, name too long" (:name table))
+ (do
+ (log/infof "Archiving table %s (deactivated at %s, new-name %s)"
+ (sync-util/name-for-logging table)
+ (:deactivated_at table)
+ new-name)
+ (let [[did-update err]
+ (try
+ ;; in the extremely unlikely case that there already exists a table with our
+ ;; archived name, we let it fail from hitting the unique constraints violation
+ ;; and just report the failure
+ [(t2/update! :model/Table
+ {:id (:id table)
+ :active false}
+ {:archived_at (mi/now)
+ :name new-name})]
+ (catch Throwable t
+ [0 t]))]
+ (when (zero? did-update)
+ (if err
+ (log/errorf err "Failed archiving table %s" (sync-util/name-for-logging table))
+ (log/warnf "Did not archive table %s" (sync-util/name-for-logging table))))
+ (swap! archived + did-update)))))
+ @archived))
+
(mu/defn sync-tables-and-database!
"Sync the Tables recorded in the Metabase application database with the ones obtained by calling `database`'s driver's
implementation of `describe-database`.
@@ -319,5 +373,9 @@
;; we need to fetch the tables again because we might have retired tables in the previous steps
(update-tables-metadata-if-needed! db-table-metadatas (db->our-metadata database) database))
- {:updated-tables (+ (count new-table-metadatas) (count old-table-metadatas))
- :total-tables (count our-metadata)})))
+ (let [archived-tables (sync-util/with-error-handling (format "Error archiving tables for %s"
+ (sync-util/name-for-logging database))
+ (archive-tables! database))]
+
+ {:updated-tables (+ (count new-table-metadatas) (count old-table-metadatas) (or archived-tables 0))
+ :total-tables (count our-metadata)}))))
diff --git a/src/metabase/warehouse_schema/models/table.clj b/src/metabase/warehouse_schema/models/table.clj
index e49829de03c..e22973cc6b2 100644
--- a/src/metabase/warehouse_schema/models/table.clj
+++ b/src/metabase/warehouse_schema/models/table.clj
@@ -70,6 +70,25 @@
;; foreign key constraints in generated columns. #44866
(t2/delete! :model/Field :table_id (:id table)))
+(t2/define-before-update :model/Table
+ [table]
+ (let [changes (t2/changes table)
+ original-table (t2/original table)
+ current-active (:active original-table)
+ new-active (:active changes)]
+ (cond
+ ;; active: true -> false (table being deactivated)
+ (and (true? current-active) (false? new-active))
+ (assoc changes :deactivated_at (mi/now))
+
+ ;; active: false -> true (table being reactivated)
+ (and (false? current-active) (true? new-active))
+ (assoc changes
+ :deactivated_at nil
+ :archived_at nil)
+
+ :else table)))
+
(defn- set-new-table-permissions!
[table]
(t2/with-transaction [_conn]
@@ -301,6 +320,8 @@
:database_require_filter :is_defective_duplicate :unique_table_helper]
:skip [:estimated_row_count :view_count]
:transform {:created_at (serdes/date)
+ :archived_at (serdes/date)
+ :deactivated_at (serdes/date)
:db_id (serdes/fk :model/Database :name)}})
(defmethod serdes/storage-path "Table" [table _ctx]
diff --git a/test/metabase/sync/sync_metadata/tables_test.clj b/test/metabase/sync/sync_metadata/tables_test.clj
index 701dee671e8..25389855442 100644
--- a/test/metabase/sync/sync_metadata/tables_test.clj
+++ b/test/metabase/sync/sync_metadata/tables_test.clj
@@ -2,7 +2,9 @@
"Test for the logic that syncs Table models with the metadata fetched from a DB."
(:require
[clojure.java.jdbc :as jdbc]
+ [clojure.string :as str]
[clojure.test :refer :all]
+ [java-time.api :as t]
[metabase.driver :as driver]
[metabase.driver.sql-jdbc.connection :as sql-jdbc.conn]
[metabase.driver.sql-jdbc.execute :as sql-jdbc.execute]
@@ -159,3 +161,98 @@
(is (= #{["employees" :cruft]
["transactions" nil]}
(t2/select-fn-set (juxt :name :visibility_type) :model/Table :db_id (u/the-id db))))))))
+
+(deftest archive-tables-test
+ (testing "Tables deactivated for more than 14 days should be archived"
+ (mt/with-temp [:model/Database db {}
+ :model/Table table-1 {:name "old_table"
+ :db_id (u/the-id db)
+ :active false
+ :deactivated_at (t/minus (t/offset-date-time) (t/days 15))}
+ :model/Table table-2 {:name "recent_table"
+ :db_id (u/the-id db)
+ :active false
+ :deactivated_at (t/minus (t/offset-date-time) (t/days 7))}
+ :model/Table table-3 {:name "active_table"
+ :db_id (u/the-id db)
+ :active true}]
+ (#'sync-tables/archive-tables! db)
+
+ (testing "Old deactivated table is archived with suffix"
+ (let [archived-table (t2/select-one :model/Table (:id table-1))]
+ (is (some? (:archived_at archived-table)))
+ (is (str/starts-with? (:name archived-table) "old_table__mbarchiv__"))))
+
+ (testing "Recently deactivated table is not archived"
+ (let [recent-table (t2/select-one :model/Table (:id table-2))]
+ (is (nil? (:archived_at recent-table)))
+ (is (= "recent_table" (:name recent-table)))))
+
+ (testing "Active table is not affected"
+ (let [active-table (t2/select-one :model/Table (:id table-3))]
+ (is (nil? (:archived_at active-table)))
+ (is (= "active_table" (:name active-table)))
+ (is (true? (:active active-table))))))))
+
+(deftest archive-tables-already-archived-test
+ (testing "Already archived tables should not be processed again"
+ (mt/with-temp [:model/Database db {}
+ :model/Table table {:name "already_archived"
+ :db_id (u/the-id db)
+ :active false
+ :deactivated_at (t/minus (t/offset-date-time) (t/days 20))
+ :archived_at (t/minus (t/offset-date-time) (t/days 5))}]
+ (let [original-name (:name table)
+ original-archived-at (:archived_at table)]
+ (#'sync-tables/archive-tables! db)
+
+ (let [updated-table (t2/select-one :model/Table (:id table))]
+ (is (= original-name (:name updated-table)))
+ (is (= original-archived-at (:archived_at updated-table))))))))
+
+(deftest deactivated-at-timestamp-test
+ (testing "deactivated_at is set when table becomes inactive"
+ (mt/with-temp [:model/Database db {}
+ :model/Table table {:name "test_table"
+ :db_id (u/the-id db)
+ :active true}]
+ (testing "Initially active table has no deactivated_at"
+ (is (nil? (:deactivated_at (t2/select-one :model/Table (:id table))))))
+
+ (testing "Setting active to false sets deactivated_at"
+ (t2/update! :model/Table (:id table) {:active false})
+ (let [updated-table (t2/select-one :model/Table (:id table))]
+ (is (some? (:deactivated_at updated-table)))
+ (is (false? (:active updated-table)))))
+
+ (testing "Reactivating table clears deactivated_at and archived_at"
+ (t2/update! :model/Table (:id table) {:archived_at (t/offset-date-time)})
+
+ (t2/update! :model/Table (:id table) {:active true})
+ (let [reactivated-table (t2/select-one :model/Table (:id table))]
+ (is (nil? (:deactivated_at reactivated-table)))
+ (is (nil? (:archived_at reactivated-table)))
+ (is (true? (:active reactivated-table))))))))
+
+(deftest archive-tables-permissions-security-test
+ (testing "Archival prevents permission inheritance on table recreation"
+ (mt/with-temp [:model/Database db {}
+ :model/Table original-table {:name "sensitive_table"
+ :db_id (u/the-id db)
+ :active false
+ :deactivated_at (t/minus (t/offset-date-time) (t/days 20))}]
+ (#'sync-tables/archive-tables! db)
+
+ (testing "the original table was archived and renamed"
+ (let [archived-table (t2/select-one :model/Table (:id original-table))]
+ (is (some? (:archived_at archived-table)))
+ (is (str/starts-with? (:name archived-table) "sensitive_table__mbarchiv__"))))
+
+ (mt/with-temp [:model/Table new-table {:name "sensitive_table"
+ :db_id (u/the-id db)
+ :active true}]
+
+ (testing "the new table should be treated as completely separate"
+ (is (not= (:id original-table) (:id new-table)))
+ (is (= "sensitive_table" (:name new-table)))
+ (is (nil? (:archived_at new-table))))))))
diff --git a/test/metabase/sync/sync_test.clj b/test/metabase/sync/sync_test.clj
index f74cfbed34a..b7687c06133 100644
--- a/test/metabase/sync/sync_test.clj
+++ b/test/metabase/sync/sync_test.clj
@@ -123,6 +123,8 @@
:db_id true
:entity_type :entity/GenericTable
:id true
+ :archived_at false
+ :deactivated_at false
:updated_at true}))
(defn- field-defaults []
diff --git a/test_resources/serialization_baseline/databases/My Database/tables/Schemaless Table/Schemaless Table.yaml b/test_resources/serialization_baseline/databases/My Database/tables/Schemaless Table/Schemaless Table.yaml
index db3136cce55..74b63a7e08b 100644
--- a/test_resources/serialization_baseline/databases/My Database/tables/Schemaless Table/Schemaless Table.yaml
+++ b/test_resources/serialization_baseline/databases/My Database/tables/Schemaless Table/Schemaless Table.yaml
@@ -18,4 +18,6 @@ serdes/meta:
model: Database
- id: Schemaless Table
model: Table
+archived_at: null
database_require_filter: null
+deactivated_at: null
diff --git a/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/CATEGORIES/CATEGORIES.yaml b/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/CATEGORIES/CATEGORIES.yaml
index a96ba52f904..b94ad7015a8 100644
--- a/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/CATEGORIES/CATEGORIES.yaml
+++ b/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/CATEGORIES/CATEGORIES.yaml
@@ -20,4 +20,6 @@ serdes/meta:
model: Schema
- id: CATEGORIES
model: Table
+archived_at: null
database_require_filter: null
+deactivated_at: null
diff --git a/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/CHECKINS/CHECKINS.yaml b/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/CHECKINS/CHECKINS.yaml
index d9c9fb3b621..8053e917195 100644
--- a/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/CHECKINS/CHECKINS.yaml
+++ b/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/CHECKINS/CHECKINS.yaml
@@ -20,4 +20,6 @@ serdes/meta:
model: Schema
- id: CHECKINS
model: Table
+archived_at: null
database_require_filter: null
+deactivated_at: null
diff --git a/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/ORDERS/ORDERS.yaml b/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/ORDERS/ORDERS.yaml
index 5608a60211c..d192e78bacb 100644
--- a/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/ORDERS/ORDERS.yaml
+++ b/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/ORDERS/ORDERS.yaml
@@ -20,4 +20,6 @@ serdes/meta:
model: Schema
- id: ORDERS
model: Table
+archived_at: null
database_require_filter: null
+deactivated_at: null
diff --git a/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/PEOPLE/PEOPLE.yaml b/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/PEOPLE/PEOPLE.yaml
index 390780b02cd..78f8743d840 100644
--- a/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/PEOPLE/PEOPLE.yaml
+++ b/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/PEOPLE/PEOPLE.yaml
@@ -20,4 +20,6 @@ serdes/meta:
model: Schema
- id: PEOPLE
model: Table
+archived_at: null
database_require_filter: null
+deactivated_at: null
diff --git a/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/PRODUCTS/PRODUCTS.yaml b/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/PRODUCTS/PRODUCTS.yaml
index 667388f2535..0e3efc05552 100644
--- a/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/PRODUCTS/PRODUCTS.yaml
+++ b/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/PRODUCTS/PRODUCTS.yaml
@@ -20,4 +20,6 @@ serdes/meta:
model: Schema
- id: PRODUCTS
model: Table
+archived_at: null
database_require_filter: null
+deactivated_at: null
diff --git a/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/REVIEWS/REVIEWS.yaml b/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/REVIEWS/REVIEWS.yaml
index 72726eecf89..924563abec2 100644
--- a/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/REVIEWS/REVIEWS.yaml
+++ b/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/REVIEWS/REVIEWS.yaml
@@ -20,4 +20,6 @@ serdes/meta:
model: Schema
- id: REVIEWS
model: Table
+archived_at: null
database_require_filter: null
+deactivated_at: null
diff --git a/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/USERS/USERS.yaml b/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/USERS/USERS.yaml
index dac2a228c5f..a57ded6ec29 100644
--- a/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/USERS/USERS.yaml
+++ b/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/USERS/USERS.yaml
@@ -20,4 +20,6 @@ serdes/meta:
model: Schema
- id: USERS
model: Table
+archived_at: null
database_require_filter: null
+deactivated_at: null
diff --git a/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/VENUES/VENUES.yaml b/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/VENUES/VENUES.yaml
index e5bead5536c..b6beb8236af 100644
--- a/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/VENUES/VENUES.yaml
+++ b/test_resources/serialization_baseline/databases/test-data (h2)/schemas/PUBLIC/tables/VENUES/VENUES.yaml
@@ -20,4 +20,6 @@ serdes/meta:
model: Schema
- id: VENUES
model: Table
+archived_at: null
database_require_filter: null
+deactivated_at: null