The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
(ns lint-migrations-file
"This is cljc because it is used from both Clojure (:clj) and Babashka (:bb). Not cljs!"
;; kondo also lints cljc as cljs, where the :bb/:clj conditional below hides the only io usage
#_{:clj-kondo/ignore [:unused-alias :unused-namespace]}
(:require
[change-set.strict]
[clj-yaml.core :as yaml]
[clojure.java.io :as io]
[clojure.pprint :as pprint]
[clojure.set :as set]
[clojure.spec.alpha :as s]
[clojure.string :as str])
(:import
(clojure.lang ExceptionInfo)
(java.lang Integer)))
;; kondo also lints a :cljs branch where this doesn't resolve; the file is :clj + :bb only
#_{:clj-kondo/ignore [:unresolved-symbol]}
(set! *warn-on-reflection* true)
(comment change-set.strict/keep-me)
(defmacro validation-error
"An exception with `::validation-error` in the data, for easy id later."
[msg & [data]]
`(ex-info ~msg (merge ~data {::validation-error true})))
(defn- validation-error? [e]
(::validation-error (ex-data e)))
#?(:bb ::no-op
:clj ;; just print ordered maps like normal maps.
(defmethod print-method flatland.ordered.map.OrderedMap
[m writer]
(print-method (into {} m) writer)))
(defn- require-database-change-log! [migrations]
(when-not (contains? migrations :databaseChangeLog)
(throw (validation-error "Missing `databaseChangeLog` key."))))
(defn- change-set-ids
"Returns all the change set ids given a change-log."
[change-log]
(for [{{id :id} :changeSet} change-log
:when id]
id))
(defn- require-distinct-change-set-ids [change-log]
(let [ids (change-set-ids change-log)
duplicates (->> ids
(group-by identity)
(keep (fn [[k v]]
(when (< 1 (count v))
k))))]
(when (seq duplicates)
(throw (validation-error "Change set IDs are not distinct." {:duplicates duplicates})))))
(defn- directory-based-migration-file?
"Returns true if the file is a directory-based migration file. This covers both the version-numbered directories
(e.g., `060/20260905_mq_indexes.yaml`) and the newer year-based directories (e.g., `2026/20260905_workspaces.yaml`)."
[file]
(boolean (re-matches #".*(\d{3}|\d{4})/\d{8}_[a-z0-9_]+\.yaml$" (str file))))
(defn- year-dir-migration-file?
"Returns true if the file lives in a year-based migration directory (e.g., `2026/20260905_workspaces.yaml`). Unlike
version-numbered directories, year directories are not tied to a Metabase version: their changeset IDs are
version-less and the version a changeset ships with is decided by which branch it is merged into."
[file]
(boolean (re-find #"[/\\]\d{4}[/\\]\d{8}_[a-z0-9_]+\.yaml$" (str file))))
(defn- file-version
"Extracts the migration version number from a file.
For per-release files like `059_update_migrations.yaml`, parses from the filename.
For directory-based files like `060/20260106_125531.yaml`, parses from the parent directory name."
[^java.io.File file]
(if (directory-based-migration-file? file)
(parse-long (re-find #"\d+" (.getName (.getParentFile file))))
(parse-long (re-find #"\d+" (.getName file)))))
(defn- changeset-version+id
"Returns [version local-id] for a changeset.
Parses from the ID itself, which should be of the form 'v{version}.{local-id}'."
[_file changeset-id]
(let [id-str (str changeset-id)]
(when-let [[_ version local-id] (re-matches #"^v(\d+)\.(.+)$" id-str)]
[(parse-long version) local-id])))
(defn- changeset-at-or-after?
"Returns true if the changeset (identified by file context and changeset ID) is at or after
the given [threshold-version threshold-id]."
[file changeset-id threshold-version threshold-id]
(when-let [[v local-id] (changeset-version+id file changeset-id)]
(or (> v threshold-version)
(and (= v threshold-version)
(not (neg? (compare local-id threshold-id)))))))
(defn- require-change-set-ids-in-order [change-log file]
(when-not (directory-based-migration-file? file)
(let [ids (change-set-ids change-log)
out-of-order-ids (->> ids
(partition 2 1)
(filter (fn [[id1 id2]]
(pos? (compare id1 id2)))))]
(when (seq out-of-order-ids)
(throw (validation-error "Change set IDs are not in order"
{:out-of-order-ids out-of-order-ids}))))))
(defn- require-change-set-ids-in-correct-file [change-log file]
;; year-based directories are not tied to a version, so their version-less IDs are not bound to any file version.
(when-not (year-dir-migration-file? file)
(let [fv (file-version file)
ids (change-set-ids change-log)
wrong-file-ids
(->> ids
(filter (fn [id]
;; a version-less id has no digits, so no version, and belongs in no versioned file
(let [id-version (some-> (re-find #"\d+" id) parse-long)]
(if (= fv 1)
(some-> id-version (> 55))
(not= fv id-version))))))]
(when (seq wrong-file-ids)
(throw (validation-error "Change set IDs are in the wrong file"
{:wrong-file-ids wrong-file-ids}))))))
(defn- check-change-use-types?
"Return `true` if change use any type in `types`."
[types change]
{:pre [(set? types)]}
(let [match-target-types? (fn [ttype]
(contains? types (str/lower-case ttype)))]
(cond
;; a createTable or addColumn change; see if it adds a target-type col
(or (:createTable change) (:addColumn change))
(let [op (cond (:createTable change) :createTable (:addColumn change) :addColumn)]
(some (fn [col-def]
(match-target-types? (get-in col-def [:column :type] "")))
(get-in change [op :columns])))
;; a modifyDataType change; see if it change a column to target-type
(and (:modifyDataType change)
(match-target-types? (get-in change [:modifyDataType :newDataType] "")))
true)))
(defn- check-change-set-use-types?
"Return true if `change-set` doesn't contain usage of any type in `types`."
[target-types change-set]
(some #(check-change-use-types? target-types %) (get-in change-set [:changeSet :changes])))
(defn- require-no-types-in-change-log!
"Throws if any changeset at or after [version id] uses a type in target-types.
When version and id are not provided, checks all changesets."
([target-types change-log]
(require-no-types-in-change-log! target-types change-log nil nil nil))
([target-types change-log file version id]
{:pre [(set? target-types)]}
(when-let [using-types? (->> change-log
(filter (fn [change-set]
(let [cs-id (get-in change-set [:changeSet :id])]
(and cs-id
(if version
;; year-dir changesets have version-less ids that
;; `changeset-at-or-after?` cannot parse, but they are by
;; definition newer than every `vNN.` threshold
(or (year-dir-migration-file? file)
(changeset-at-or-after? file cs-id version id))
true)))))
(filter #(check-change-set-use-types? target-types %))
(map #(get-in % [:changeSet :id]))
seq)]
(throw (validation-error
;; false unresolved-symbol from kondo's :cljs pass; this cljc is :clj+:bb only
#_{:clj-kondo/ignore [:unresolved-symbol]}
(format "Migration(s) [%s] uses invalid types (in %s)"
(str/join "," (map #(str "'" % "'") using-types?))
(str/join "," (map #(str "'" % "'") target-types)))
{:invalid-ids using-types?
:target-types target-types})))))
(defn require-no-bare-blob-or-text-types
"Ensures that no \"text\" or \"blob\" type columns are added in any changesets."
[change-log]
(require-no-types-in-change-log! #{"blob" "text"} change-log))
(defn require-no-bare-boolean-types
"Ensures that no \"boolean\" type columns are added in changesets with id later than v49.00-032. From that point on,
\"${boolean.type}\" should be used instead, so that we can consistently use `BIT(1)` for Boolean columns on MySQL."
[change-log file]
(require-no-types-in-change-log! #{"boolean"} change-log file 49 "00-032"))
(defn require-no-datetime-type
"Ensures that no \"datetime\" or \"timestamp without time zone\".
From that point on, \"${timestamp_type}\" should be used instead, so that all of our time related columns are tz-aware."
[change-log file]
(require-no-types-in-change-log!
#{"datetime" "timestamp" "timestamp without time zone"}
change-log file 49 "00-000"))
(defn- bare-entity-id-type-changes
"The changes of `change-set` that give an `entity_id` column the bare `char(21)` type instead of `${entity_id.type}`."
[change-set]
(let [bare? #(= "char(21)" (some-> % str/lower-case str/trim))
bare-col? (fn [col] (and (= "entity_id" (get-in col [:column :name])) (bare? (get-in col [:column :type]))))]
(filter (fn [change]
(or (some bare-col? (get-in change [:createTable :columns]))
(some bare-col? (get-in change [:addColumn :columns]))
(and (= "entity_id" (get-in change [:addNotNullConstraint :columnName]))
(bare? (get-in change [:addNotNullConstraint :columnDataType])))
(and (= "entity_id" (get-in change [:modifyDataType :columnName]))
(bare? (get-in change [:modifyDataType :newDataType])))))
(get-in change-set [:changeSet :changes]))))
(defn require-entity-id-type
"Ensures that directory-based migration files from `20261019_` on give `entity_id` columns the `${entity_id.type}`
type, which carries the byte-wise collation serialization relies on to order entities alike on every app DB."
[change-log ^java.io.File file]
(when-let [bad-ids (when (and (directory-based-migration-file? file)
(not (neg? (compare (subs (.getName file) 0 8) "20261019"))))
(->> change-log
(filter (comp seq bare-entity-id-type-changes))
(map #(get-in % [:changeSet :id]))
seq))]
(throw (validation-error
(str "Migration(s) [" (str/join "," (map #(str "'" % "'") bad-ids))
"] give entity_id the bare char(21) type; use ${entity_id.type}")
{:invalid-ids (vec bad-ids)}))))
(def ^:private directory-based-id-format-re
"For directory-based migration files (v60+), IDs must be prefixed with the correct version.
E.g., `v60.my-migration-name` or `v60.1`"
#"^v\d{2,}\..+$")
(defn valid-version-less-id?
"Whether `id` is a valid version-less changeset ID: lowercase letters/digits/underscores, at least one letter, and no
leading `v`. Binaries from before version-less support read the schema's major from the highest `id LIKE 'v%'` and
roll back by the number in those ids, so a `view_metrics` id would sort above every `vNN.` id there and break both."
[id]
(boolean (and (string? id)
(re-matches #"[a-z0-9_]+" id)
(re-find #"[a-z]" id)
(not (str/starts-with? id "v")))))
(defn- require-change-set-ids-match-file-format
"Enforces that changeset IDs use the correct format for the file type:
- Directory-based files (v60+): IDs must be prefixed with v{version}. (e.g., v60.anything)
- 001_update_migrations.yaml: any string ID is allowed (legacy file)
- Other per-release files: IDs must match the timestamp format"
[change-log file]
(cond
;; year-based directories use version-less IDs (e.g. `aeiagus09e`): lowercase letters/digits/underscores with at
;; least one letter, and no leading `v`. This keeps out timestamp-style IDs (`2026-02-09T12:00:00`) and
;; version-prefixed IDs (`v60.aeiagus09e`, `v60abc`) -- the version must not be encoded in the ID -- and all-digit
;; IDs (`20260703`), which `decide-liquibase-file` would mistake for a pre-4.2 changeset if the year-directory
;; filename signal were ever lost. A leading `v` would pollute the `id LIKE 'v%'` version scans that older
;; binaries use for downgrade detection and rollback.
(year-dir-migration-file? file)
(let [ids (change-set-ids change-log)
;; the ISO date/timestamp the versioned ids were built from (`v50.2024-03-18T16:00:00`): checked first so
;; the habit gets its own message rather than a generic character-set complaint
iso-date-id? (fn [id] (and (string? id) (re-find #"\d{4}-\d{2}-\d{2}" id)))
dated-ids (filter iso-date-id? ids)
bad-ids (remove valid-version-less-id? ids)]
(when (seq dated-ids)
(throw (validation-error
(format (str "Migration file contains changeset IDs that look like dates or timestamps; a version-less "
"ID names the change instead (the file name already carries the date): %s")
(str/join ", " dated-ids))
{:date-like-ids (vec dated-ids)})))
(when (seq bad-ids)
(throw (validation-error
(format (str "Migration file contains invalid changeset IDs (use a version-less ID: lowercase "
"letters/digits/underscores with at least one letter, no leading 'v', and no "
"timestamp or version prefix): %s")
(str/join ", " bad-ids))
{:invalid-ids (vec bad-ids)}))))
(directory-based-migration-file? file)
(let [ids (change-set-ids change-log)
bad-ids (remove #(and (string? %) (re-matches directory-based-id-format-re %)) ids)]
(when (seq bad-ids)
(throw (validation-error
(format "Directory-based migration file contains IDs without v{version}. prefix: %s"
(str/join ", " bad-ids))
{:invalid-ids (vec bad-ids)}))))
(not= (file-version file) 1)
(let [ids (change-set-ids change-log)
bad-ids (remove #(re-matches change-set.strict/id-timestamp-format-re %) ids)]
(when (seq bad-ids)
(throw (validation-error
(format "Per-release migration file contains non-timestamp ID formats: %s"
(str/join ", " bad-ids))
{:invalid-ids (vec bad-ids)}))))))
(def ^:private table-scoped-preconditions
"Existence preconditions mapped to the key that scopes them to a single table. Without that key,
Liquibase answers the check by snapshotting the whole schema — ~2 seconds per precondition on a
large postgres appdb, which is how 27 name-only preconditions once added ~50s to every full
migration."
{:primaryKeyExists :tableName
:indexExists :tableName
:uniqueConstraintExists :tableName
:foreignKeyConstraintExists :foreignKeyTableName})
(defn- unscoped-preconditions
"Walk a preConditions tree (maps nested under and/or/not, in either flat-map or list form) and
return [precondition-key required-key] pairs for every table-scoped existence check that is
missing its table key."
[form]
(cond
(map? form) (concat
(for [[precondition required] table-scoped-preconditions
:let [check (get form precondition)]
:when (and (map? check) (not (contains? check required)))]
[precondition required])
(mapcat unscoped-preconditions (vals form)))
(sequential? form) (mapcat unscoped-preconditions form)
:else nil))
(defn require-table-scoped-existence-preconditions
"Ensures that primaryKeyExists/indexExists/uniqueConstraintExists preconditions specify a
tableName, and foreignKeyConstraintExists a foreignKeyTableName."
[change-log]
(doseq [{:keys [changeSet]} change-log
:when changeSet
:let [[precondition required] (first (unscoped-preconditions (:preConditions changeSet)))]
:when precondition]
(throw (validation-error
(format "Migration '%s' has %s precondition without %s: without it Liquibase snapshots the entire schema to answer the check (~2s per precondition on a large postgres appdb)"
(:id changeSet) (name precondition) (name required))
{:id (:id changeSet)}))))
(defn require-no-run-always
"Refuses `runAlways: true` changesets. Liquibase lists a runAlways changeset as unrun on every update, which breaks
how Metabase runs and tracks migrations:
1. Every boot of every instance finds an unrun changeset, so it takes the migration lock and runs a migration. Each
run records a new deployment, adds a `databasechangelog_version` row and moves the legacy-version-tracking
marker row.
2. With `MB_DB_AUTOMIGRATE=false`, Metabase prints the migration SQL and refuses to start on every boot, even
after the SQL has been applied, because the changeset is still unrun.
3. Each run moves the changeset's changelog row into its own deployment. The deployment of the run before is then
left with no changelog rows, but its `databasechangelog_version` row stays until a rollback removes it: one more
row per boot.
4. An older patch booted against a newer patch's schema runs it too, so the newest deployment looks like it was
run by the older patch (the `migrate down` guard has to look at every deployment because of this).
Use `runOnChange` for objects that must follow their definition (views). To allow runAlways, first make
`metabase.app-db.liquibase/unrun-migrations` and the `migrate print` path ignore runAlways changesets when they
decide whether there is work to do (run them only with other migrations, or in a separate step that records no
deployment), and remove the version rows of deployments that a re-run leaves empty when it happens, not only at
rollback; then run the upgrade, downgrade and `MB_DB_AUTOMIGRATE=false` scenarios again."
[change-log]
(doseq [{:keys [changeSet]} change-log
:when (true? (:runAlways changeSet))]
(throw (validation-error
(format (str "Migration '%s' uses runAlways, which Metabase does not support: every boot would run it as a "
"new migration, and with MB_DB_AUTOMIGRATE=false Metabase would never start. See "
"require-no-run-always in bin/lint-migrations-file.")
(:id changeSet))
{:id (:id changeSet)}))))
(s/def ::changeSet
(s/spec :change-set.strict/change-set))
(defn- only-key [m]
(let [keys (keys m)]
(when-not (= 1 (count keys))
(throw (validation-error "Expected exactly one key." {:keys keys})))
(first keys)))
(defn- major-version
"Returns major version from id string, e.g. 44 from \"v44.00-034\".
For directory-based migrations (file path matches `NNN/`), extracts
version from the file path. Otherwise parses from the id string.
Returns nil for year-based directories, whose IDs are version-less and not tied to a version."
[id-str file]
(cond
(and file (year-dir-migration-file? file))
nil
(string? id-str)
(if-let [[_ file-version] (when file (re-find #"(\d{3})[/\\]" (str file)))]
(Integer/parseInt file-version)
(some-> (re-find #"\d+" id-str) Integer/parseInt))
:else
(when-let [[_ file-version] (when file (re-find #"(\d{3})[/\\]" (str file)))]
(Integer/parseInt file-version))))
(def first-versionless-major
"The first Metabase major whose changesets must all be version-less: they live in a year-based directory with a version-less ID"
67)
(defn- require-no-versioned-changesets-from-first-versionless-major
"Ensures no `vNN.`-prefixed changeset for [[first-versionless-major]] or later exists, whichever kind of versioned
file it is in. Year-based directories are exempt: their IDs are version-less by construction."
[change-log file]
(when-not (year-dir-migration-file? file)
(let [versioned-ids (filter #(some-> (major-version % file) (>= first-versionless-major))
(change-set-ids change-log))]
(when (seq versioned-ids)
(throw (validation-error
(str "Versioned changesets are not allowed from v" first-versionless-major " on; add new changesets "
"to a year-based directory (e.g. migrations/2026/) with version-less IDs: "
(str/join ", " versioned-ids))
{:versioned-ids (vec versioned-ids)
:first-versionless-major first-versionless-major}))))))
(def change-types-supporting-rollback
"This set was generated with a little grep and awk from the docs here:
https://docs.liquibase.com/workflows/liquibase-community/liquibase-auto-rollback.html
If a new change type is introduced that supports automatic rollback, it should be added
to this set."
#{:addCheckConstraint
:addColumn
:addDefaultValue
:addForeignKeyConstraint
:addLookupTable
:addNotNullConstraint
:addPrimaryKey
:addUniqueConstraint
:createIndex
:createSequence
:createSynonym
:createTable
:createView
:disableCheckConstraint
:disableTrigger
:dropNotNullConstraint
:enableCheckConstraint
:enableTrigger
:renameColumn
:renameSequence
:renameTable
:renameTrigger
:renameView
;; assumes all custom changes use the `def-migration` or `define-reversible-migration` in
;; [[metabase.app-db.custom-migrations]]
:customChange})
(defn- rollback-present-when-required?
"Ensures rollback key is present when change type doesn't support auto rollback.
`file` is used to extract version for directory-based migrations."
[{:keys [id changes] :as change-set} file]
(or
(let [v (major-version (str id) file)]
(and v (< v 45)))
(some change-types-supporting-rollback (mapcat keys changes))
(contains? change-set :rollback)))
(defn- validate-database-change-log [change-log file]
(when (string? change-log)
(throw (validation-error "Expected `:databaseChangeLog` to be a map, not a string.")))
(require-distinct-change-set-ids change-log)
(require-change-set-ids-in-correct-file change-log file)
(require-no-versioned-changesets-from-first-versionless-major change-log file)
(require-change-set-ids-in-order change-log file)
(require-change-set-ids-match-file-format change-log file)
(require-no-bare-blob-or-text-types change-log)
(require-no-bare-boolean-types change-log file)
(require-no-datetime-type change-log file)
(require-entity-id-type change-log file)
(require-table-scoped-existence-preconditions change-log)
(require-no-run-always change-log)
(let [{:keys [changeSet]
:as all} (group-by only-key change-log)]
(when-not (set/subset? (set (keys all)) #{:property :objectQuotingStrategy :changeSet :logicalFilePath})
(throw (validation-error "Expected exactly one of :property, :objectQuotingStrategy, :logicalFilePath, or :changeSet."
{:keys (keys all)})))
(doseq [{:keys [changeSet]} changeSet]
(when-not (s/valid? ::changeSet changeSet)
(throw (validation-error "Invalid change set." (s/explain-data ::changeSet changeSet))))
(when-not (rollback-present-when-required? changeSet file)
(throw (validation-error "Rollback is required but not present."
{:id (:id changeSet)}))))))
(defn- validate-migrations [migrations file]
(require-database-change-log! migrations)
(validate-database-change-log (:databaseChangeLog migrations) file)
:ok)
(defn- migration-files []
;; kondo can't parse the :bb reader-conditional branch and mangles the surrounding let
#_{:clj-kondo/ignore [:unresolved-symbol :unused-binding :syntax]}
(let [dir-str #?(:bb "resources/migrations" :clj "../../resources/migrations")
dir (io/file dir-str)]
(->> (file-seq dir)
(filter (fn [^java.io.File f]
(and (.isFile f)
(or
;; Per-release files: 059_update_migrations.yaml
(str/ends-with? (.getName f) "_update_migrations.yaml")
;; Directory-based files: 060/20260106_125531.yaml
(directory-based-migration-file? f)))))
(sort-by str))))
(defn- migrations [file]
(assert (.exists file) (format "%s does not exist" file))
(letfn [(fix-vals [x]
;; convert any lazy seqs to regular vectors and maps
(cond (map? x) (update-vals x fix-vals)
(sequential? x) (mapv fix-vals x)
:else x))]
(fix-vals (yaml/parse-string
;; false unresolved-symbol from kondo's :cljs pass; this cljc is :clj+:bb only
#_{:clj-kondo/ignore [:unresolved-symbol]} (slurp file)))))
(defn- display-name
"Returns a human-readable name for a migration file.
For per-release files, returns just the filename.
For directory-based files, returns `parent/filename`."
[^java.io.File file]
(if (directory-based-migration-file? file)
(str (.getName (.getParentFile file)) "/" (.getName file))
(.getName file)))
(defn- validate-all []
(doseq [file (migration-files)]
(println "Validating" (display-name file) "...")
(try
(validate-migrations (migrations file) file)
(catch ExceptionInfo e
(throw (ex-info (.getMessage e) (assoc (ex-data e) :file (display-name file)) e))))))
(defn -main
"Entry point for Clojure CLI task `lint-migrations-file`. Run it with
./bin/lint-migrations-file.sh"
[]
(println "Check Liquibase migrations files...")
(try
(validate-all)
(println "Ok.")
;; false unresolved warning from kondo's :cljs pass; this cljc is :clj+:bb only
#_{:clj-kondo/ignore [:unresolved-namespace]}
(System/exit 0)
(catch ExceptionInfo e
(if (validation-error? e)
(do
(println)
;; false unresolved-symbol from kondo's :cljs pass; this cljc is :clj+:bb only
#_{:clj-kondo/ignore [:unresolved-symbol]}
(printf "Error in %s:\t%s\n" (:file (ex-data e)) (.getMessage e))
(printf "Details:\n\n %s" (with-out-str (pprint/pprint (dissoc (ex-data e) ::validation-error))))
(println))
(do
(pprint/pprint (Throwable->map e))
(println (.getMessage e))))
(System/exit 1))
;; false unresolved-symbol from kondo's :cljs pass; this cljc is :clj+:bb only
(catch #_{:clj-kondo/ignore [:unresolved-symbol]}
Throwable e
(pprint/pprint (Throwable->map e))
(println (.getMessage e))
(System/exit 1))))