Skip to content

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

6.3 KB
Raw Blame
(ns metabase-enterprise.serialization.models.entity-id-test
  "To support serialization, all exported entities should have either an external name (eg. a database path) or a
  generated NanoID in a column called entity_id. There's a property :entity_id to automatically populate that field.

  This file makes it impossible to forget to add entity_id to new entities. It tests that every entity is either
  explicitly excluded, or has the :entity_id property."
  (:require
   [clojure.test :refer :all]
   [metabase-enterprise.serialization.v2.models :as serdes.models]
   [metabase.classloader.core :as classloader]
   [metabase.models.resolution :as models.resolution]
   [metabase.models.serialization :as serdes]))

(set! *warn-on-reflection* true)

(def ^:private entities-external-name
  "Entities with external names, so they don't need a generated entity_id."
  #{:model/Channel
    ;; CustomVizPlugins have unique identifiers.
    :model/CustomVizPlugin
    ;; Databases have external names based on their URLs; tables are nested under databases; fields under tables.
    :model/Database
    :model/Table
    :model/Field
    :model/FieldValues
    :model/FieldUserSettings
    :model/TableUserSettings
    ;; Settings have human-selected unique names.
    :model/Setting})

(def ^:private entities-not-exported
  "Entities that are either:
  - not exported in serialization; or
  - exported as a child of something else (eg. timeline_event under timeline)
  so they don't need a generated entity_id."
  #{:model/AgentApiCallLog
    :model/AiUsageLog
    :model/AnalysisFinding
    :model/AnalysisFindingError
    :model/AnalysisFindingStatus
    :model/ApiKey
    :model/ApiKeyUsageLog
    :model/AuthIdentity
    :model/ImplicitAction
    :model/QueryAction
    :model/ApplicationPermissionsRevision
    :model/AuditLog
    :model/BookmarkOrdering
    :model/CacheConfig
    :model/CardBookmark
    :model/ChannelTemplate
    :model/CollectionBookmark
    ;; Content Diagnostics findings are scan-snapshot runtime data (its `entity_id` column is a
    ;; polymorphic reference to the flagged entity, not a serdes NanoID) -- not portable content.
    :model/ContentDiagnosticsFinding
    :model/ContentTranslation
    :model/DashboardBookmark
    :model/DataComplexityScore
    :model/DataPermissions
    :model/DatabaseRouter
    :model/Dependency
    :model/DependencyStatus
    :model/DocumentBookmark
    :model/EmbeddingSdkReact18Host
    :model/Exploration
    :model/ExplorationBookmark
    :model/ExplorationQuery
    :model/ExplorationQueryResult
    :model/ExplorationThread
    :model/ExplorationBlock
    :model/ExplorationPage
    :model/ExplorationThreadTimeline
    :model/StoredResult
    :model/StoredResultUse
    :model/CollectionPermissionGraphRevision
    :model/DashboardCardSeries
    :model/LoginHistory
    :model/McpFeedback
    :model/McpGroupPermission
    :model/McpQueryHandle
    :model/McpSessionLog
    :model/McpToolCallLog
    :model/FieldValues
    :model/MetabotConversation
    :model/MetabotFeedback
    :model/MetabotGroupLimit
    :model/MetabotInstanceLimit
    :model/MetabotMessage
    :model/MetabotPermissions
    :model/MetabotSourceFeedback
    :model/MetabotUsedTable
    :model/ModelIndex
    :model/ModelIndexValue
    :model/ModerationReview
    :model/Notification
    :model/NotificationCard
    :model/NotificationSubscription
    :model/NotificationHandler
    :model/NotificationRecipient
    :model/OAuthAccessToken
    :model/OAuthAuthorizationCode
    :model/OAuthClient
    :model/OAuthClientEvent
    :model/OAuthRefreshToken
    :model/ParameterCard
    :model/Permissions
    :model/PermissionsGroup
    :model/PermissionsGroupMembership
    :model/PermissionsRevision
    :model/PersistedInfo
    :model/PremiumFeaturesCache
    :model/Pulse
    :model/PulseCard
    :model/PulseChannel
    :model/PulseChannelRecipient
    :model/Query
    :model/QueryCache
    :model/QueryExecution
    :model/QueryField
    :model/QueryTable
    :model/RecentViews
    :model/ReplacementRun
    :model/RemoteSyncObject
    :model/RemoteSyncTask
    :model/ResultMetadataStatus
    :model/Revision
    :model/SemanticSearchTokenTracking
    :model/SearchIndexMetadata
    :model/Secret
    :model/Session
    :model/SourceDimensionDaily
    :model/SourceDimensionProfileDaily
    :model/SourceMetricDaily
    :model/SourceSegmentCompositeDaily
    :model/SourceSegmentDaily
    :model/SsoRelayState
    :model/SupportAccessGrantLog
    :model/TableIndex
    :model/TaskHistory
    :model/TaskRun
    :model/Tenant
    :model/TimelineEvent
    ;; Run history is intentionally not serialized.
    :model/TransformTestRun
    ;; TODO we should remove these models from here once serialization is supported
    :model/TransformRun
    :model/TransformRunCancelation
    :model/TransformDagRun
    :model/TransformJobRun
    :model/TransformJobTransformTag
    :model/TransformTransformTag
    :model/Undo
    :model/User
    :model/UserParameterValue
    :model/UserKeyValue
    :model/ViewLog
    :model/Sandbox
    :model/ConnectionImpersonation
    :model/ImpersonationQueryCache
    :model/SecurityAdvisory
    :model/CloudMigration
    :model/Comment
    :model/CommentReaction})

(deftest ^:parallel comprehensive-entity-id-test
  (let [entity-id-models (->> (keys models.resolution/model->namespace)
                              (remove entities-not-exported)
                              (remove entities-external-name))]
    (testing "All exported models should get entity id except those with other unique property (like name)"
      (is (= (set (concat serdes.models/exported-models
                          ;; those are inline models which still have entity_id
                          ["DashboardCard" "DashboardTab" "Dimension" "MetabotPrompt" "FieldUserSettings"]))
             (set (->> (concat entity-id-models
                               entities-external-name)
                       (map name))))))
    (doseq [model entity-id-models]
      (testing (format (str "Model %s should either: have the ::mi/entity-id property, or be explicitly listed as having "
                            "an external name, or explicitly listed as excluded from serialization")
                       model)
        ;; the property is registered by the model's own namespace, which nothing else here loads
        (classloader/require (models.resolution/model->namespace model))
        (is (serdes/has-entity-id? model))))))